Search code examples
iosswift

How to mutate structs in Swift using map?


I have the following struct defined.

struct Person {

    var firstName :String
    var lastName :String
    var active :Bool
}

I have created a collection of Person as shown below:

var persons :[Person] = []

for var i = 1; i<=10; i++ {

    var person = Person(firstName: "John \(i)", lastName: "Doe \(i)", active: true)
    persons.append(person)
}

and Now I am trying to change the active property to false using the code below:

let inActionPersons = persons.map { (var p) in

    p.active = false
    return p
}

But I get the following error:

Cannot invoke map with an argument list of type @noescape (Person) throws

Any ideas?

SOLUTION:

Looks like Swift can't infer types sometimes which is kinda lame! Here is the solution:

let a = persons.map { (var p) -> Person in

        p.active = false
        return p
}

THIS DOES NOT WORK:

let a = persons.map { p in

        var p1 = p
        p1.active = false
        return p1
}

Solution

  • When using the brackets for arguments so that var works, you have to put the return type as well:

    let inActionPersons = persons.map { (var p) -> Person in
    
        p.active = false
        return p
    }