代码之家  ›  专栏  ›  技术社区  ›  Fattie

Swift3,展开可选的<绑定>(在SQLite.swift中)

  •  1
  • Fattie  · 技术社区  · 9 年前

    在最优秀的SQLite中。斯威夫特,我有

     let stmt = try local.db!.prepare(..)
     for row in stmt {
        for tricky in row {
    

    每个“棘手”都是 Optional<Binding>

    我所知道的解开每一个棘手问题的唯一方法就是这样

    变量可打印:字符串=”

    if let trickyNotNil = tricky {
        if let anInt:Int64 = trickyNotNil as? Int64 {
           print("it's an Int") 
            .. use anInt
            }
        if let aString:String = trickyNotNil as? String {
            print("it's a String")
            .. use aString}
    }
    else {
        tricky is nil, do something else
    }
    

    在这个例子中,我很确定它只能是一个Int64或字符串(或一些字符串);我想我们必须用默认情况来涵盖所有其他可能性。

    有更快捷的方法吗?

    有办法吗 获取类型 可选<结合> ?

    (顺便说一句,特别是关于SQLite.swift;从doco中可能有一种我不知道的方法“获取列n的类型”。这很酷,但是,上一段中的问题仍然存在。)

    1 回复  |  直到 9 年前
        1
  •  1
  •   Duncan C    9 年前

    可以基于类使用switch语句。此类switch语句的示例代码如下所示:

    let array: [Any?] = ["One", 1, nil, "Two", 2]
    
    for item in array {
      switch item {
      case let anInt as Int:
        print("Element is int \(anInt)")
      case let aString as String:
        print("Element is String \"\(aString)\"")
      case nil:
        print("Element is nil")
      default:
        break
      }
    }
    

    如果需要,还可以将where子句添加到一个或多个案例中:

    let array: [Any?] = ["One", 1, nil, "Two", 2, "One Hundred", 100]
    
    for item in array {
      switch item {
      case let anInt as Int
           where anInt < 100:
        print("Element is int < 100 == \(anInt)")
      case let anInt as Int where anInt >= 100:
        print("Element is int >= 100 == \(anInt)")
      case let aString as String:
        print("Element is String \"\(aString)\"")
      case nil:
        print("Element is nil")
      default:
        break
      }
    }