Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make function that some parameters not required in when call it in iOS Swift 3?

I wanna make function without some required parameters like this:

func myMethod(Name name:String,Age age:Int){
    print(name)
}

//call
myMethod(Name:"Donald")

Is this can be?

like image 371
reza_khalafi Avatar asked Nov 30 '22 22:11

reza_khalafi


1 Answers

You just have to make them nilable.

func myMethod(name name: String? = nil, age age: Int? = nil) {
    print(name!)
}

Notice: when yo make parameters optional, you have to be careful about how to unwrap them. usually using if let syntax is helpful.

func myMethod(name name: String? = nil, age age: Int? = nil) {
  if let name = name {
     print(name)
  }
}

you can also provide default value for them:

func myMethod(name name: String? = "Donald", age age: Int? = 10) {
    print(name!)
}
like image 188
Mina Avatar answered Dec 04 '22 10:12

Mina