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

Change the value that is being set in variable's willSet block

我试图在设置之前对正在设置的数组进行排序,但 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 正试图改变它。

willSet 中设置值类型(包括数组)之前,无法更改它们。您将需要改为使用计算 属性 和后备存储,如下所示:

var _people = [Person]()

var people: [Person] {
    get {
        return _people
    }
    set(newPeople) {
        _people = newPeople.sorted { [=10=].age > .age }
    }
}

无法改变 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
        })
    }

}