Why isn't is possible to append a String! via += operator?

后端 未结 2 541
清酒与你
清酒与你 2021-01-21 00:16

As the title says I\'m trying to append text to an implicitly unwrapped optional String via += operator which gives me

\'String!\' is not identical          


        
相关标签:
2条回答
  • 2021-01-21 00:39

    String! is implicitly unwrapped optional type which is special case of optional type.

    As you may know String! is not identical to String. So when you write:

    var myOptionalString: String! = "Foo "
    myOptionalString += " bar" // error: String! is not identical to 'UInt8'
    

    it will try to find += operator with String! which it could not and the hence error.

    if you explicitly unwrap it (you could say then it defies the purpose) works:

     myOptionalString! += " bar"
    
    0 讨论(0)
  • 2021-01-21 00:42

    There's nothing wrong in your code. It looks like in Swift's standard library there's no += operator overload made to work with String optionals.

    Taken from the standard library, += is overloaded for String (not for String?)

    func +=(inout lhs: String, rhs: String)
    

    Just follow this nice SO answer to view the contents of the Swift standard library to check that

    Note

    Your code will be better written as:

    var myOptionalString: String? = "Foo "
    myOptionalString
    myOptionalString! += " bar"
    
    0 讨论(0)
提交回复
热议问题