EnumerateSubstringsInRange in Swift

Rewrite existing c (ios) object code in Swift, encountering some problems with the enumerateSubstringsInRange method. Can someone help me convert the following code to Swift?

[contentString enumerateSubstringsInRange:NSMakeRange(0,[contentString length])
                               options:NSStringEnumerationByComposedCharacterSequences
                               usingBlock: ^(NSString *substring,
                               NSRange substringRange, 
                               NSRange enclosingRange,BOOL *stop) {

          if(substring.length >= 2) {
              /* my code goes here */
          }
    }
]
+4
source share
4 answers

Try the following:

contentString.enumerateSubstringsInRange(NSMakeRange(0, (contentString as NSString).length), options: NSStringEnumerationOptions.ByComposedCharacterSequences) { (substring, substringRange, enclosingRange, stop) -> () in
    if((substring as NSString).length >= 2) {
        NSLog("%@", substring)
    } 
}

Note , in order to access the length property String, you need to pass it in NSStringas shown above.

+2
source

For Swift version 3.0.2 use the following code

         string.enumerateSubstrings(in: NSMakeRange(0, (string as NSString).length), options: NSString.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, stop) -> () in

        let objCString:NSString = NSString(string:substring!)
        let hs: unichar = objCString.character(at: 0)
    }
0
source

.

       contentString.enumerateSubstrings(in: NSRange(location: 0, length: contentString.length), options: NSStringEnumerationByComposedCharacterSequences, usingBlock: {(_ substring: String, _ substringRange: NSRange, _ enclosingRange: NSRange, _ stop: Bool) -> Void in
        if substring.length >= 2 {
            /* my code goes here */
        }
    })

, , . https://iswift.org/try. .

0

let contentString: NSString = "string";

contentString.enumerateSubstrings (in: NSRange.init (location: 0, length: contentString.length), options: NSString.EnumerationOptions.byComposedCharacterSequences) {(substring, substringRange, enclosingRange, stop) to // your code}

-1
source

All Articles