我尝试在设置之前对正在设置的数组进行排序,但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
正试图改变它。
答案 0 :(得分:28)
无法改变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
})
}
}
答案 1 :(得分:6)
在willSet
内设置值类型(包括数组)之前,无法更改它们。您将需要使用计算属性和后备存储,如下所示:
var _people = [Person]()
var people: [Person] {
get {
return _people
}
set(newPeople) {
_people = newPeople.sorted { $0.age > $1.age }
}
}