输入任何?没有下标成员 [英] type any? has no subscript members

查看:35
本文介绍了输入任何?没有下标成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从配置文件字典中获取地址,但出现错误输入任何内容?没有下标成员"

I want to get Addresses from profile dictionary,but I got the error "type any? has no subscript members"

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

我如何修复它并获取地址?非常感谢.

How can I fix it and get the address? Thanks a lot.

推荐答案

当您使用 "Addresses" 对配置文件进行下标时,您将返回一个 Any 实例.您选择使用 Any 来适应同一数组中的各种类型会导致类型擦除发生.您需要将结果转换回它的真实类型,[[String: Any]] 以便它知道 Any 实例代表一个 Array.然后你就可以给它下标了:

When you subscript profile with "Addresses", you're getting an Any instance back. Your choice to use Any to fit various types within the same array has caused type erasure to occur. You'll need to cast the result back to its real type, [[String: Any]] so that it knows that the Any instance represents an Array. Then you'll be able to subscript it:

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])
}

虽然这很笨拙,而且首先使用字典并不是一个非常合适的情况.

This is very clunky though, and it's not a very appropriate case to be using Dictionaries in the first place.

在这种情况下,您的字典具有一组固定的键,结构是更合适的选择.它们是强类型的,因此您不必从 Any 上下转换,它们具有更好的性能,并且更易于使用.试试这个:

In such a situation, where you have dictionaries with a fixed set of keys, structs are a more more appropriate choice. They're strongly typed, so you don't have to do casting up and down from Any, they have better performance, and they're much easier to work with. Try this:

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!

这篇关于输入任何?没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆