简体   繁体   中英

Reference to member 'subscript' cannot be resolved without a contextual type

I need to convert an array of strings to integers.

import UIKit

var test = ["1", "2"]
let test1 = Int(test)[0]
let test2 = Int(test)[1]
print(test1 + test2)

^ this is the basic idea of what I'm trying to do, but I get "Reference to member 'subscript' cannot be resolved without a contextual type". Is this even possible?

Try using the subscript on the test array, rather than on the result of Int initializer:

var test = ["1", "2"]
let test1 = Int(test[0])
let test2 = Int(test[1])

However, you can achieve what you are trying in an more swifty way:

var test = ["1", "2"]
print(test.compactMap(Int.init).reduce(0, +))

Or with just reduce(_:_:) :

var test = ["1", "2"]
print(test.reduce(0) { $0 + (Int($1) ?? .zero) })

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