简体   繁体   English

Swift nil可选字符串=空字符串

[英]Swift nil Optional String = Empty String

This one does not make sense to me at all. 这一点对我完全没有意义。 I have a struct that takes a few strings: 我有一个需要几个字符串的结构:

public struct Organization {
  let id: String
  let name: String
  let legacyID: String?
  let rID: String?

  public init(id: String, name: String, legacyID: String?, rID: String?) {
    self.id = id
    self.name = name
    self.legacyID = legacyID
    self.rID = rID
  }
}

Notice that legacyID and rID are optional. 注意, legacyIDrID是可选的。 However, if I attempt to set either of them to nil or .None , instead they get set to "" (empty string). 但是,如果我尝试将它们之一设置为nil.None ,它们将被设置为"" (空字符串)。 Ex: 例如:

let org = Organization(id: company.companyID, name: company.name, legacyID: company.context, rID: nil)

And yet, when I attempt to access rID , it shows up as "" instead of nil . 但是,当我尝试访问rID ,它显示为""而不是nil I've even tried directly setting nil in the init and it's still set as "" . 我什至尝试直接在init设置nil ,但仍设置为"" This is messing up my equality checks. 这搞砸了我的平等检查。 Anyone know what is going on? 有人知道发生了什么吗?

Note: This is Swift 1.2 注意:这是Swift 1.2

You getting "" as output because your data type is String. 由于数据类型为String,因此获得“”作为输出。 So if any String variable is empty or nil it always shows "". 因此,如果任何String变量为空或nil,则始终显示“”。 You can't get nil as output by using String type. 使用String类型不能得到nil作为输出。 Even if you assign nil directly nothing happen same output will come. 即使直接分配nil,也不会发生相同的输出。

Edited : This is what i got from ur code. 编辑:这是我从我们的代码中得到的。 Its working properly. 它的工作正常。 在此处输入图片说明

So it turns out the problem was the debugger. 因此事实证明问题出在调试器上。 If I used the debugger to check the value, even in the debugger prompt, p/po/print org.rID it returned the incorrect value. 如果我使用调试器检查该值,即使在调试器提示符p/po/print org.rIDp/po/print org.rID返回错误的值。 However, inserting a println(org.rID) in my code printed the correct value nil . 但是,在我的代码中插入println(org.rID)打印正确的值nil I hate it when I can't trust the debugger. 当我不信任调试器时,我会讨厌它。 Happened when they switched from gcd to lldb too. 当他们也从gcd切换到lldb时发生。 Hopefully this is straightened out in Xcode 7. 希望这可以在Xcode 7中得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM