h.and.h
h.and.h

Reputation: 776

Is there a way to constrain a generic to be one type or another in Swift?

Is there a way to add multiple, optional constraints to a generic? I'd like my generic to be either a string or a bool. Something like:

func myFunction<T>(_ dict: [String: T]) where T == String || T == Bool {
    // Do stuff with dict
}

Upvotes: 2

Views: 159

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236360

You can just create a protocol and make String and Bool conform to it:

protocol StringOrBool { }
extension Bool: StringOrBool {}
extension String: StringOrBool {}

func myFunction<T: StringOrBool>(_ dict: [String: T])  {
    print(dict)
}

myFunction(["a": true])
myFunction(["b": "test"])
myFunction(["b": 1]) // error: MyPlayground Xcode 11.playground:706:1: error: global function 'myFunction' requires that 'Int' conform to 'StringOrBool'

Upvotes: 4

rraphael
rraphael

Reputation: 11066

You can't event constrain a generic to one single type:

// error: Same-type requirement makes generic parameter 'T' non-generic
func myFunction<T>(_ dict: [String: T]) where T == String {

}

You probably want some overload of your function for your types:

func myFunction(_ dict: [String: String]) {
    print("String")
}

func myFunction(_ dict: [String: Bool]) {
    print("Bool")
}

let strings = ["a": "b"]
let bools = ["a": false]

myFunction(strings) // print String
myFunction(bools) // print Bool

Upvotes: 3

Related Questions