swift - 如何将 "Text(example1: "ex 1", example2: "ex 2")"转换为可用的字典

标签 swift xcode dictionary

我真的是编程新手,我正在构建一个关于运动和位置的应用程序。我无法从“词典”中获取特定项目,但“词典”并不是真正的词典。

基本上,我有一个 TableView ,其中包含从我的 Firebase Firestore 数据集中获取的数据行,在点击一行之后,我想将该行的数据带到另一个场景。

我试过搜索类似的问题,但是输出

Person(name: "Test3", zip: "33333", sport: "Tennis", email: "test3@email.com")

(from print(tappedRow)) 在我尝试 let tappedEmail = tappedRow[3] 时没有下标

我还尝试通过 let tappedRow: Dictionary = peopleView.people[number] as! 将 tappedRow 转换为字典!字典,但是说这总是失败并给出错误

Cannot convert value of type 'Person' to type 'Dictionary<_, _>' in coercion

主要部分代码如下:

let number = myIndex
let tappedRow = peopleView.people[number]
print (tappedRow)
let tappedEmail = tappedRow[3]      <- Value of type 'Person' has no subscripts

print(tappedEmail)

let tappedUser = FirebaseFirestore.root.collection("users").document(tappedEmail)

peopleView 是这样的:

var myIndex = 0
var selectedPerson = ""

struct Person {
    let name, zip, sport, email: String
}


class PeopleViewController: UITableViewController {

    @IBOutlet var table: UITableView!

    var people = [Person]() as Dictionary
    private var document: [DocumentSnapshot] = []

    override public func viewDidLoad() {
        super.viewDidLoad()

        peopleView = self

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = people[indexPath.row]
        let cell = self.table.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell

        cell.name.text = person.name
        cell.sport.text = person.sport
        cell.zip.text = person.zip
        cell.email.text = person.email

        return cell
    }

    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        myIndex = indexPath.row

        performSegue(withIdentifier: "toTappedUser", sender: self)
    }

我期望的是它会获取点击的行,并从字典集中获取“电子邮件”,并使用它从 Firebase 调用 getDocument。实际发生的是我收到此错误:

Value of type 'Person' has no subscripts

我认为原因是因为 Person(name: "Test3", zip: "33333", sport: "Tennis", email: "test3@email.com") 不是真的一个字典,因为开头的 Person,所以我想以某种方式将它转换成一个真正的字典,然后从中获取 email

我对 firebase 和 swift 还很陌生,所以非常感谢任何帮助。

最佳答案

不要改变任何东西。请尝试理解错误

Cannot convert value of type 'Person' to type 'Dictionary<_, _>' in coercion

表示 PersonDictionary 无关。无论如何,桥接转换毫无意义,因为自定义结构比字典更具体

var people = [Person]()

Type Person has no subscripts

自定义结构默认没有下标。而且按索引下标无论如何都是错误的。查看cellForRowAt中的代码,例如获取结构成员值的正确方法

let tappedEmail = tappedRow.email

请阅读Language Guide学习基础知识。

关于swift - 如何将 "Text(example1: "ex 1", example2: "ex 2")"转换为可用的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735274/

相关文章:

python - 我可以使用集合理解从更大的字典列表中创建字典列表吗?

swift - Swift中 `try`关键字的用途是什么?

swift - 保存 UIImage 数组以解析为一个文件

swift - "invalid signature"JWT token Opentok

ios - 以编程方式更改为 SwiftUI 中的另一个选项卡

iOS权限提示问题

ios - 首次启动/已登录 Storyboard View Controllers Swift

创建嵌套字典的 Pythonic 方式

ios - 如何使数字不重复超过 2 次?

Python:创建列表列表作为字典值