No Exact Matches in Call to Subscript [Swift]

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
        }
0

2 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")
    }
}

Your Answer

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest