在Swift中使用Map来更改自定义结构属性 [英] Using Map in Swift to Change Custom Struct Properties

查看:474
本文介绍了在Swift中使用Map来更改自定义结构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下结构。

struct Person {

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

我创建了一个Person集合,如下所示:

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)
}

现在我尝试使用代码将活动属性更改为false下面:

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
}

但是我收到以下错误:

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

任何想法?

解决方案:

看起来斯威夫特有时无法推断类型有点蹩脚!以下是解决方案:

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
}

这不起作用:

let a = persons.map { p in

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


推荐答案

当使用参数括号使 var 有效时,您还必须输入返回类型:

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
}

这篇关于在Swift中使用Map来更改自定义结构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆