KevM KevM - 1 year ago 40
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 {
return result


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 = { Optional($0) }

Edit: Code modified based on suggestions in comments.