Home > Software design >  How to assign default parameter value in closure with swift?
How to assign default parameter value in closure with swift?

Time:01-12

I have a closure function and I want assign a default value in it but I am getting an error as Default argument not permitted in a tuple type

func getResponse(address: String, completion : @escaping ((_ lat : CLLocationDegrees, _ long : CLLocationDegrees, _ attributedPlaceName: String, _ placeId: String? = nil)->())) {
    
  }

CodePudding user response:

You need to do a old fashion overload instead, i.e.

with 3 params:

func getResponse(
    address: String,
    completion: @escaping (
        (
            _ lat: CLLocationDegrees,
            _ long: CLLocationDegrees,
            _ attributedPlaceName: String
        ) -> ()
    )
) {
    //
}

getResponse(address: "foo") { lat, long, attributedPlaceName in
    //
}

with 4 params:

func getResponse(
    address: String,
    completion: @escaping (
        (
            _ lat: CLLocationDegrees,
            _ long: CLLocationDegrees,
            _ attributedPlaceName: String,
            _ placeId: String?
        ) -> ()
    )
) {
    //
}

getResponse(address: "bar") { lat, long, attributedPlaceName, placeId in
    //
}

Although I honestly don't know why you would bother. If you just had the 4 param signature, you can ignore any parameters as you like by using a underscore, i.e.

getResponse(address: "bar") { lat, long, attributedPlaceName, _ in
    // 
}

CodePudding user response:

Instead of using multiple parameters, define a model to hold your data:

struct Place {
    let latitude: CLLocationDegrees
    let longitude: CLLocationDegrees
    let attributedName: String
    let id: String?

    init(
        latitude: CLLocationDegrees,
        longitude: CLLocationDegrees,
        attributedName: String,
        id: String? = nil
    ) {
        self.latitude = latitude
        self.longitude = longitude
        self.attributedName = attributedName
        self.id = id
    }
}

And use that type:

func getResponse(address: String, completion: @escaping (Place) -> Void) {    
}

Your code will be much easier to read and you have the default parameter value hidden inside Place initializer.

  •  Tags:  
  • Related