class Animal {
class func generate() -> Animal {
return self()
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨构造类型为"Animal"的对象,其元类型值必须使用"required"初始值设定项
我能理解这一点.如果我写这样的子类:
class SubAnimal: Animal {
let head: Int
init(head: Int) {
self.head = head
super.init()
}
}
Run Code Online (Sandbox Code Playgroud)
它将继承Animal
的类方法,generate()
但不会继承其默认的初始化程序init()
.所以SmallAnimal.generate()
实际上是调用SmallAnimal()
,但SmallAnimal
没有初始化程序init()
!当然这是编译器想要阻止的.
令我困惑的是一个类似的问题.
class someClass {
}
let anotherClass = someClass.self
let anotherObject = anotherClass()
Run Code Online (Sandbox Code Playgroud)
编译器仍抱怨构造类型为"Animal"的对象,其元类型值必须使用"required"初始化器.
这一次,我无法理解.anotherClass
是一个元类型值,但会导致什么不好的结果?
我知道如何解决这个问题,添加required init() {}
是解决方案.但我真的想知道第二种情况的原因.
假设我有一个只有一个角色'的线,让我们看看\n
在不同情况下的效果:
:s/s/a\nb
a^@b
:s/s/a\\nb
a\nb
:s/s/a\\\nb
a\^@b
:s/s/a\\\\nb
a\\nb
:echo "a\nb"
a
b
:echo "a\\nb"
a\nb
:echo "a\\\nb"
a\
b
:echo "a\\\\nb"
a\\nb
Run Code Online (Sandbox Code Playgroud)
那么为什么\n
表现不一样呢?然后让我们看看使用条件substitute()
:echo substitute(" ", " ", "a\nb", "")
a
b
:echo substitute(" ", " ", "a\\nb", "")
a
b
:echo substitute(" ", " ", "a\\\nb", "")
a
b
:echo substitute(" ", " ", "a\\\\nb", "")
a\nb
Run Code Online (Sandbox Code Playgroud)
这一次,\n
仍被解释为"换行",但如何解释反斜杠?
下一部分,说我还有一个只有一个角色的',而不是\n
,\r
将要研究:
:s/s/a\rb
a
b
:s/s/a\\rb
a\rb
:s/s/a\\\rb
a\
b …
Run Code Online (Sandbox Code Playgroud) 我已经阅读了这个问题并认为我理解了两种方法之间的区别,直到找到一个奇怪的例子:
设置表格视图单元格的样式为基本,标识符为故事板中的单元格,代码如下:
import UIKit
class TableViewController: UITableViewController {
var items: [String]!
override func viewDidLoad() {
super.viewDidLoad()
items = ["first", "second", "third"]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// either works fine
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! // let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = items[indexPath.row]
return …
Run Code Online (Sandbox Code Playgroud)