-1

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?

dsneedy
  • 3
  • 1
  • 2

1 Answers1

0

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) })
gcharita
  • 7,729
  • 3
  • 20
  • 37
  • 1
    or in a single iteration `test.reduce(0){ $0 + (Int($1) ?? .zero)}` – Leo Dabus Nov 17 '20 at 19:09
  • 1
    @LeoDabus hm, that's better. Thank you. – gcharita Nov 17 '20 at 19:12
  • why should one use `.zero` over `0` here? – Clashsoft Nov 17 '20 at 19:18
  • @Clashsoft there is no difference in this case. `.zero` is only needed when the actual type is not known https://stackoverflow.com/a/58420510/2303865. I prefer using `.zero` instead of `0` just for better readability. In fact it is just my opinion. Use whatever you feel comfortable with. – Leo Dabus Nov 17 '20 at 19:20