I'm new to Swift. I found out some weird behavior of subscript matching:
struct SubscriptTest {
subscript(character: Character) -> String {
return "Character: \(character)"
}
subscript(string: String) -> String {
return "String: \(string)"
}
subscript(int: Int) -> String {
return "Int: \(int)"
}
}
let test = SubscriptTest()
test["abc"] // String: abc
test[13] // Int: 13
test["🐧"] // String: 🐧 (surprisingly)
I thought the last test would match my Character
subscript, not the String
one. I tried to swap the order of subscripts declarations, thinking that maybe the last matching one is being used. It didn't change anything, String
subscript is still used for single Character
.
I know I could just use String
subscript and check for characters count, but the root of my question is curiosity.
Why is Character
subscript never matched here?
"🐧"
can be both a String
literal and a Character
literal,
and defaults to String
(if both are valid in the context). With
test["🐧" as Character] // Character: 🐧
or
let c: Character = "🐧"
test[c] // Character: 🐧
you get the expected result.