【问题标题】:What is the name of the parameter before the method in Swift?Swift中方法之前的参数名称是什么?
【发布时间】:2016-01-19 18:41:03
【问题描述】:
optional func locationManager(_ manager: CLLocationManager,
           didUpdateLocations locations: [CLLocation])

didUpdateLocations 是什么?使用这样一个名字的原因是什么?我认为一般来说,用其他方法。

【问题讨论】:

  • 您可能需要清理您的问题,以便我们确切知道您要查找的内容并删除任何错误答案。

标签: swift cllocationmanager locationmanager


【解决方案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 是您在实际实现中使用的内部地址。

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

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

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

print(didUpdateLocations) // ugly variable name

或

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

【讨论】:

    【解决方案2】:

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

    函数参数名称

    函数参数有一个外部参数名和一个本地参数名。外部参数名称用于标记传递给函数调用的参数。在函数的实现中使用本地参数名称。

    【讨论】:

    • 这不是问题所在,听起来他的代码是他正在寻找的一个例子
    • Swift中方法前的参数名称是什么?
    • 我也不理解反对票。参考和引用很好,完美地反映了 OP 的要求 - 我包含了更多的解释,因为我觉得这个答案中缺少这些 - 但远不是反对 +1 的理由
    • 我觉得这句话的回答比我能解释的任何方式都好,而解释只会把事情搞得更糟
    • Martin S,请不要同时选择两个作为正确答案,您只能选择 1。当您获得足够的代表进行投票时,您可以回到这个问题并为答案投票。
    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2013-11-18
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多