Value of optional type 'String?' must be unwrapped to a value of type 'String'

var text = "hello"

let map = ["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","a":"ᴀ","b":"ʙ","c":"ᴄ","d":"ᴅ","e":"ᴇ","f":"ғ","g":"ɢ","h":"ʜ","i":"ɪ","j":"ᴊ","k":"ᴋ","l":"ʟ","m":"ᴍ","n":"ɴ","o":"ᴏ","p":"ᴘ","q":"ǫ","r":"ʀ","s":"s","t":"ᴛ","u":"ᴜ","v":"ᴠ","w":"ᴡ","x":"x","y":"ʏ","z":"ᴢ","A":"A","B":"B","C":"C","D":"D","E":"E","F":"F","G":"G","H":"H","I":"I","J":"J","K":"K","L":"L","M":"M","N":"N","O":"O","P":"P","Q":"Q","R":"R","S":"S","T":"T","U":"U","V":"V","W":"W","X":"X","Y":"Y","Z":"Z"]

var charArray = text.components(separatedBy: " ")

var i = 0

while i<charArray.count {

i+=1

charArray[i] = map[charArray[i]] }

let string = charArray.joined(separator: "")

print(string)

Answered by OOPer in 398411022

I am wondering why it says

Value of optional type 'String?' must be unwrapped to a value of type 'String'

right behind


The lefthand side of your assignment expression (`charArray[i]`) is of type `String`,

but the righthand side (`map[charArray[i]]`) is of type `String?` (aka `Optional<String>`).


You need to unwrap an Optional value to assign it to a non-Optional.

But your current code has some more flaws and you may need to fix them first.

So, what do you want to ask?


---

Generally, if you want to make per-character based mapping on String:

- `components(separatedBy:)` and `joined(separator:)` are not good tools

- You need to define the output for the characters not contained in the `map`


I would write it as:

var text = "hello"
let map: [Character: Character] = ["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","a":"ᴀ","b":"ʙ","c":"ᴄ","d":"ᴅ","e":"ᴇ","f":"ғ","g":"ɢ","h":"ʜ","i":"ɪ","j":"ᴊ","k":"ᴋ","l":"ʟ","m":"ᴍ","n":"ɴ","o":"ᴏ","p":"ᴘ","q":"ǫ","r":"ʀ","s":"s","t":"ᴛ","u":"ᴜ","v":"ᴠ","w":"ᴡ","x":"x","y":"ʏ","z":"ᴢ","A":"A","B":"B","C":"C","D":"D","E":"E","F":"F","G":"G","H":"H","I":"I","J":"J","K":"K","L":"L","M":"M","N":"N","O":"O","P":"P","Q":"Q","R":"R","S":"S","T":"T","U":"U","V":"V","W":"W","X":"X","Y":"Y","Z":"Z"]

let string = String(text.map {ch in map[ch, default: ch]})
print(string) //->ʜᴇʟʟᴏ

I am wondering why it says

Value of optional type 'String?' must be unwrapped to a value of type 'String'

right behind

charArray[i] = map[charArray[i]]

Accepted Answer

I am wondering why it says

Value of optional type 'String?' must be unwrapped to a value of type 'String'

right behind


The lefthand side of your assignment expression (`charArray[i]`) is of type `String`,

but the righthand side (`map[charArray[i]]`) is of type `String?` (aka `Optional<String>`).


You need to unwrap an Optional value to assign it to a non-Optional.

But your current code has some more flaws and you may need to fix them first.

Value of optional type 'String?' must be unwrapped to a value of type 'String'
 
 
Q