Mick
Mick

Reputation: 8922

Different return types from protocol method

I would like to have a protocol that defines some methods and properties. However, property types and method return types may vary between the different classes that conform to said protocol. For example: A.getContent() may return a value of type String, but B.getContent() may return a value of type Int. In my example below, I used the type Any. Is this possible in Swift or is this a totally wrong approach? Maybe with generics?

protocol Content {
    func getContent() -> any
}

class A: Content {
    func getContent() -> String {
        return "Im a String"
    }
}

class B: Content {
    func getContent() -> Int {
        return 1234
    }
}

Upvotes: 3

Views: 1744

Answers (2)

ViTUu
ViTUu

Reputation: 1204

I think you are looking about Generics in Protocol. You can associate a type dynamically with associatedtype, for example

protocol Content{
    associatedtype T
    func getContent()-> T
}

class A: Content {
    func getContent() -> String {
       return "Hello World"
    }
}

class B: Content {
    func getContent() -> Int {
        return 42
    }
}

A().getContent() //"Hello World"
B().getContent() //42

If you look at this example when you put the Type after the function in the class sun of Content, the protocol Content will be this one type

Update

I am putting another example using "swiftly" syntax instead of traditional getContent.

protocol Content{
    associatedtype T
    var content:T { get }
}

class A: Content {
    var content:String{
        return "Hello World"
    }
}

class B: Content {
    var content:Int{
        return 42
    }
}

A().content //"Hello World"
B().content //42

Upvotes: 9

Aaron
Aaron

Reputation: 6714

You can use generics and meta-types:

protocol Content {
    func getContent<T>(ofType: T.Type) -> T?
}

class A: Content {
    func getContent<T>(ofType: T.Type) -> T? {
        return "Im a String" as? T ?? nil
    }
}

class B: Content {
    func getContent<T>(ofType: T.Type) -> T? {
        return 1234 as? T ?? nil
    }
}

let aClass = A()
let aValue = aClass.getContent(ofType: String.self) // "Im a String"

let bClass = B()
let bValue = bClass.getContent(ofType: Int.self)    // 1234

Upvotes: 1

Related Questions