Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //There are two ways to write a method in Swift:
- //1. The standard way, as with other languages:
- func add(number1: Int, number2: Int) -> Int {
- return number1 + number2
- }
- //You call it the 'standard' way:
- add(number1: 1, number2: 2)
- //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):
- func add(number number1: Int, toNumber number2: Int) -> Int {
- //Inside the body of the method, I get to use the arguments with the names, as I did previously:
- return number1 + number2
- }
- //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):
- add(number: 1, toNumber: 2)
- //But Swift allows you to go a step further, by omitting the need to have the 'number' label in 'add(number: 1, toNumber: 2)'
- //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.
- // 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)
- // eg: _ = add(number: 1, toNumber: 2) <--This implies you just want to add 1 to 2 and don't care for the returned value
- //Here's how Swift allows you more flexibility:
- func add(_ number1: Int, to number2: Int) -> Int {
- //I still get to preserve my obsessive desire to use the 'number1' and 'number2' parameters within my body...
- return number1 + number2
- }
- //...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):
- add(1, to: 2)
- //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)
- //BONUS: You could go all-out on brevity with Swift APIs, if that is your cup of tea:
- func add(_ number1: Int, _ number2: Int) -> Int {
- //Still sticking by my obession for retaining paramter names...
- return number1 + number2
- }
- //...while removing all parameter labels:
- add(1, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement