János János - 6 months ago 11
Swift Question

How to pick capital letters from a Swift string?

I need capital letters from a string. With

NSString
it was sth like:

for (var i = 0; i<str.length; i++) {

let c = str.characterAtIndex(i)

if c >= 'A' && c < 'Z' {
//..
}
}


In Swift it starts like:

for (var i = 0; i<countElements(str); i++) {
//..
}


But I do not know i.e. how to pick i-th character, I am checking this

Answer

For example this work fine in Swift :

var st = "Hello World"

for ch in st {
   if ch >= "A" && ch <= "Z"{
      println(ch)
   }
}

And print

H
W

Or you could this instead :

var range = "A"..."Z"

for ch in st {
   if range.contains(String(ch)) {
      println(ch)
  }
}

Or the solution of @Gabrielle updated to Swift 2.0:

func capitalLetters(s: String) -> [Character] {
    return s.characters.filter { ("A"..."Z").contains($0) }
}

capitalLetters("fOo BAr") // ["O", "B", "A"]