I’m surprised no one posted anything…
Alternative solution for #5
func reverseString(string: String) {
guard !string.isEmpty else { return }
print(string.substringFromIndex(string.endIndex.predecessor()), terminator: string.startIndex < string.endIndex.predecessor() ? "" : "\n")
reverseString(string.substringToIndex(string.endIndex.predecessor()))
}
func altReverseString(string: String) -> String {
guard !string.isEmpty else { return "" }
return string.substringFromIndex(string.endIndex.predecessor()) + altReverseString(string.substringToIndex(string.endIndex.predecessor()))
}
Challenge #6:
func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else { return "" }
return lhs + (lhs * (rhs-1))
}
Challenge #7:
func isSuccess(success: Bool) -> String {
return ["error", "success!"][Int(success)]
}
print(isSuccess(doWork()))
Final:
func countHand(deck: [Card]) -> Int {
return deck.enumerate().reduce(0) {
guard $1.index < deck.count - 1 else { return $0 }
if case Rank.Num(5) = $1.element.rank, case Rank.Ace = deck[$1.index+1].rank where $1.element.suit == .Diamonds {
return $0 + 100
} else if case Rank.Num(let num) = deck[$1.index+1].rank where $1.element.suit == .Hearts && [3, 5, 7, 9].contains(num) {
return $0 + num * 2
}
return $0
}
}
Hey bossagroove I’m glad you’re enjoying the “ninja” articles. They are about 2 years old (when Swift was in early beta) and I this was before the last big update to the forums on raywenderlich.com so I think the comments are somewhere on the forums, which was the old system to track comments per article.
Here is my solution for #5 I know i use variables but in my case it makes the code a little bit cleaner.
extension String {
func reversed() -> String {
return reverseString(text: self, lastCharacters: "")
}
fileprivate func reverseString(text:String, lastCharacters: String) -> String {
if let lastCharacter = text.characters.last {
let subText = text.substring(to: text.index(text.endIndex, offsetBy: -1))
return reverseString(text: subText, lastCharacters: lastCharacters + String(lastCharacter))
} else {
return lastCharacters
}
}
}
"Reverse Me".reversed()
I know it is late, but still wanted to paste my solution to the final challenge.
FinalSwiftChallenge.swift
func countHand(_ cards: [Card]) -> Int {
let addCards: (Card, Card) -> Int = {
if $0.suit == .Hearts, case let .Num(number) = $1.rank, number % 2 != 0 { return number * 2 }
else if $0.suit == .Diamonds, case .Num(5) = $0.rank, case .Ace = $1.rank { return 100 }
return 0
}
var previousCard: Card? = nil
return cards.reduce(0, { var result = $0
if let previousCard = previousCard { result += addCards(previousCard, $1) }
This file has been truncated. show original
This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!