Search code examples
swiftdefinition

Could Swift create "OR" type for parameters?


It's easy to create "AND" type for parameter:

func test(item:(CVarArg&AnyObject))->String?{
    return nil
}

as you know,item type is CVarArg And AnyObject.

but how to create "OR" type to indicate item is CVarArg Or AnyObject???

thanks :)

PS: I tried item:(item:(CVarArg|AnyObject))

but it's not working!

Updating 1:

I only want limit item's type between CVarArg and AnyObject,then coding by myself:

func test(item:(CVarArg|AnyObject))->String?{
    if item is CVarArg {
        // Do something for CVarArg
    }else{
        // Must be AnyObject,Do something ...
    }
}

Solution

  • You can't do that. Swift is a statically typed language and at compile time compiler have to what your type is. If your type can be one thing OR the other, compiler doesn't know how to resolve that.

    Imagine, for instance you have type A with method foo() and type B with method bar(). If your item is A or B, how would the compiler resolve a call to foo() or bar() at compile time? It just can't, since there's no guarantees your type would implement any of those. I would suggest you to create your function with two separate optional parameters. Something like:

    func test(item: CVarArg?, other: AnyObject?)->String? {
        return nil
    }
    

    Then, check which of the parameters is passed. Hope that helps!

    EDIT

    Another option you also have is to wrap your types into enum cases. Something like:

    enum Item {
      case foo(CVarArg)
      case bar(AnyObject)
    }
    
    func test(item: Item) {
      switch item {
      case .foo(let arg):
        // arg is CVarArg
        print(arg)
      case .bar(let obj):
        // obj is AnyObject
        print(obj)
      }
    }
    
    var arg: CVarArg!
    test(item: .foo(arg))