简体   繁体   English

在Swift中从嵌套数组读取的正确语法?

[英]Correct syntax for reading from a nested array in Swift?

Essentially I'm trying to grab in integer from an Array -> Dictionary -> Array -> Int. 本质上,我试图从Array-> Dictionary-> Array-> Int中获取整数。 What I have produces no console errors and compiles fine, but always returns 0. I think my syntax is wrong but I'm not sure of the correct way to rewrite it. 我没有产生任何控制台错误,并且可以正常编译,但始终返回0。我认为我的语法错误,但是我不确定重写它的正确方法。

convenience init(fromDict dict: [String: Any]) {
    let dfa = dict["forms"] as? Array<Dictionary<String,Array<Any>>>
    self.init(
        heart: dfa?[0]["abilities"]?[0] as? Int ?? 0
    )
}

<array> <dict> <key>forms</key> <array> <dict> <key>abilities</key> </array> <integer>65</integer> </array>

Your syntax looks ok to me, although I would suggest making the inner array contain Int rather than Any if it will always contain ints. 您的语法对我来说还可以,尽管我建议使内部数组包含Int而不是Any如果它始终包含int)。 That way you can lose that final cast to Int type. 这样,您就可以将最终的转换类型丢失为Int类型。

If either of your conditional casts fails then you'll get nil, and the nil coalescing operator will convert your nil into a 0. I suggest writing debug code that logs the object passed into your init method, and then casting one thing at a time and stepping through to see where it fails. 如果您的任何一个条件转换都失败,那么您将得到nil,并且nil合并运算符会将您的nil转换为0。我建议编写调试代码,将传递给该对象的对象记录到您的init方法中,然后一次转换一件事并逐步查看失败的地方。

(As Matt says in his comment, if the first conditional cast fails, your dfa variable will be nil.) (正如Matt在评论中所说,如果第一个条件转换失败,则您的dfa变量将为nil。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM