在swift 4中无法解决这个Null问题?

时间:2018-05-31 06:14:31

标签: swift string null is-empty

我正在尝试检查我从服务器收到的值,如果字符串为空我使用以下条件。

 var line2Cvar = permanentCAddVarDictionary?["line2"] as! String
                    if line2Cvar.isEmpty {
                        line2Cvar = "---"
                    }
                    self.permanentCAddDic.setValue(line2Cvar, forKey: "line2Cvar")

如果字符串为null我使用以下条件。

 var line2Cvar = permanentCAddVarDictionary?["line2"]

                    if line2Cvar is NSNull {
                        line2Cvar = "----"
                    }
                    self.emergencyContactDic.setValue(line2Cvar, forKey: "line2Cvar")

但在我的情况下,有时我会变空,有时我会得到一个空值。 check string如何为空或直接为null。

2 个答案:

答案 0 :(得分:0)

在字典中检查字符串时,您有4种可能的状态:

  1. 字符串存在,非空
  2. 字符串存在,但为空
  3. 密钥在字典中,但值不是字符串
  4. 字典中没有密钥
  5. 您必须单独检查每个案例。

    let possibleString = dict[key]
    
    if let string = possibleString as? String {
        if string.isEmpty {
            // deal with empty case
        } else {
            // deal with non-empty case
        }
    } else if possibleString == nil {
        // deal with key not-present case
    } else {
        // deal with value-not-string case
    }
    

    您可以结合一些检查并消除其他检查,具体取决于您需要的特定逻辑。例如,如果您想以相同的方式处理not-present和not-a-string,则可以取消nil检查,然后直至最终else

答案 1 :(得分:0)

extension String {
    var isEmptyNull:Bool {

        let string = self.trimmingCharacters(in: CharacterSet.whitespaces)

        if string == "" || string.lowercased() == "null" {
            return true
        }else {
            return false
        }
    }
}

你可以在这里查看

let stringvalue = ""

if stringvalue.isEmptyNull {
     print("string value is empty or null")
}else {
     print(stringvalue)
}

输出

string value is empty or null