Anatomy
func functionName (parameterName: parameterType) -> returnType {
statements to execute
return object
}
External & Local Parameter Names
Parameters can have two names in the function definition, one for external use and the other for local use. The external parameter is kind of like named parameters and used when then the function is called
func functionName (externalParameterName localParameterName: parameterType) -> returnType {
statements to execute
return object
}
An example of a named param being defined and called, the named param in the function call is critical to it working properly, if we remove the namedParam
from the function definition we can omit it in the function call and used just a normal string
func placeFirstLetterLast(namedParam myString: String) -> String {
var newString = myString
newString.append(firstCharacterOf(word: myString))
newString.remove(at: myString.startIndex)
return newString
}
placeFirstLetterLast(namedParam: "Hello")
Methods
Methods are just functions that belong to a particular type (class, struct, etc)
class MyViewController: UIViewController {
func myFunc(someParam: String) -> String {
return "hello, \(someParam)"
}
}
When we want to override a func from a superclass we need to explicitly tell swift we know we are doing that by preceding func
with override
A method can be marked final
which will prevent subclasses from being able to override it
Entire classes can also be marked final
Declaring static
before a method or property denotes that it is a method or property on the type itself, not on instances of the type. For example if we consider the type Double
which has a number of static vars and funcs on it's type, one of which will give us pi
(Double.pi
). We access pi
by calling it on the Double
type itself.