协议方法的不同返回类型

Mic*_*ick 3 swift

我想有一个定义一些方法和属性的协议.但是,属性类型和方法返回类型可能在符合所述协议的不同类之间有所不同.例如:A.getContent()可能返回type的值String,但B.getContent()可能返回type的值Int.在下面的示例中,我使用了该类型Any.这在Swift中是可能的还是这是一种完全错误的方法?也许用泛型?

protocol Content {
    func getContent() -> any
}

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

class B: Content {
    func getContent() -> Int {
        return 1234
    }
}
Run Code Online (Sandbox Code Playgroud)

ViT*_*TUu 8

我想你正在寻找协议中的泛型.您可以将动态类型与之关联associatedtype,例如

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
Run Code Online (Sandbox Code Playgroud)

如果你看一下这个例子,当你在内容的类sun中放入Ty​​pe after函数时,协议Content将是这一种类型