Home > OS >  How to get function's parameter value without parameter name in swift?
How to get function's parameter value without parameter name in swift?

Time:03-27

func test(_: [Int]) {
  print("xxx")
}

test([1,2,3])

I saw this code is valid in swift, how can I get the value passed into test?

CodePudding user response:

To explicitly answer your question:

how can I get the value passed in test?

You can't, in the same way that after

let _ = someFunction() 

you have no way to get at the return value of someFunction. That's really the whole point of _ which basically means "I'm ignoring this intentionally".

CodePudding user response:

In order to get the parameter value inside the function, you have to specify the parameterName. Swift's function has this kind of structure :

func someFunction(argumentLabel parameterName: Int) {
    // In the function body, parameterName refers to the argument value
    // for that parameter.
}

where argumentLabel is used on the function caller, for example

func eat(byWhom person: String){}

would become

eat(byWhom: "Victor") 

in the caller code. On the other hand, you can get the "Victor" value from the parameterName :

func eat(byWhom person: String){
    print(person) // should print "Victor"
}

CodePudding user response:

create function like this

func test(_ value: [Int]) { }

and then you can call it like this.

test([1,2]) without mentioning the parameter name.

CodePudding user response:

There's no chance to get functions parameter value w/o its name. That is why it is being used. But you can do this:

func test(_ value: [Int]) {
  print(value)
}


test([1,2,3])
  • Related