我在表视图中找到了关于部分的这段代码,以便在表视图中创建索引:
class User: NSObject {
let namex: String
var section: Int?
init(name: String) {
self.namex = name
}
}
// custom type to represent table sections
class Section {
var users: [User] = []
func addUser(user: User) {
self.users.append(user)
}
}
// raw user data
let names = [
"Clementine",
"Bessie",
"Annis",
"Charlena"
]
// `UIKit` convenience class for sectioning a table
let collation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
// table sections
var sections: [Section] {
// return if already initialized
if self._sections != nil {
return self._sections!
}
// create users from the name list
var users: [User] = names.map { namess in
var user = User(name: namess)
user.section = self.collation.sectionForObject(user, collationStringSelector: "namex")
return user
}
// create empty sections
var sections = [Section]()
for i in 0..<self.collation.sectionIndexTitles.count {
sections.append(Section())
}
// put each user in a section
for user in users {
sections[user.section!].addUser(user)
}
// sort each section
for section in sections {
section.users = self.collation.sortedArrayFromArray(section.users, collationStringSelector: "namex") as [User]
}
self._sections = sections
return self._sections!
}
var _sections: [Section]?
我不明白的部分是:
// table sections
var sections: [Section] {
// return if already initialized
if self._sections != nil {
return self._sections!
}
// etc...
return self._sections!
}
var _sections: [Section]?
我的问题是:
这是什么意思var sections: [Section] { }
?我想这不是一个函数,因为前面没有func
关键字。
这是var _sections: [Section]
是什么?将_
放在前面的原因是什么?
答案 0 :(得分:3)
尽管没有关键字,它与函数非常相似 - 它是computed property。
这些看起来像变量,但就像功能一样。它们可以是只读的(get
但不是set
),或者可以同时具有get
和set
版本。这是一个更简单的例子:
var y = 3
var x: Int {
get { return 2*y }
}
println(x) // prints 6
y += 1
println(x) // prints 8
var z: Int {
get { return y }
set(newVal) { y = newVal }
}
println(z) // prints 4
z = 10 // sets y to 10
println(x) // prints 20 (2*10)
如果它只是get
,您可以省略关键字,这就是问题中版本的完成方式。上面的x
声明可以在没有它的情况下编写:
var x: Int {
return 2*y
}
示例中的var _sections
与上面代码中的y
变量扮演类似的角色 - 它是从中派生计算属性结果的基础数据。 _
的原因只是表明它是一个内部实现细节。下划线对Swift本身没有意义,这只是人们使用的命名约定。
答案 1 :(得分:1)
这是一个只读的计算属性。它们的行为类似于属性,但每次都会计算。您可以阅读更多相关信息in the docs。查看“计算属性”部分以及“只读计算属性”部分以了解简写。