KevM KevM - 6 months ago 13
Swift Question

Simple way to convert an array of non-optionals to an array of optionals

I wish to assign an array [T] to an optional array [T?]. This seems like it should be straightforward but the only solution I came up with is to do it manually.

struct ArrayHelper<T> {
func toArrayOfOptionals(input: [T]) -> [T?] {
var result = [T?]()
for value in input {
result.append(value)
}
return result
}
}

Answer

I don't think there are any built-in ways to do this seamlessly, but map ought to be a simpler solution:

var input = [T]()
let output = input.map { Optional($0) }

Edit: Code modified based on suggestions in comments.