作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下 Playground :
// : Playground - noun: a place where people can play
import Foundation
// Define a protocol
protocol MyProtocol
{
func getMeAString() -> String!
}
// Create a class that conforms to the protocol
class ClassThatConformsToProtocol: MyProtocol
{
func getMeAString() -> String! {
return "hey!"
}
}
// Define a function that takes a generic, but ensure the generic conforms to the protocol
func logTheThing<T: MyProtocol>(theThing: T!)
{
theThing.getMeAString()
}
// Let's create an instance
let instanceOfClassThatConforms = ClassThatConformsToProtocol()
// We're now going to see if we can pass the object to our generic method
logTheThing(instanceOfClassThatConforms)
// It works!
// Let's create another method, but this one only knows the protocol its parameter conforms to, the in implementing class
func takeInAnObjectThatWeOnlyKnowItsProtocol(object:MyProtocol)
{
logTheThing(object) // error: cannot convert value of type 'MyProtocol' to expected argument type '_!'
}
如前所述,我收到一条错误消息:
error: cannot convert value of type 'MyProtocol' to expected argument type '_!'
为什么我不能将这个一致的对象传递给泛型方法?
如果编译器知道一个对象符合协议(protocol),为什么我不能将它传递给泛型方法?
最佳答案
协议(protocol)不符合自身。你必须使这个通用:
func takeInAnObjectThatWeOnlyKnowItsProtocol<T: MyProtocol>(object: T)
{
logTheThing(object)
}
下一个问题:为什么协议(protocol)不符合自身?因为它没有。最终它可能会,但今天不会。
就是说,鉴于此特定代码,根本没有理由使其通用。只需传递协议(protocol),它就会完全按照您的意愿行事:
func logTheThing(theThing: MyProtocol) {
theThing.getMeAString()
}
func takeInAnObjectThatWeOnlyKnowItsProtocol(object: MyProtocol) {
logTheThing(object)
}
传递 object: MyProtocol
表示“任何符合 MyProtocol
的类型”并且在两个地方都匹配。路过<T: MyProtocol>(object: T)
表示“符合 MyProtocol
的特定具体类型”和“符合 MyProtocol
的任何类型”不是“特定具体类型”,因此失败(今天;再一次,他们可能有一天会解决这个问题).
(不相关的注释:在 Swift 中返回 String!
从来没有充分的理由。只需返回 String。如果您不使用 T!
并且只是在您的日志记录调用中使用 T
。除非您桥接到 ObjC,否则几乎没有理由传递或返回 !
类型。它们只在纯 Swift 中对属性有意义。)
关于Swift:将一致的对象实例传递给泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287083/
我是一名优秀的程序员,十分优秀!