How can I capitalize all the strings inside an array directly?

Rhenz picture Rhenz · Feb 24, 2015 · Viewed 7.2k times · Source

I'm learning swift. I've been trying this in Playground. I have no idea why the string is not being capitalized here. Or is there any other way to capitalize the string inside the array directly?

Here's my code.

var dogNames = ["Sean", "fido", "Sarah", "Parker", "Walt", "abby", "Yang"]

for index in 0..<dogNames.count {
    var dogName = dogNames[index].capitalizedString
    dogNames.removeAtIndex(index)
    dogNames.append(dogName)
}

When I try to display again the variable dogNames. The strings inside are not being capitalized.

Answer

Leo Dabus picture Leo Dabus · Feb 24, 2015

update: Xcode 8.2.1 • Swift 3.0.2

var dogNames = ["Sean", "fido", "Sarah", "Parker", "Walt", "abby", "Yang"]

for (index, element) in dogNames.enumerated() {
    dogNames[index] = element.capitalized
}

print(dogNames)   // "["Sean", "Fido", "Sarah", "Parker", "Walt", "Abby", "Yang"]\n"

This is a typical case for using map():

let dogNames1 = ["Sean", "fido", "Sarah", "Parker", "Walt", "abby", "Yang"].map{$0.capitalized}

A filter() sample:

let dogNamesStartingWithS = ["Sean", "fido", "Sarah", "Parker", "Walt", "abby", "Yang"].filter{$0.hasPrefix("S")}

dogNamesStartingWithS   // ["Sean", "Sarah"]

you can combine both:

let namesStartingWithS = ["sean", "fido", "sarah", "parker", "walt", "abby", "yang"].map{$0.capitalized}.filter{$0.hasPrefix("S")}

namesStartingWithS   // ["Sean", "Sarah"]

You can also use the method sort (or sorted if you don't want to mutate the original array) to sort the result alphabetically if needed:

let sortedNames = ["sean", "fido", "sarah", "parker", "walt", "abby", "yang"].map{$0.capitalized}.sorted()

sortedNames  // ["Abby", "Fido", "Parker", "Sarah", "Sean", "Walt", "Yang"]