简体   繁体   中英

Correct syntax for reading from a nested array in Swift?

Essentially I'm trying to grab in integer from an 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.

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. That way you can lose that final cast to Int type.

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.

(As Matt says in his comment, if the first conditional cast fails, your dfa variable will be nil.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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