gpt4 book ai didi

ios - 用于条件可选展开的 Swift 类型变量

转载 作者:行者123 更新时间:2023-11-28 06:50:32 24 4
gpt4 key购买 nike

我正在尝试设置一个类型变量,然后使用它有条件地解包可选。这是一个例子:

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 示例。

关于ios - 用于条件可选展开的 Swift 类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35045969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com