【问题标题】:How do I use AS with a switch in swift to get the class type如何在 swift 中使用带有开关的 AS 来获取类类型
【发布时间】:2015-09-03 14:22:33
【问题描述】:

我有一个 SomeClass 数组,它是其他各种类的超类。
该数组中包含所有这些随机类。
有没有办法使用开关(而不是else if let something = elm as? TheSubClassType

在伪代码中:

for AObjectOfTypeSomeClass in MyBigArray{
  switch the_type_of(AObjectOfTypeSomeClass){
    case SubClass1:
        let O = AObjectOfTypeSomeClass as! SubClass1
    ...
    ...
    ...
  }
}

【问题讨论】:

    标签: swift object casting switch-statement control-flow


    【解决方案1】:

    你很亲密。

    for objectOfSomeClass in MyBigArray {
        switch objectOfSomeClass {
        case let subClass as SubClass1:
            // Do what you want with subClass
        default:
            // Object isn't the subclass do something else
        }
    }
    

    这个网站有我找到的最好的模式匹配概要。 http://appventure.me/2015/08/20/swift-pattern-matching-in-detail/

    【讨论】:

    • 我知道它是如何工作的,但从逻辑上讲,我不理解这种语法的一些东西。比如as怎么不是可选的?
    • as 不是可选的,因为您是模式匹配,而不是绑定。绑定看起来像这样并且需要可选转换: if let subClass = anObject as?子类 { } 。我承认这有点违反直觉,因为它们都实现了相似的目标。
    • @Itay:对于 asas? 在 case 语句中比较 stackoverflow.com/questions/31759778/…
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2020-12-24
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多