方法命名问题Swift

Rya*_*ner 6 swift

我希望创建一个等效的Swift方法

+ (void)insertFileWithService:(GTLServiceDrive *)service
                    title:(NSString *)title
Run Code Online (Sandbox Code Playgroud)

当我输入

func insertFileWithService(service: GTLServiceDrive,
    title title: String,
Run Code Online (Sandbox Code Playgroud)

我得到一个警告标题标题可以更简洁地表达为#title

但当我将其更改为func insertFileWithService(service:GTLServiceDrive,#title:String

我得到一个警告参数title中的无关'#'已经是关键字参数名称

我应该忽略这些警告并将其归结为Beta中的错误吗?

jac*_*ted 5

我不相信这是一个错误,事实上,这就是语言的设计方式:


来自Apple的资料(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
    }
}
Run Code Online (Sandbox Code Playgroud)

此incrementBy方法有两个参数 - amount和numberOfTimes.默认情况下,Swift仅将金额视为本地名称,但将numberOfTimes视为本地名称和外部名称.您调用该方法如下:

let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15
Run Code Online (Sandbox Code Playgroud)

您不需要为第一个参数值定义外部参数名称,因为其目的在函数名称incrementBy中是明确的.但是,第二个参数由外部参数名称限定,以便在调用方法时使其目的明确.

此默认行为有效地将方法视为在numberOfTimes参数之前编写了哈希符号(#)


基本上,对于类中的方法,第一个参数仅默认为内部参数名.所有后续参数名称默认为外部名称,默认情况下外部名称是参数名称.因此,这#是多余的.

func insertFileWithService(service: GTLServiceDrive, title: String)
Run Code Online (Sandbox Code Playgroud)

相当于

func insertFileWithService(service: GTLServiceDrive, #title: String)
Run Code Online (Sandbox Code Playgroud)

对于方法,而不是函数.这就是你收到警告的原因.