Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Naming Issues Swift

Tags:

swift

I wish to Create a Swift Method Equivalent to

+ (void)insertFileWithService:(GTLServiceDrive *)service
                    title:(NSString *)title

When I type

func insertFileWithService(service: GTLServiceDrive,
    title title: String,

I get a warning title title can be expressed more succinctly as #title

But when I change it to func insertFileWithService(service: GTLServiceDrive, #title: String

I get a warning extraneous '#' in parameter title is already the keyword argument name

Should I ignore these warnings and chalk it up to a bug in Beta ?

like image 820
Ryan Heitner Avatar asked Jun 10 '14 14:06

Ryan Heitner


Video Answer


1 Answers

I do not believe this is a bug, in fact, this is how the language was designed to work:


From Apple's Stuff (https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html#//apple_ref/doc/uid/TP40014097-CH15-XID_300):

class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTimes: Int) {
        count += amount * numberOfTimes
    }
}

This incrementBy method has two parameters—amount and numberOfTimes. By default, Swift treats amount as a local name only, but treats numberOfTimes as both a local and an external name. You call the method as follows:

let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15

You don’t need to define an external parameter name for the first argument value, because its purpose is clear from the function name incrementBy. The second argument, however, is qualified by an external parameter name to make its purpose clear when the method is called.

This default behavior effectively treats the method as if you had written a hash symbol (#) before the numberOfTimes parameter


Basically, for Methods inside a class, the first parameter defaults to an internal parameter name only. All subsequent parameter names default to external names where the external name is the parameter name by default. Thus, the # is redundant.

func insertFileWithService(service: GTLServiceDrive, title: String)

Is equivalent to

func insertFileWithService(service: GTLServiceDrive, #title: String)

For Methods, not for Functions. This is why you are getting a warning.

like image 188
jacobhyphenated Avatar answered Nov 10 '22 07:11

jacobhyphenated