2017-03-17 75 views
1

我讀蘋果文檔的時候我就落到了這片語法:需要說明的雙標記函數聲明

struct Point { 
    var x = 0.0, y = 0.0 
    mutating func moveBy(x deltaX: Double, y deltaY: Double) { 
     x += deltaX 
     y += deltaY 
    } 
} 
var somePoint = Point(x: 1.0, y: 1.0) 
somePoint.moveBy(x: 2.0, y: 3.0) 
print("The point is now at (\(somePoint.x), \(somePoint.y))") 
// Prints "The point is now at (3.0, 4.0)" 

有人能解釋爲什麼moveBy(x deltaX: Double, y deltaY: Double)對參數的雙標籤?

回答

2

短的答案:第一個參數的標籤用於外部呼叫者,第二個用於在本地法使用。

func moveBy(x deltaX: Double, y deltaY: Double)當調用看起來如下:moveBy(x: 1, y: 1),但內部的方法deltaXdeltaY標籤被使用。

這種命名方式沒有必要,你可以聲明方法func moveBy(x: Double, y: Double),所以xy將用在方法裏面。

爲了支持傳統風格,因此來自調用者範圍的方法看起來像moveBy(1, 1),您應該將_作爲第一個參數標籤:func moveBy(_ deltaX: Double, _ deltaY: Double)。 CocoaTouch使用這種聲明來支持傳統的obj-c接口(例如:func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool)。

1

仔細查看蘋果documentation。它與連接參數名稱

可以覆蓋參數標籤的默認行爲與 一個下列形式:

參數標籤參數名:參數類型

_參數名:參數類型

2

第一標籤是參數標籤標籤參數名稱

從蘋果文檔

每個函數參數同時具有參數標籤和參數 名。參數標籤在調用函數時使用;每個 參數在其之前的參數標籤 中被寫入函數調用中。該參數名稱用於執行 函數。默認情況下,參數使用其參數名稱作爲它們的參數標籤 。

用法

func foo(with hoge: Int) { 
    return hoge * 2 
} 


let A = foo(with: 2) // A = 4;