Swift 3.0 iterate over String.Index range

后端 未结 9 1303
温柔的废话
温柔的废话 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:03

    To concretely demonstrate how to traverse through a range in a string in Swift 4, we can use the where filter in a for loop to filter its execution to the specified range:

    func iterateStringByRange(_ sentence: String, from: Int, to: Int) {
    
        let startIndex = sentence.index(sentence.startIndex, offsetBy: from)
        let endIndex = sentence.index(sentence.startIndex, offsetBy: to)
    
        for position in sentence.indices where (position >= startIndex && position < endIndex) {
            let char = sentence[position]
            print(char)
        }
    
    }
    

    iterateStringByRange("string", from: 1, to: 3) will print t, r and i

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

    Iterating over characters in a string is cleaner in Swift 4:

    let myString = "Hello World"    
    for char in myString {
        print(char)
    }
    
    0 讨论(0)
  • 2020-12-16 11:14

    Another option is to use enumerated() e.g:

    let string = "Hello World"    
    for (index, char) in string.characters.enumerated() {
        print(char)
    }
    

    or for Swift 4 just use

    let string = "Hello World"    
    for (index, char) in string.enumerated() {
        print(char)
    }
    
    0 讨论(0)
  • 2020-12-16 11:15

    The best way to do this is :-

     let name = "nick" // The String which we want to print.
    
      for i in 0..<name.count 
    {
       // Operation name[i] is not allowed in Swift, an alternative is
       let index = name.index[name.startIndex, offsetBy: i]
       print(name[index])
    }
    

    for more details visit here

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

    Swift 4.2

    Simply:

    let m = "alpha"
    for i in m.indices {
       print(m[i])
    }
    
    0 讨论(0)
  • 2020-12-16 11:19

    If you want to traverse over the characters of a String, then instead of explicitly accessing the indices of the String, you could simply work with the CharacterView of the String, which conforms to CollectionType, allowing you access to neat subsequencing methods such as prefix(_:) and so on.

    /* traverse the characters of your string instance,
       up to middle character of the string, where "middle"
       will be rounded down for strings of an odd amount of
       characters (e.g. 5 characters -> travers through 2)  */
    let m = "alpha"
    for ch in m.characters.prefix(m.characters.count/2) {
        print(ch, ch.dynamicType)
    } /* a Character
         l Character */
    
    /* round odd division up instead */
    for ch in m.characters.prefix((m.characters.count+1)/2) {
        print(ch, ch.dynamicType)
    } /* a Character
         l Character 
         p Character */
    

    If you'd like to treat the characters within the loop as strings, simply use String(ch) above.


    With regard to your comment below: if you'd like to access a range of the CharacterView, you could easily implement your own extension of CollectionType (specified for when Generator.Element is Character) making use of both prefix(_:) and suffix(_:) to yield a sub-collection given e.g. a half-open (from..<to) range

    /* for values to >= count, prefixed CharacterView will be suffixed until its end */
    extension CollectionType where Generator.Element == Character {
        func inHalfOpenRange(from: Int, to: Int) -> Self {
            guard case let to = min(to, underestimateCount()) where from <= to else {
                return self.prefix(0) as! Self
            }
            return self.prefix(to).suffix(to-from) as! Self
        }
    }
    
    /* example */
    let m = "0123456789"    
    for ch in m.characters.inHalfOpenRange(4, to: 8) {
        print(ch)         /*  \                                   */
    } /* 4                     a (sub-collection) CharacterView
         5
         6
         7 */
    
    0 讨论(0)
提交回复
热议问题