【发布时间】:2017-01-02 21:33:47
【问题描述】:
阅读 Apple 的 ARC 指南后,我正在慢慢尝试掌握保留周期,但我不清楚的是 swift 的类型推断在推断全局变量时需要可选问号或强制展开感叹号类的范围。
例如:
import XCTest
@testable import PassionProject
class ItemManagerTests: XCTestCase {
var sut: ItemManager!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
sut = ItemManager()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func tests_ToDoCount_Is_InitiallyZero() {
XCTAssertEqual(sut.toDoCount, 0)
}
func tests_DoneCount_Is_InitiallyZero(){
XCTAssertEqual(sut.doneCount, 0)
}
}
如果我在下一行省略了问号或解释点,则会引发关于类没有初始化器的错误:
var sut: ItemManager
我的问题是,类型推断不只是简单地说这个变量将是这种类型吗?如果是这样,如果我们没有给它一个初始值,为什么 Xcode 会认为它是一个属性?其次,如果我们从未设置推断类型的值,为什么要强制解包它?
如果需要,这里是我们用作示例的对象的代码,并提前感谢您更好地掌握:
import Foundation
class ItemManager {
let toDoCount = 0
let doneCount = 0
}
【问题讨论】: