0

Having array of employee object, called employees and now I want to create another array called filteremployees which is having only id and date of birth value. Using let filteremployees = employee.map({ $0.id}) I can get array which contains only id value but i want to have id as well dateOfBirth

class Employee {

    var id: Int
    var firstName: String
    var lastName: String
    var dateOfBirth: NSDate?

    init(id: Int, firstName: String, lastName: String) {
        self.id = id
        self.firstName = firstName
        self.lastName = lastName
    }
}
2
  • are you trying to loop through the one array and add filtered data into another array? Commented Sep 26, 2015 at 12:30
  • @Jatin: One suggestion: Employee is a good candidate for being a struct here. And the properties are good candidates for being declared with let instead of var. Look a what Abizern has done with the FilteredEmployee struct. Commented Sep 26, 2015 at 12:50

2 Answers 2

2

Try this:

let employees : [Employee] = ...
let list: [(Int, NSDate?)] = employees.map { ($0.id, $0.dateOfBirth) }

You must explicitly declare the type of list otherwise you get this error from the compiler

Type of expression is ambiguous without more context.

Tested with Xcode 7 Playground and Swift 2.0.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

You could try using the same map method and returning a tuple of your expected values:

let filter employees: [(Int, NSDate?)] = employee.map({ ($0.id, $0.dateOfBirth) })

Alternatively, and I think this is a better solution, create a new value type and create that with only your required values

struct FilteredEmployee {
    let id: String
    let dateOfBirth: NSDate?

    init(employee: Employee) {
        id = employee.id
        dateOfBirth = employee.dateOfBirth
    }
}

And then you can map the initialiser over the array

    let filteremployees = employee.map { FilteredEmployee($0) }

1 Comment

I was trying the same solution, but your first block of code does not compile.

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.