Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i have 2 types on parameter in swift?

so i've created function and it does something, but i want it to do something else if the parameter type is different, for example:

func (parameter: unknownType){
    if(typeof parameter == Int){
        //do this
    }else if(typeof parameter == String){
        //do that
    }
}

i've done this in javascript or other programming languages, but i don't know how to do this in swift

i've created function which takes 1 argument UITextField and centers it using constraints

now i want to center my button, but since button is not UITextField type it does not work, so is there a way i can tell function to do the same on UIButton??

like image 635
nikagar4 Avatar asked Sep 06 '25 03:09

nikagar4


2 Answers

Use Overload:

class Example
{
    func method(a : String) -> NSString {
    return a;
    }
    func method(a : UInt) -> NSString {
    return "{\(a)}"
    }
}

Example().method("Foo") // "Foo"
Example().method(123) // "{123}"
like image 115
Victor Viola Avatar answered Sep 08 '25 23:09

Victor Viola


The equivalent of the Javascript code would be:

func doSomething(parameter: Any?) {
    if let intValue = parameter as? Int {
       // do something with the int
    } else if let stringValue = parameter as? String {
      // do something with the string
    }
}

But be warned, this approach makes you loose the type safety which is one of most useful feature of Swift.

A better approach would be to declare a protocol that is implemented by all types that you want to allow to be passed to doSomething:

protocol MyProtocol {
    func doSomething()
}

extension Int: MyProtocol {
    func doSomething() {
        print("I am an int")
    }
}

extension String: MyProtocol {
    func doSomething() {
        print("I am a string")
    }
}

func doSomething(parameter: MyProtocol) {
    parameter.doSomething()
}


doSomething(1) // will print "I am an int"
doSomething("a") // will print "I am a string"
doSomething(14.0) // compiler error as Double does not conform to MyProtocol
like image 26
Cristik Avatar answered Sep 08 '25 21:09

Cristik