一尘不染

输入任何?没有下标成员

swift

我想从个人资料字典中获取地址,但出现错误“输入任何类型?没有下标成员”

var address:[[String : Any]] = [["Address": "someLocation", "City": "ABC","Zip" : 123],["Address": "someLocation", "City": "DEF","Zip" : 456]]
var profile:[String : Any] = ["Name": "Mir", "Age": 10, "Addresses": address]
profile["Addresses"][0]     <-----------------type any? has no subscript members

我该如何解决并获取地址?非常感谢。


阅读 208

收藏
2020-07-07

共1个答案

一尘不染

当您使用下标配置文件时"Addresses",您将获得一个Any实例。您选择使用Any适合同一数组中的各种类型已导致发生类型擦除。您需要将结果转换回其实型,[[String: Any]]以便它知道Any实例代表Array。然后,您可以对其进行下标:

func f() {
    let address: [[String : Any]] = [["Address": "someLocation", "City": "ABC","Zip" : 123],["Address": "someLocation", "City": "DEF","Zip" : 456]]
    let profile: [String : Any] = ["Name": "Mir", "Age": 10, "Addresses": address]

    guard let addresses = profile["Addresses"] as? [[String: Any]] else {
        // Either profile["Addresses"] is nil, or it's not a [[String: Any]]
        // Handle error here
        return
    }

    print(addresses[0])
}

但是,这非常笨拙,并且一开始就使用Dictionary并不是一个非常合适的情况。

在这种情况下,如果词典中有一组固定的键,则结构是更合适的选择。它们的类型很严格,因此您不必从上或下进行转换Any,它们具有更好的性能,并且更易于使用。试试这个:

struct Address {
    let address: String
    let city: String
    let zip: Int
}

struct Profile {
    let name: String
    let age: Int
    let addresses: [Address]
}

let addresses = [
    Address(
        address: "someLocation"
        city: "ABC"
        zip: 123
    ),
    Address(
        address: "someLocation"
        city: "DEF"
        zip: 456
    ),
]

let profile = Profile(name: "Mir", age: 10, addresses: addresses)

print(profile.addresses[0]) //much cleaner/easier!
2020-07-07