注意,這個問題是在swift1.0時發生的,swift2.0中,好像統一了function 和 method 的定義,具體待正式版發佈後研究一下!express
今天在使用swift時發現,寫的func老是要求寫出第二個參數的外部變量名,很不理解,感受和書上說的function不同,查了一下,終於發現了緣由:寫在class內部的function叫作method,是特殊的functoin,系統會自動補上外部變量名,參看如下鏈接 http://stackoverflow.com/questions/24050844/swift-missing-argument-label-xxx-in-callswift
防止鏈接失效,截取部份內容以下:ide
One possible reason is that it is actually a method. Methods are very sneaky, they look just like regular functions, but they don't act the same way, let's look at this:ui
func funFunction(someArg: Int, someOtherArg: Int) { println("funFunction: \(someArg) : \(someOtherArg)") } // No external parameter funFunction(1, 4) func externalParamFunction(externalOne internalOne: Int, externalTwo internalTwo: Int) { println("externalParamFunction: \(internalOne) : \(internalTwo)") } // Requires external parameters externalParamFunction(externalOne: 1, externalTwo: 4) func externalInternalShared(#paramOne: Int, #paramTwo: Int) { println("externalInternalShared: \(paramOne) : \(paramTwo)") } // The '#' basically says, you want your internal and external names to be the same externalInternalShared(paramOne: 1, paramTwo: 4)
Now here's the fun part, declare a function inside of a class and it's no longer a function ... it's a methodthis
class SomeClass { func someClassFunctionWithParamOne(paramOne: Int, paramTwo: Int) { println("someClassFunction: \(paramOne) : \(paramTwo)") } } var someInstance = SomeClass() someInstance.someClassFunctionWithParamOne(1, paramTwo: 4)
This is part of the design of behavior for methodsspa
Apple Docs:code
Specifically, Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default. This convention matches the typical naming and calling convention you will be familiar with from writing Objective-C methods, and makes for expressive method calls without the need to qualify your parameter names.ci