3

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 to 'UInt8' 

To let you see what I mean:

var myString: String = "Hello " myString += "world" // works great var myOptionalString: String! = "Foo " myOptionalString += " bar" // error: String! is not identical to 'UInt8' 

however if I append it while the assignment it works

var myOptionalString: String! = "Foo " myOptionalString = myOptionalString + " bar" // works great 

can anyone tell me the reason for that, or is there something I missed in optionals?

Update

mySecondOpString: String? = "Hello " mySecondOpString! += "world" // works great too 
3
  • 2
    I don't know swift very much but be aware that x+=y is not semantically equivalent to x = x+y. In the first case you have something like append y to x (x pointing to a mutable string), and in the second you have catenate x and y, and associate the result to x. Optional may change things when append... Commented Mar 27, 2015 at 10:20
  • The x = x +y thing is just there so nobody can say "hey try this" but you're right it's not equivalent Commented Mar 27, 2015 at 10:22
  • 1
    See this for an answer... stackoverflow.com/questions/26583300/… Commented Mar 27, 2015 at 10:25

2 Answers 2

2

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" 
Sign up to request clarification or add additional context in comments.

Comments

0

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" 

1 Comment

Ty but dont worry this isn't copied code. I was working with UITextView.text which is a String!, thats why the question came up

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.