3 Amazing Ways of Using Python Syntax in Swift

Original article was published on Artificial Intelligence on Medium

Destructuring

Destructuring allows us to assign more than one variable at a time on a single line. This is commonly used in Python as shown below:

#Pythonx, y = (5, 11)
a, b = b, a
a,b = b, a + b

Doing the same stuff in Swift is not seen very often in codebases. Nevertheless, it is very handy for pulling apart tuples into multiple values. Or even swapping variables like Python. The following Swift snippet shows a few destructuring examples:

//Swiftfunc getUserDetails() -> (name: String, password: String) {
return ("Swift", "beta5.3")
}
let (username, password) = getUserDetails()var a = 10
var b = 20
(a, b) = (b, a)

The last piece of code that does swapping in place is a lot easier to comprehend that doing it with a third variable in Swift. Do note, that unlike Python syntax, using a parentheses in Swift destructuring is mandatory.