小编典典

更改在变量的willSet块中设置的值

swift

我正在尝试在设置数组之前对要设置的数组进行排序,但是的参数willSet是不可变的,并且会sort改变值。如何克服这个限制?

var files:[File]! = [File]() {
    willSet(newFiles) {
        newFiles.sort { (a:File, b:File) -> Bool in
            return a.created_at > b.created_at
        }
    }
}

为了使这个问题脱离我自己的项目环境,我提出了以下要点:

class Person {
    var name:String!
    var age:Int!

    init(name:String, age:Int) {
        self.name = name
        self.age = age
    }
}

let scott = Person(name: "Scott", age: 28)
let will = Person(name: "Will", age: 27)
let john = Person(name: "John", age: 32)
let noah = Person(name: "Noah", age: 15)

var sample = [scott,will,john,noah]



var people:[Person] = [Person]() {
    willSet(newPeople) {
        newPeople.sort({ (a:Person, b:Person) -> Bool in
            return a.age > b.age
        })

    }
}

people = sample

people[0]

我收到错误消息,指出该newPeople变量不可变,sort正在尝试对其进行突变。


阅读 262

收藏
2020-07-07

共1个答案

小编典典

不能对内部的值进行突变willSet。如果实现willSet观察者,则将新的属性值作为常量参数传递给它。


修改它以使用该didSet怎么办?

var people:[Person] = [Person]()
{
    didSet
    {
        people.sort({ (a:Person, b:Person) -> Bool in
            return a.age > b.age
        })
    }
}

willSet在值存储之前被调用。
didSet新值存储后立即调用。

您可以在此处阅读有关财产观察员的更多信息
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

您还可以像下面这样编写自定义getter和setter。但是didSet似乎更方便。

var _people = [Person]()

var people: [Person] {
    get {
        return _people
    }
    set(newPeople) {
        _people = newPeople.sorted({ (a:Person, b:Person) -> Bool in
            return a.age > b.age
        })
    }

}
2020-07-07