gpt4 book ai didi

ios - swift : missing argument label 'xxx' in call

转载 作者:IT王子 更新时间:2023-10-29 04:57:47 24 4
gpt4 key购买 nike

func say(name:String, msg:String) {
println("\(name) say \(msg)")
}

say("Henry","Hi,Swift") <---- error because missing argument label 'msg' in call

我需要用

   say("Henry",msg:"Hi,Swift")

为什么?如果我在 func 中放置了两个以上的 var,那么当我调用这个 func 时我需要写 var name 而不是第一个 var
真的很麻烦,我在 iBook Swift 教程中没有看到任何解释。

最佳答案

一个可能的原因是它实际上是一种方法。方法非常偷偷摸摸,它们看起来就像常规函数,但它们的行为方式不同,让我们看一下:

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

// Note that there's been an update in Swift 2 and the above function would have to be written as:

func externalInternalShared(paramOne paramOne: Int, #paramTwo: Int) {
print("externalInternalShared: \(paramOne) : \(paramTwo)")
}

externalInternalShared(paramOne: 1, paramTwo: 4)

现在这是有趣的部分,在类中声明一个函数,它不再是一个函数......而是一个方法

class SomeClass {
func someClassFunctionWithParamOne(paramOne: Int, paramTwo: Int) {
println("someClassFunction: \(paramOne) : \(paramTwo)")
}
}

var someInstance = SomeClass()
someInstance.someClassFunctionWithParamOne(1, paramTwo: 4)

这是方法行为设计的一部分

Apple 文档:

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.

注意自动完成: enter image description here

关于ios - swift : missing argument label 'xxx' in call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com