2

I'm trying to append Character to String using "+=", but It doesn't really work. Once I tried with append method, it works. I just wonder why it is. The compiler says "string is not identical to Unit8".

let puzzleInput = "great minds think alike"
var puzzleOutput = " "
for character in puzzleInput {

    switch character {
        case "a", "e", "i", "o", "u", " ":
        continue

    default:
        // error : doesn't work
        puzzleOutput += character
        //puzzleOutput.append(character)
    }
}
println(puzzleOutput)
1
  • 2
    FYI, it will work if you make character a String first: puzzleOutput += String(character). Commented Sep 25, 2014 at 1:58

3 Answers 3

3

20140818, Apple updated:

Updated the Concatenating Strings and Characters section to reflect the fact that String and Character values can no longer be combined with the addition operator (+) or addition assignment operator (+=). These operators are now used only with String values. Use the String type’s append method to append a single Character value onto the end of a string.

Document Revision History 2014-08-18

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. I tried out with puzzleOutput += "(character)". And it works.
@Toshi puzzleOutput += "(\character)" should also work.
oh yeah I meant puzzleOutput += "(\character)" . Thanks anyway!
0

To append a Character to a String in Swift you can do something similar to the following:

var myString: String = "ab"
let myCharacter: Character = "c"
let myStringChar: String = "d"

myString += String(myCharacter) // abc
myString += myStringChar // abcd

Comments

0

Updated version

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
  switch character {
  case "a", "e", "i", "o", "u", " ":
   continue
  default:
    puzzleOutput += String(character)
  }
}
print(puzzleOutput)
// prints "grtmndsthnklk"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.