【问题标题】:how to convert null string to null swift如何将空字符串快速转换为空字符串
【发布时间】:2016-12-14 07:55:01
【问题描述】:

我是Swift 的新手。我尝试了这个 Swift 链接Detect a Null value in NSDictionaryNSDictionary,但我没有这样做。

数据:

"end_time" = "<null>"

这是我的代码:

if endTime["end_time"] is NSNull {

    print("your session still available ")
 }
else{
   print("your session end \(endTime["end_time"])")
}

每次都会去else语句。可能我需要将字符串转换为 null 或替代解决方案。你能帮帮我吗?

谢谢。

【问题讨论】:

  • 该值也可以是文字字符串"&lt;null&gt;"
  • 你可以和"&lt;null&gt;"这样的字符串比较:if endTime["end_time"] == "&lt;null&gt;"
  • 非“NSNull”时end_time是什么格式(当它有值时)

标签: swift null swift2 nsnull


【解决方案1】:

这是您在 swift 中检查 null 的方法:

let time = endTime["end_time"]
if  time != "<null>" {
    print("time is not <null>")
}
else
{
    print("time is <null>")
}

【讨论】:

  • &lt;null&gt; != nil
  • 它导致相同的结果,endTime["end_time"] 等于 "" 它不是 nil。
【解决方案2】:

您可以创建一个 NilCheck 控制器来检查各种数据类型的 nil 或 null。例如,我创建了一个函数来从字典中删除 null [如果有] 并将字典数组存储在 Userdefaults 中。请随时提出您的疑问:)

func removeNilAndSaveToLocalStore(array : [[String:Any]]) {

    var arrayToSave = [[String:Any]]()
    for place in array {

        var dict = [String:Any]()
        dict["AreaId"] =  NilCheck.sharedInstance.checkIntForNil(nbr: place["AreaId"]! as? Int)
        dict["AreaNameAr"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaNameAr"]! as? String)
        dict["AreaName"] = NilCheck.sharedInstance.checkStringForNil(str: place["AreaName"]! as? String)
        dict["GovernorateId"] = NilCheck.sharedInstance.checkIntForNil(nbr: place["GovernorateId"]! as? Int)
        arrayToSave.append(dict)
    }
    LocalStore.setAreaList(token: arrayToSave)
}

class NilCheck {

static let sharedInstance : NilCheck = {
    let instance = NilCheck()
    return instance
}()

func checkStringForNil(str : String?) -> String {

    guard let str = str else {
        return String() // return default string
    }
    return str
}
func checkIntForNil(nbr : Int?) -> Int {

    guard let num = nbr else {
        return 0 // return default Int
    }
    return num
} }

【讨论】:

  • 有一个操作符可以做你喜欢的函数str ?? ""num ?? 0
猜你喜欢
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2016-05-25
  • 2014-11-12
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多