Swift 3.0 iterate over String.Index range

后端 未结 9 1304
温柔的废话
温柔的废话 2020-12-16 10:27

The following was possible with Swift 2.2:

let m = \"alpha\"
for i in m.startIndex..

With 3.0,

相关标签:
9条回答
  • 2020-12-16 11:21

    Use the following:

    for i in s.characters.indices[s.startIndex..<s.endIndex] {
      print(s[i])
    }
    

    Taken from Migrating to Swift 2.3 or Swift 3 from Swift 2.2

    0 讨论(0)
  • 2020-12-16 11:24

    You can traverse a string by using indices property of the characters property like this:

    let letters = "string"
    let middle = letters.index(letters.startIndex, offsetBy: letters.characters.count / 2)
    
    for index in letters.characters.indices {
    
        // to traverse to half the length of string 
        if index == middle { break }  // s, t, r
    
        print(letters[index])  // s, t, r, i, n, g
    }
    

    From the documentation in section Strings and Characters - Counting Characters:

    Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries.

    emphasis is my own.

    This will not work:

    let secondChar = letters[1] 
    // error: subscript is unavailable, cannot subscript String with an Int
    
    0 讨论(0)
  • 2020-12-16 11:25

    Swift 4:

    let mi: String = "hello how are you?"
    for i in mi {
       print(i)
    }
    
    0 讨论(0)
提交回复
热议问题