Guest User

Untitled

a guest
Feb 17th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. Default and Optional Arguments is one of the handy feature of Swift and was missing in Objective C.
  2.  
  3. 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.
  4.  
  5. Few examples:
  6.  
  7. Default Arguments:
  8.  
  9. func displayName(firstName: String = "John", middleName: String = "Smith", lastName: String = "Jr") -> Void {
  10. print("\(firstName)"+" "+"\(middleName)"+" "+"\(lastName)")
  11. }
  12.  
  13. displayName() \\ -> John Smith Jr
  14.  
  15. displayName(middleName:"Trev") \\ -> John Trev Jr
  16.  
  17. displayName(middleName:"Trev", lastName: "Sr") \\ -> John Trev Sr
  18.  
  19. Optional Arguments
  20.  
  21.  
  22. func displayName(firstName: String? = nil, middleName: String? = nil, lastName: String? = nil) -> Void {
  23.  
  24. if let fName = firstName {
  25. print("\(fName)")
  26. }
  27.  
  28. if let mName = middleName {
  29. print("\(mName)")
  30. }
  31.  
  32. if let lName = lastName {
  33. print("\(lName)")
  34. }
  35. }
  36.  
  37. displayName(firstName: "John", middleName: "Smith", lastName: "Jr")
  38.  
  39. Output:
  40.  
  41. John
  42. Smith
  43. Jr
  44.  
  45. displayName(firstName: "John", middleName: "Smith")
  46.  
  47. Output:
  48.  
  49. John
  50. Smith
  51.  
  52. displayName(firstName: "John", lastName: "Jr")
  53.  
  54. Output:
  55.  
  56. John
  57. Jr
  58.  
  59. displayName(middleName: "Smith", lastName: "Jr")
  60.  
  61. Output:
  62.  
  63. Smith
  64. Jr
  65.  
  66. displayName(middleName: "Smith")
  67.  
  68. Output:
  69.  
  70. Smith
Add Comment
Please, Sign In to add comment