Your solution of the challenge 2 doesn’t really answer the point “If no parameters pass to the function, it will return the string “none”.” but more “If the sum of the 2 strings is empty then return none”
please someone explain to me how challenge one works. How on earth does rearranging a tuple swap the values of two variables?? I understand tuples (i thought), inout functions etc. I feel like ive never encountered this before however.
var x = 1
var y = 2
how does
(x,y) = (y,x)
have anything to do with the values assigned to x and y?
Imagine tuples like little anonymous arrays (like closures are anonymous functions - you construct them only to use them once - most often to assign them to a variable).
You can access the members of a tuple by their numeric index (since they are not named)
3 . The map is unnecessary since in reduce, one can just return the input number like so
func sumAny(params: Any...) -> String {
return String(params.reduce(0) {
if let string = $1 as? String {
if string.isEmpty {
return $0 - 10
} else if let int = Int(string) where int > 0 {
return $0 + int
}
} else if let int = $1 as? Int {
return int == 0 ? $0 - 10 : $0 + int
}
return $0
})
}
Not a huge fan of the solution for #4.
I don’t think the solution is “Swifty” at all. It’s just general programming challenge. No reason to be on this thread…
I think introducing stride would make it more Swifty like so:
func countFrom(from: Int, to: Int) {
assert(from < to)
print(from.stride(through: to, by: 1).reduce("") { return $0+"\($1)" })
}
Plus, since the original post is old, print no longer prints in-line, but adds a line break at the end. So for the current 2.2 syntax, the following would be the correct answer:
func altCountFrom(from: Int, to: Int) {
guard from <= to else { return }
print(from, terminator: from < to ? "" : "\n")
altCountFrom(from+1, to: to)
}