The mistake in your code is that the type of item.index(item.startIndex, offsetBy: 7)
is not a String
, nor a Character
. It's of type String.Index
(in Swift 3, it's an alias of String.CharacterView.Index
), which holds just a position in a String
and does not represent any sort of contents in a String
.
Your code in question would be rewritten as:
let item = "01: 06-08-2017, 13:43"
if item[item.index(item.startIndex, offsetBy: 7)] == "1" {
print("ok!")
} else {
print("invalid") //->invalid
}
You can subscript ([]
) to a String
with String.Index
and get a Character
at the position, and compare it to a Character
. (In this context, "1"
is treated as a Character
, not String
.)
Subscript for String
works also with Range<String.Index>
:
let startIndex = item.index(item.startIndex, offsetBy: 4)
let endIndex = item.index(startIndex, offsetBy: 10)
if item[startIndex..<endIndex] == "06-08-2017" {
print("hit!") //->hit!
}
In Swift 4, many things around String
type have changed, but the code above should work both in Swift 3 & 4.