【发布时间】:2016-01-28 13:36:30
【问题描述】:
我正在尝试设置一个类型变量,然后使用它来有条件地解开一个可选项。这是一个例子:
func testInt() {
var test:Int? = 15
let intType = Int.self
if let testInt = test as? intType {
print("is a int")
} else {
print("not a int")
}
}
在上面的示例中,我收到'intType' is not a type 的错误。
这有可能吗?
我也试过.Type,但我得到了同样的错误。
编辑****
这是我正在尝试做的一个例子。上面的示例只是将类型存储在变量中的简单示例。我知道还有其他方法可以完成上述功能...
class TableCell0: UITableViewCell {}
class TableCell1: UITableViewCell {}
enum SectionInfo: Int {
case section0 = 0, section1
var cellIdentifier: String {
let identifiers = ["Section0Cell", "Section1Cell"]
return identifiers[self.rawValue]
}
var cellType: UITableViewCell.Type {
let types:[UITableViewCell.Type] = [TableCell0.self, TableCell1.self]
return types[self.rawValue]
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let sectionInfo = SectionInfo(rawValue: indexPath.section) else {
fatalError("Unexpected section passed from tableView")
}
guard let cell = tableView.dequeueReusableCellWithIdentifier(sectionInfo.cellIdentifier, forIndexPath: indexPath) as? sectionInfo.cellType else {
fatalError("unexpected cell dequeued from tableView")
}
return cell
}
这应该会创建我想要的正确类型的单元格
【问题讨论】:
-
如果你的 var 测试是一个可选的 Int 你应该使用
guard或if let来解开你的值。if let test = test { ... // test it is not nil and has a value } -
我知道我可以使用 guard 或者 if let 并使用显式类型,即 as? Int 但我的问题是,如果我将类型存储在一个变量中,为什么我不能将该变量用作向下转换中的类型。