Swift 3.0 Swift 3.0 Swift 2.x Swift 2.x Swift 1.x Swift 1.x ...
- 在String中獲取某個位置的Character,各Swift版本的差異
-
- Swift 3.0
let text = "abc" let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2) let lastChar2 = text.characters[characterIndex2] //will do the same let range: Range<String.Index> = text.range(of: "b")! let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
-
- Swift 2.x
let text = "abc" let index2 = text.startIndex.advancedBy(2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let lastChar = text.characters[index2] //will do the same let range: Range<String.Index> = text.rangeOfString("b")! let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match
-
- Swift 1.x
let text = "abc" let index2 = advance(text.startIndex, 2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let range = text.rangeOfString("b") let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times