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

Swift:展开选项和NSNull

  •  0
  • nuvaryan  · 技术社区  · 9 年前
    if let action = self.info?["action"] {
        switch action as! String {
            ....
        }
    } else {...}
    

    第二行执行后,我得到:

    Could not cast value of type 'NSNull' (0x1b7f59128) to 'NSString' (0x1b7f8ae8).
    

    3 回复  |  直到 9 年前
        1
  •  1
  •   rmaddy    9 年前

    NSNull 是一个特殊值,通常由JSON处理产生。它与 nil 价值您不能强制将对象从一种类型转换为另一种类型,这就是代码失败的原因。

    let action = self.info?["action"] // An optional
    if let action = action as? String {
        // You have your String, process as needed
    } else if let action = action as? NSNull {
        // It was "null", process as needed
    } else {
        // It is something else, possible nil, process as needed
    }
    
        2
  •  0
  •   Krunal    9 年前

    String

    if let action = self.info?["action"] as? String {
        switch action{
            ....
        }
    } else {...}
    
        3
  •  0
  •   Krunal    9 年前
    if let action = self.info?["action"] { // Unwrap optional
    
       if action is String {  //Check String
    
          switch action {
            ....
          }
    
      } else if action is NSNull { // Check Null
    
        print("action is NSNull")
    
      } else {
    
        print("Action is neither a string nor NSNUll")
    
      }
    
    } else {
    
        print("Action is nil")
    
    }