将字符串元素从类添加到字符串数组

时间:2018-03-27 07:16:41

标签: ios arrays swift google-cloud-firestore

我有class,其中包含变量hall和其他变量。我需要拉出并在新的字符串数组中添加变量hall

现在所有变量都存储在类型为BookingHall的变量中。

如何获取变量hall并将其添加到新变量?

我使用的所有内容firestore

我的班级实施:

protocol BookingDocumentSerializable {

    init?(dictionary: [String:Any])

}

struct BookingHall {

    var contactInfo: [String: Any] = [:]
    ................
    var hall: String = ""

    var dictionary: [String: Any] {

        return [

            "contact_info": contactInfo,
            ................
            "hall": hall

        ]
    }
}

extension BookingHall: BookingDocumentSerializable {

    init?(dictionary: [String: Any]) {

        let contactInfo = dictionary["contact_info"] as? [String: Any] ?? [:]
        ................
        let hall = dictionary["hall"] as? String ?? ""

        self.init(contactInfo: contactInfo,
                  ................
                  hall: hall)

    }
}

我在课堂上获得所有变量:

var hallArray: [String] = []

private var historyBooking: [BookingHall] = []

fileprivate func observeQuery() {

    guard let query = query else { return }

    listener = query.addSnapshotListener { [unowned self] (snapshot, error) in

        if let snapshot = snapshot {

            let bookingModel = snapshot.documents.map { (document) -> BookingHall in

                if let newHistoryBooking = BookingHall(dictionary: document.data()) {

                    return newHistoryBooking

                } else {

                    fatalError("Ошибка загрузки!")

                }
            }

            self.historyBooking = bookingModel
            self.document = snapshot.documents

            for index in 0...self.historyBooking.count {

                self.hallArray.append(self.historyBooking[index].hall)

                print("hall id \(self.hallArray)")

            }

            self.tableView.reloadData()

        }
    }
}

在这里我收到错误index out of range,但在控制台中我可以看到hall id

self.hallArray.append(self.historyBooking[index].hall)

如何在{... p>中将hall正确添加到新的字符串数组中

var hallArray: [String] = []

2 个答案:

答案 0 :(得分:2)

一个非常常见的错误。

索引从零开始。想象一下你的数组有一个元素。范围0...array.count包含索引01,但索引1处没有元素...

你必须写

for index in 0..<self.historyBooking.count

for index in 0...self.historyBooking.count - 1

第一种语法更可取。

答案 1 :(得分:0)

要避免Index out of bound,您可以使用for...in循环

for obj in 0...self.historyBooking.count {

  self.hallArray.append(obj.hall)

  print("hall id \(self.hallArray)")

}