Kaunteya Kaunteya - 1 year ago 91
Swift Question

Array transform having failable initialiser

I am using Swift 1.2 in Xcode 6.3.1

Following is my


struct Person {
let age: Int
init?(age: Int) { //Failable init
if age > 100 { return nil }
self.age = age

I am having a list of ages against which I have to make Person Objects.

I have made playground file.

let arr = Array(1...150) //Sample set of ages against which Person is created
var personList: [Person]!


personList = arr.map({ (val: Int) -> Person? in
return Person(age: val) //Makes object of type Person?
}).filter {
$0 != nil
}.map {
return $0!

Here I have uses
map - filter - map
because the first map invokes failable intializer, (hence it returns Person?) and
is of type

Hence second function filters all the non nil objects and third map forcefully opens to optional therby making Person? to Person.

Is there a more easy/readable way out ? Chaining map-filter-map definitely seems to be an overkill for this

Answer Source

You can use flatMap to get rid of any nils in the array, this tutorial discusses the method in length, but the following will work best:

let personList = arr.flatMap { Person(age: $0) }

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