KevM KevM - 2 years ago 74
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download