1

I have a class called Person:

class Person {

    var firstName: String?
    var lastName: String?
    let birthPlace = "Belgium"

}


let person = [Person]()

Now the problem is I want to get all first names into a String array ([String]), how can I do it?

1
  • 1
    Why are firstName and lastName optional? In practice everybody has a first and last name. Don't use optionals as an alibi not to write an initializer. That's very bad habit. Commented Sep 12, 2017 at 12:20

2 Answers 2

1

you can use flatMap for that:

let firstName = person.flatMap{ return $0.firstName }
Sign up to request clarification or add additional context in comments.

2 Comments

Why flatMap? The array is not nested in any way.
flatMap will create an array of non-optional strings [String], that's what OP asked for. The firstName property is an optional (String?), so the result of map{ return $0.firstName} will be [String?].
0

First of all, you should rewrite your Person class. firstName and lastName shouldn't be optional, since everyone has both a first and a last name and unless your app will specifically be made for people who were born in Belgium, hardcoding that as the birthPlace is also a bad idea.

Take the time and write an initializer for the class.

class Person {
    var firstName: String
    var lastName: String
    let birthPlace: String

    init(firstName: String, lastName: String, birthPlace: String){
        self.firstName = firstName
        self.lastName = lastName
        self.birthPlace = birthPlace
    }
}

You can use map to get an array of first names from an array of Person objects.

let people = [Person]()
let firstNames = people.map{$0.firstName}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.