Skip to content

Instantly share code, notes, and snippets.

@ChenCodes
Last active June 1, 2017 21:18
Show Gist options
  • Save ChenCodes/70f781aa23733b9cea8a49bc8bc6c7b7 to your computer and use it in GitHub Desktop.
Save ChenCodes/70f781aa23733b9cea8a49bc8bc6c7b7 to your computer and use it in GitHub Desktop.
Sum All parameters (can be of different type)
func sumAll(objs: Any...) -> Int {
var sum = 0
for obj in objs {
if obj is Int {
sum += obj as! Int
} else if obj is String {
if let variable = Int(obj as! String) {
sum += variable
}
}
}
return sum
}
let result = sumAll(objs: "1", 2, 3, "-10.899","😎", -3)
print("\( result == 3 ? "👍🏻" : "👎🏻" )")
/*What this method does is that it loops through all of our parameters and checks to see if the object is of type Int or type String. If we find a parameter that's of type String but it cannot be converted to an Int, then we disregard it.
The cool trick here is that when we try doing Int(obj as! String) for the "-10.899", variable will be nil, so we don't go into that case. The reasoning behind this is that it doesn't work when you try to call the Int initializer on a string that contains a non-Int object.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment