[英]Swift Type Variable for conditional optional unwrapping
我试图设置一个类型变量,然后用它有条件地打开一个可选变量。 这是一个例子:
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
}
这应该创建我想要的单元格的正确类型
我想我知道您要做什么。 使用dynamicType
进行比较,而不是有条件地展开可选内容。
func testInt() {
var test:Int = 15
let intType = Int.self
if test.dynamicType == intType {
print("is a int")
} else {
print("not a int")
}
}
至少这对您的Integer示例有效,不确定是否对您的UITableViewCell示例适用。
诠释示例
var myValue: Int = 1
if let test = myValue as? Int {
print("IS INT") // hits here
} else {
print("NOT INT")
}
非整数示例
var myValue: Float = 1.1
if let test = myValue as? Int {
print("IS INT")
} else {
print("NOT INT") // hits here
}
我想提出一点争议,因为编译器会让您知道您已经知道类型了。 AKA“总是失败”或“总是成功”
我不确定您要做什么,但是如果要检查变量是否为int类型,可以使用is
func testInt() {
let test:Int? = 15
// let intType = Int.self <-----comment this out. you dont need it
if test! is Int { //i'm force unwrapping "test!" cause you declared it as optional
print("is a int")
} else {
print("not a int")
}
}
func test<T>(type: T.Type) {
let test:Int? = 15
if let _ = test as? T {
print("is a int")
} else {
print("not a int")
}
}
test(Int) // is a int
test(Double) // not a int
要么 ...
func test<T>(type: T.Type, what: Any) {
if let w = what as? T {
print(w, "is a \(T.Type.self)")
} else {
print(what, "not a \(T.Type.self)")
}
}
test(Int.self, what: 1)
test(Double.self, what: 1)
test(Double.self, what: 2.2)
/*
1 is a Int.Type
1 not a Double.Type
2.2 is a Double.Type
*/
根据您的注释,您可以使用通用方法,并且仍然使用变量从第一个示例中“保存”您的类型// test()
let t1 = Int.self
let t2 = Double.self
test(t1) // is a int
test(t2) // not a int
t1和t2都是常量,t1具有Int.Type.Type类型,t2具有Double.Type.Type类型。 您不能投射为? t1还是? T2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.