Unwrapping optional properties from an optional array of objects I'm currently working with an SDK where methods return an optional array of objects with optional properties.  Only the array itself is optional, it will either be nil or always contain non-optionals.  I'm struggling to find a cleaner way to unwrap optional properties for each non-optional in the array:

class Person {
    var id: String?
}

func someOptionalArrayOfPeople() -&gt; [Person]? {
    // returns either nil or some array of Person objects
}

let people = someOptionalArrayOfPeople()

if let unwrappedPeople = people {

    // 1
    for person in unwrappedPeople {
        if let id = person.id {
            print(id) // too many nested statements
        }
    }

    // 2
    for person in unwrappedPeople where person.id != nil {
        print(person.id!) // stil force unwrapping
    }
}


For option 1, I'm not thrilled about unwrapping the initial optional array, and I feel that there should be a way to skip the unwrapping of the id.  Option 2 attempts to do that with a where clause, but the compiler isn't smart enough to determine that person.id is non-nil even if we explicitly check that id != nil.

What are my "Swifty" options for unwrapping optional properties on an optional array of objects?  I am using Swift 2.2 with Xcode 7.3.1.
There are several options, but in any case you can use

public func flatMap&lt;T&gt;(@noescape transform: (Self.Generator.Element) throws -&gt; T?) rethrows -&gt; [T]


which returns an array containing the non-nil results of applying the
transformation to all sequence elements.

For example

if let unwrappedPeople = people {
    for id in unwrappedPeople.flatMap({ $0.id }) {
        print(id)
    }
}


to iterate over the non-nil ids, or 

if let unwrappedPeople = people {
    let ids = unwrappedPeople.flatMap { $0.id }
    print(ids)
}


to get the non-nil ids as an array.

To get rid of the outer unwrapping/optional binding, you can use
optional chaining:

people?.flatMap({ $0.id }).forEach {
    print($0)
}


If people is nil, then flatMap() is not applied. Otherwise
it returns an array of the non-nil ids, which are enumerated with
forEach().

I think that all these methods (as well as your first method) are "Swifty",
you have to decide how compact your code should be.