Get nth character of a string in Swift programming language

后端 未结 30 1972
一整个雨季
一整个雨季 2020-11-22 01:26

How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = \"Hello, world!\"

var firstChar = string[         


        
30条回答
  •  孤独总比滥情好
    2020-11-22 01:37

    Swift 2.2 Solution:

    The following extension works in Xcode 7, this is a combination of this solution and Swift 2.0 syntax conversion.

    extension String {
        subscript(integerIndex: Int) -> Character {
            let index = startIndex.advancedBy(integerIndex)
            return self[index]
        }
    
        subscript(integerRange: Range) -> String {
            let start = startIndex.advancedBy(integerRange.startIndex)
            let end = startIndex.advancedBy(integerRange.endIndex)
            let range = start..

提交回复
热议问题