Reputation: 302
How can I make method in which a user can pass only specific values for example
button.setTitle("SKIP", for: .normal)
setTitle method takes specific parameters after "for", we just press . (dot) and it show suggestions for values to pass.
I want to do same thing, for example I want to make a method for calculate distance between 2 points,
func distanceBetween(loc1: CLLocation, and loc2: CLLocation, unit: String) -> CLLocationDistance {}
here user will pass location1 and location2 as arguments and I want to restrict user when he pass unit, he should have only 3 options, km, miles and meters.
Upvotes: 1
Views: 81
Reputation: 11242
Create a enum
with the values you need and use that enum as argument.
enum Unit {
case km
case miles
case meters
}
Now your function would change to:
func distanceBetween(loc1: CLLocation, and loc2: CLLocation, unit: Unit) -> CLLocationDistance {
switch unit {
case .km:
// Do something for kilometers
case .miles:
// Do something for miles
case .meter:
// Do something for meters
}
If in case you add a another unit, your compiler will throw an error saying that you haven't specified a default
case and you would immediately be made to handle it.
And your fuction call would take any one of the Unit
as argument. Example:
distanceBetween(loc1: location1, and loc2: location2, unit: .km)
Upvotes: 1