Default Parameter Values
Swift supports default parameters unlike in Objective-C where there is no concept of default parameter values. The following is an example of a function that adds punctuation to a sentence, where you declare a period to be the default punctuation:
func addPunctuation(#sentence: String, punctuation: String = ".") -> String { return sentence + punctuation}
If a parameter is declared with a default value, it will be made into an external parameter. If you’d like to override this functionality and not include an external parameter, you can insert an underscore (_
) as your external variable. If you wanted a version of addPunctuation
that had no external parameters, its declaration would look ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.