Underneath this you can see my code. I commented the line which causes the error. Error message: "No exact matches in call to subscript". Do you know how I can avoid this error? Thank you for your help!
let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26] var newwrd = "" for var i in str ?? "" { let ci = dic[i] // This line causes the error } 02 Answers
Actually you should get the error
Cannot subscript a value of type '[String : Int]' with an argument of type 'String.Element' (aka 'Character')
str is obviously String?, the element type when enumerating a string is Character but the subscription type must be String.
let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26] for i in str ?? "" { // no need for var i let ci = dic[String(i)] ?? 0 print(ci) } If the string contains a character which is not in the dictionary the result is 0.
There is a shorter way without a helper dictionary
for i in str ?? "" where ("a"..."z") ~= i { let ci = Int(i.asciiValue!) - 96 print(ci) } As @vadian says, it looks like str is an Optional<String>. Looping through a string gives you Characters, but your dictionary keys are Strings. You need to convert each character to a String, and deal with optionals. Try this code:
let str: String? = "abcqrml@" let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26] var newwrd = "" for i in str ?? "" { if let ci = dic[String(i)] { print("dic[\(i)] = \(ci)") } else { print("dic[\(i)] = nil") } }