reza_khalafi
reza_khalafi

Reputation: 6534

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?

Upvotes: 8

Views: 12058

Answers (1)

Mina
Mina

Reputation: 2212

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!)
}

Upvotes: 26

Related Questions