Category: Swift

Optional Value In Swift

An optional provides a variable that can be assigned to contain a value, or left or assigned as nil. The pattern below creates and optional variable (note the ?), assigns it a value, then checks if that value has been assigned.

[c collapse=”False”]
//create optional
var optionalName: String?
//assign value
optionalName = "Billy"
// check for value
if let name = optionalName {
greeting = "Hello, \(name)"
}
[/c]

Recursion in Swift

Recursion is when a method or function calls itself.

[c collapse=”False”]
//depending on what number you give to N, the function will call itself that many times, subtracting 1 from the original N each time through to pass as an argument.

func thisFunctionCallsItself(thisManyTimes: Int) {

//The next few lines are to set up the proper suffix on the printed result string
var mySuffix = String()
//let’s get the last two digits from thisManyTimes
let lastTwoDigits = thisManyTimes % 100
switch lastTwoDigits {
case 10…20:
mySuffix = "th"
default:
//get the last digit
let lastDigit = thisManyTimes % 10
switch lastDigit {
case 1:
mySuffix = "st"
case 2:
mySuffix = "nd"
case 3:
mySuffix = "rd"
default:
mySuffix = "th"
}
}
//OK that it.

//below is where the function calls itself
if thisManyTimes != 0 {
thisFunctionCallsItself (thisManyTimes – 1)
print("This is the \(thisManyTimes)\(mySuffix) time that this function has called itself.")
}

}

//call the function.

thisFunctionCallsItself(10)

[/c]