Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. //There are two ways to write a method in Swift:
  2. //1. The standard way, as with other languages:
  3. func add(number1: Int, number2: Int) -> Int {
  4. return number1 + number2
  5. }
  6. //You call it the 'standard' way:
  7. add(number1: 1, number2: 2)
  8.  
  9. //2. The other way (that allows you more flexibility--both where the method is called and within the body of your method--by splitting up the paramters into a set of labels):
  10. func add(number number1: Int, toNumber number2: Int) -> Int {
  11. //Inside the body of the method, I get to use the arguments with the names, as I did previously:
  12. return number1 + number2
  13. }
  14. //However, the point where the method is called is a bit cleaner (I no longer expose argument names such as 'number1' to the user of my method, even though that's how I like to use it *inside* my method):
  15. add(number: 1, toNumber: 2)
  16.  
  17. //But Swift allows you to go a step further, by omitting the need to have the 'number' label in 'add(number: 1, toNumber: 2)'
  18. //Why would you want to remove 'number' as a label for the parameter? Because there is still a way to reduce the length of my method while still retaining clarity.
  19. // But first, a quick introduction to the underscore '_' operator: With Swift, if you don't care about a certain value but you acknowledge its existence, you use the underscore operator. (This is an over-simplification)
  20. // eg: _ = add(number: 1, toNumber: 2) <--This implies you just want to add 1 to 2 and don't care for the returned value
  21.  
  22. //Here's how Swift allows you more flexibility:
  23. func add(_ number1: Int, to number2: Int) -> Int {
  24. //I still get to preserve my obsessive desire to use the 'number1' and 'number2' parameters within my body...
  25. return number1 + number2
  26. }
  27.  
  28. //...but I've completely obviated the need to have the calling site see any labels except ones needed for clarity (the 'to' label for the second paramter):
  29. add(1, to: 2)
  30.  
  31. //This is the shortest this method can get while still retaining clarity--the goal of writing 'Swifty' APIs. (It also reads like a sentence--'Add one to two'--which, in my opinion, is the best way to see if you're creating great APIs)
  32.  
  33.  
  34. //BONUS: You could go all-out on brevity with Swift APIs, if that is your cup of tea:
  35. func add(_ number1: Int, _ number2: Int) -> Int {
  36. //Still sticking by my obession for retaining paramter names...
  37. return number1 + number2
  38. }
  39. //...while removing all parameter labels:
  40. add(1, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement