Code Katas in Swift (#3 Stop gninnipS My sdroW!)

Code Kata ー A way to train

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

Example playground

The Solution

Extra challenge mode

The map() Function in Swift

func properize(name: String) -> String {
return "Mr. " + name
}

let cats = ["Buttons", "Miruku", "Kochan", "Sunshine", "Patches"]

let fancyCats = cats.map(properize)
print(fancyCats) // ["Mr. Buttons", "Mr. Miruku", "Mr. Kochan", "Mr. Sunshine", "Mr. Patches"]
let cats = ["Buttons", "Miruku", "Kochan", "Sunshine", "Patches"]
let fancyCats = cats.map({ (name: String) -> String in
return "Mr. " + name
})
print(fancyCats) // ["Mr. Buttons", "Mr. Miruku", "Mr. Kochan", "Mr. Sunshine", "Mr. Patches"]
["Buttons", "Miruku", "Kochan", "Sunshine", "Patches"].map({"Mr. \($0)"})
// ["Mr. Buttons", "Mr. Miruku", "Mr. Kochan", "Mr. Sunshine", "Mr. Patches"]

The one liner

func spinWords(in sentence: String) -> String {
String(sentence.components(separatedBy: " ").map({
$0.count > 4 ? $0.reversed() + " " : $0 + " "
}).joined().dropLast())
}

P.S.

--

--

Hey, I’m Jason Cheladyn. Going back to the coding world after 6 years of teaching English in Japan. https://www.twitter.com/liyicky https://www.liyicky.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Liyicky

Hey, I’m Jason Cheladyn. Going back to the coding world after 6 years of teaching English in Japan. https://www.twitter.com/liyicky https://www.liyicky.com