How to do string swift enum in string in Swift?

For example, I have a regular quick enumeration

for (var myChar:Character) in "Hello World!"
{//code }

      

This works great and I can do whatever I want with every character on that line. But what if I want to use a string instead of a character like this

for ( var myStr : String) in "Hello World!"//this is error
{
   switch myStr
{
case "Hello":
//code
case "World!":
//code
default:
break
}
}

      

Can this be done? Thanks to

+3


source to share


3 answers


You can use componentsSeparatedByCharactersInSet

to split a string into an array of strings:

import Foundation // not necessary if you import UIKit or Cocoa

for myStr in "Hello World!".componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:" ")) {
    switch myStr {
    case "Hello":
        println("well hello there")
    case "World!":
        println("the whole world")
    default:
        println("something else")
    }
}

      

NSCharacterSet(charactersInString:" ")

You can also use instead NSCharacterSet.whitespaceCharacterSet()

or NSCharacterSet.whitespaceAndnewlineCharacterSet()

depending on what characters separate your words.




If your words are separated by a single space, you can use an abbreviation:

for myStr in "Hello World!".componentsSeparatedByString(" ") {
    ...
}

      

+2


source


You cannot just list lines line by line. you need to specify which ranges the substring should have.

Here it is done with the words:

var str:String = "Hello World!"
str.enumerateSubstringsInRange(Range<String.Index>(start:str.startIndex , end: str.endIndex), options: NSStringEnumerationOptions.ByWords) { (substring, substringRange, enclosingRange, stop) -> () in
    switch substring
    {
    case "Hello":
        println("Hi")
    case "World":
        println("universe")
    default:
        break
    }
}

      



but in fact I am cheating. In your code, you want to switch to World!

, but I am using World

. I do this in the same way that non-alphanumeric characters are ignored in a text enum.

But we have all the information to fix this.

var str:String = "Hello World!"
str.enumerateSubstringsInRange(Range<String.Index>(start:str.startIndex , end: str.endIndex), options: NSStringEnumerationOptions.ByWords) { (substring, substringRange, enclosingRange, stop) -> () in

    var enclosingStr = str.substringWithRange(enclosingRange)
    enclosingStr = enclosingStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    switch enclosingStr
    {
    case "Hello":
        println("Hi")
    case "World!":
        println("universe")
    default:
        break
    }
}

      

+1


source


In Swift 2.0, I am using

let line = "Hello, world"
for (index, value) in line.characters.enumerate() {
  // do something
}

      

+1


source







All Articles