Swift中方法之前的参数名称是什么?

时间:2016-01-19 18:41:03

标签: swift cllocationmanager locationmanager

optional func locationManager(_ manager: CLLocationManager,
           didUpdateLocations locations: [CLLocation])

什么是didUpdateLocations?使用这样一个名字的原因是什么?我认为通常采用其他方法。

2 个答案:

答案 0 :(得分:1)

由于@KnightOfDragon已经提到Swift区分内部和外部参数名称。

考虑以下示例:

class Bla : NSObject, CLLocationManagerDelegate {
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations)
    }
}

let bla = Bla()
bla.locationManager(someLocationManager, didUpdateLocations: [])

didUpdateLocations是调用函数时使用的外部参数名称。 locations是您在实际实施中使用的内部版本。

这种行为的原因是,在调用方法时,您清楚地知道每个参数的用途,功能的作用以及您可以像普通的英语句子一样阅读调用:
“locationManager someLocationManager didUpdateLocations(to)[]”

另一方面,在实现该函数时,您不希望将可读名称didUpdateLocations作为变量名称处理,但您要使用的是locations数组。

只有一个名字会产生次优结果,因为你要写

print(didUpdateLocations) // ugly variable name

bla.locationManager(someLocationManager, locations: []) 
// what the **** is this function doing

答案 1 :(得分:0)

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID166

  

功能参数名称

     

函数参数具有外部参数名称和本地参数名称。外部参数名称用于标记传递给函数调用的参数。本地参数名称用于函数的实现。