What is _: in Swift telling me?

后端 未结 3 1824
日久生厌
日久生厌 2020-11-28 23:24

What does the lone underscore mean in function definitions?

e.g. map(_:)

I understand that when defining functions I can do:

fun         


        
3条回答
  •  伪装坚强ぢ
    2020-11-28 23:34

    The _ is used to define that the parameter is not named

    If you have multiple _ it states that you do not need to name the parameters in your function call

    func myFunc(name:String, _ age:String){
    }
    
    myFunc(“Milo", "I'm a really old wizard")
    

    If you do not use the underscore you would use

    myFunc(“Milo”, age: "I'm a really old wizard")
    

    The _ is not necessary in function calls. It is just used to indicate that something does not to have a name.

    In regards to how you would refer to your function, You would not have to pass any name for the function call.
    But since you also don’t define a parameter type this seems to me like a invalid example (it at least doesn’t work in xCode 7 with swift 2.0)

    Edit:
    Since swift 3.0

    myFunc(name: “Milo”, age: "I'm a really old wizard")
    

    Should be used

提交回复
热议问题