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

标签 ios swift swift2

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

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/

相关文章:

ios - 检测在 uiscrollView 中点击了哪个 UIImage

ios - 有没有更好的代码,所以我们不能使用通用应用程序的条件

ios - 动画 Sprite 不会停止动画 - cocos2d

ios - 在 swift 中实现 GTScrollNavigationBar

swift2 - Swift 2 : is there a short syntax to conditionally set a non-optional variable from an optional variable?

iphone - 架构 i386 的 6 个重复符号

swift - 如何将 Firebase 数据库快照与文本进行比较?

ios - XCode/Swift 无法更改文本标签位置

ios - swift 中的惰性函数评估

ios - Swift 2 中显式的老式错误处理