协议上的关联类型和泛型

Associated types and generics on protocols

我正在尝试在协议中声明一个函数,该函数强制符合它的类型 return 相同协议但具有特定关联类型的值:

protocol Protocol {
    typealias ValueType

    var value : ValueType? {get}

    func getProtocolString<A where A : Protocol, A.ValueType == String>() -> A
}

编译通过。当我尝试创建一个符合它的 class 时,我得到了错误:

class AClass<T> : Protocol {
    var value : T?       

    func getProtocolString<A where A : Protocol, A.ValueType == String>() -> A {
        return AClass<String>()
    }
}

错误是 'AClass' 无法转换为 'A'

我错过了什么吗?这甚至可能吗?

谢谢

看来你对泛型有点误解。通用函数在这些函数的调用点实例化,而不是在每个函数本身的主体处实例化。所以,你写的类型约束是说这个函数 returns 一个值,它的类型可以是 Protocol 的所有子类型中的任何一个。因此,对于 Protocol 的所有子类型,函数定义对于 A 必须是静态正确的,而不仅仅是 AClass<String>,它只是 Protocol 的一种类型。

无论如何,我认为没有直接的方法可以实现你想要的,至少在当前Swift。

这似乎在操场上有效...它对您尝试做的事情有效吗?

protocol StringProtocol
{
    typealias ValueType

    var value : ValueType? { get }

    func getProtocolString<A where A: StringProtocol, A.ValueType == String>() -> A
}

class StringClass : StringProtocol
{
    typealias ValueType = String

    var value : ValueType?

    init() { }

    func getProtocolString<A where A: StringProtocol, A.ValueType == String>() -> A
    {
        return StringClass() as A
    }
}

我仍然没有完全遵循您尝试通过此实现满足的要求。

问题在于将受协议约束的通用占位符与协议本身混淆了。这里有一个更简单的例子,类似于你的代码,试着把它说清楚:

// first, define a protocol and two structs that conform to it
protocol P { }
struct S1: P { }
struct S2: P { }

// now, a function that returns an object in the form
// of a reference to protocol P
func f() -> P {
    // S1 conforms to P so that’s fine 
    return S1()
}
// ok all well and good, this works fine:
let obj = f()

// now, to do something similar to your example code,
// declare a generic function that returns a generic
// placeholder that is _constrained_ by P
// This will NOT compile:
func g<T: P>() -> T { return S1() }

为什么不能编译?

泛型函数的工作方式是在编译时,当你调用函数时,编译器决定占位符T需要的类型,然后为您编写一个函数,其中所有出现的 T 都替换为该类型。

因此在下面的示例中,T 应替换为 S1:

let obj1: S1 = g()
// because T needs to be S1, the generic function g above is 
// rewritten by the compiler like this:
func g() -> S1 { return S1() }

这看起来不错。除了,如果我们想让 T 变成 S2 怎么办? S2 符合 P,因此 T 是一个完全合法的值。但这怎么行得通:

// require our result to be of type S2
let obj2: S2 = g()
// so T gets replaced with S2… but now we see the problem.
// you can’t return S1 from a function that has a return type of S2.
// this would result in a compilation error that S2 is not
// convertible to S1
func g() -> S2 { return S1() }

这是您收到的错误消息的来源。您的占位符 A 可以代表任何符合 Protocol 的类型,但您正在尝试 return 一个 特定的 类型(AClass) 符合该协议。所以它不会让你做。