Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

ios - Using Map in Swift to Change Custom Struct Properties

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are exactly two cases where the Swift compiler infers the return type of a closure automatically:

  • In a "single-expression closure," i.e. the closure body consists of a single expression only (with or without explicit closure parameters).
  • If the type can be inferred from the calling context.

None of this applies in

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

or

let a = persons.map { p in
        var p1 = p
        p1.active = false
        return p1
}

and that's why you have to specify the return type explicitly as in Kametrixom's answer.

Example of a single-expression closure:

let inActionPersons = persons.map { p in
    Person(firstName: p.firstName, lastName: p.lastName, active: false)
}

and it would compile with (var p) in or (p : Person) in as well, so this has nothing to do with whether the closure arguments are given explicitly in parentheses or not.

And here is an example where the type is inferred from the calling context:

let a : [Person] = persons.map { p in
    var p1 = p
    p1.active = false
    return p1
}

The result of map() must be a [Person] array, so map needs a closure of type Person -> Person, and the compiler infers the return type Person automatically.

For more information, see "Inferring Type From Context" and "Implicit Returns from Single-Expression Closures" in the "Closures" chapter in the Swift book.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...