Are if-else statements also a form of function?

I came across this example in Apple's official Swift mannual: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48



class HTMLElement {

let name: String

let text: String?

lazy var asHTML: () -> String = {

if let text = self.text {

return "<\(self.name)>\(text)</\(self.name)>"

} else {

return "<\(self.name) />"

}

}

init(name: String, text: String? = nil) {

self.name = name

self.text = text

}

deinit {

print("\(name) is being deinitialized")

}

}


The asHTML property is of type () -> String, in other words, asHTML takes functions that have no parameters but return a String.

The code after = is asHTML's default property value which is an if-else statement that returns a String.


asHTML's type is a function that returns a string, but the given default value is an if-else statement that returns a string.


So I'm wondering are if-else statements also a form of function?

No. It's just a by-product of the closure that allows the if/else statement to look a bit like an expression.


If you want a truly functional form of conditional expression, there's the "? :" ternary operator:


     return a >= b ? a : b


or the nil-coalescing operator:


     return someOptionalText ?? "it's nil"


Also, the value of "asHTML" is a closure, not a function. Closures and functions are almost the same thing, but for functions, the argument keywords are part of the type, whereas for closures they are not.

Are if-else statements also a form of function?
 
 
Q