gpt4 book ai didi

Swift:将一致的对象实例传递给泛型方法

转载 作者:行者123 更新时间:2023-11-28 12:48:32 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com