Search code examples
swiftfunctionoption-type

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?


Solution

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