What is the meaning of the '#' mark in swift language

前端 未结 5 975
天涯浪人
天涯浪人 2020-11-28 13:37

I have seen code like this:

func hello(name: String, #helloMessage: String) -> String { 
    return \"\\(helloMessa         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 13:51

    This has changed in Swift 2:

    now you specify an external parameter name before the internal one, instead of using # to force the existing name.


    According to the convention, the method name contains the action verb and the first parameter is not specified when calling the method:

    func sayHiFrom(sender: String, to: String) {
        print("Hi from \(sender) to \(to)!")
    }
    
    sayHiFrom("Jules", to: "Jim")
    

    Specifying an internal parameter name

    This time the second parameter has a different name for using inside the method, without changing the external name. When there is two names for a parameter, the first one is external and the second one is internal:

    func sayHiFrom(sender: String, to receiver: String) {
        print("Hi from \(sender) to \(receiver)!")
    }
    
    sayHiFrom("Jane", to: "John")
    

    Forcing an external parameter name

    You can force the first parameter to have an external name:

    func sayHi(from sender: String, to receiver: String) {
        print("Hi from \(sender) to \(receiver)!")
    }
    
    sayHi(from: "Joe", to: "Jack")
    

    In this case, it's better that the method name does not contain the action term, because the forced parameter name already plays its role.

    Forcing no external parameter names

    You can also remove the parameter name for other parameters by preceding them with _ (underscore):

    func sayHi(sender: String, _ receiver: String) {
        print("Hi from \(sender) to \(receiver)!")
    }
    
    sayHi("Janice", "James")
    

提交回复
热议问题