Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Default and Optional Arguments is one of the handy feature of Swift and was missing in Objective C.
- With this feature we can have different arguments sequence for single method signature. This avoids forcing caller to pass values for all the arguments defined in the method signature.
- Few examples:
- Default Arguments:
- func displayName(firstName: String = "John", middleName: String = "Smith", lastName: String = "Jr") -> Void {
- print("\(firstName)"+" "+"\(middleName)"+" "+"\(lastName)")
- }
- displayName() \\ -> John Smith Jr
- displayName(middleName:"Trev") \\ -> John Trev Jr
- displayName(middleName:"Trev", lastName: "Sr") \\ -> John Trev Sr
- Optional Arguments
- func displayName(firstName: String? = nil, middleName: String? = nil, lastName: String? = nil) -> Void {
- if let fName = firstName {
- print("\(fName)")
- }
- if let mName = middleName {
- print("\(mName)")
- }
- if let lName = lastName {
- print("\(lName)")
- }
- }
- displayName(firstName: "John", middleName: "Smith", lastName: "Jr")
- Output:
- John
- Smith
- Jr
- displayName(firstName: "John", middleName: "Smith")
- Output:
- John
- Smith
- displayName(firstName: "John", lastName: "Jr")
- Output:
- John
- Jr
- displayName(middleName: "Smith", lastName: "Jr")
- Output:
- Smith
- Jr
- displayName(middleName: "Smith")
- Output:
- Smith
Add Comment
Please, Sign In to add comment