简体   繁体   English

如何要求泛型类型使用协议中的特定类型实现通用协议

[英]How to require a generic type implement a generic protocol using a specific type in the protocol

Hi I'm using generics a lot in my current project. 嗨,我在当前的项目中使用泛型。 However, I've come across a problem: 但是,我遇到了一个问题:

I need a generic function foo<T> to be able to take a parameter that conforms to a generic protocol using a specific type. 我需要一个通用函数foo<T>才能使用特定类型获取符合通用协议的参数。

For example in Java I can do: 例如在Java中,我可以这样做:

public interface Proto<B> {
    public void SomeFunction()
}
public class SampleClass {
}
public class Conforms extends Proto<SampleClass> {
    @Override
    public void SomeFunction () {}
}
public class TestingClass {
    public void Requires (Proto<SampleClass> param) {
        // I can use param
    }
}

How would I do the same Requires() function in Swift? 我如何在Swift中执行相同的Requires()函数? I know in Swift you use typealias in the protocol for generics. 我知道在Swift中你在泛型协议中使用了typealias How do I constrain a parameter based on the typealias ? 如何约束基础上的一个参数typealias

Prototypes don't seem to have generics the way classes and structs do in Swift, but you can have associated types with typealias , which are close. 原型似乎不具备仿制药的方式类和结构在斯威夫特做,但你可以有关联与类型typealias ,这是接近。

You can use type constraints to make sure that the object you pass in adopts the Proto with type constraints. 您可以使用类型约束来确保传入的对象采用带有类型约束的Proto To make the Proto you pass into require has the right B , you use where . 为了使Proto传递到require有正确的B ,你用where

Apples documentation on generics has a lot of info. 关于泛型的苹果文档有很多信息。

This blog post is also a good source of info on doing more complicated things with generics. 这篇博文也是关于使用泛型做更复杂的事情的一个很好的信息来源。

protocol Proto {
    typealias B
    func someFunction()
}

class SampleClass {}

class Conforms : Proto {
    typealias B = SampleClass
    func someFunction() { }
}

class TestingClass {
    func requires<T: Proto where T.B == SampleClass>(param: T) {
        param.someFunction()
    }
}

You can use a where clause to specify multiple requirements for a generic. 您可以使用where子句指定泛型的多个要求。 I think your example translates to this, but it crashes Xcode. 认为你的例子转化为这个,但它崩溃了Xcode。 Beta! 公测!

protocol Proto {
    func someFunction()
}
class SampleClass {
}
class Conforms: SampleClass, Proto {
    func someFunction() {
    }
}
class TestingClass {
    func requires<T: SampleClass >(param: T) where T: Proto {
        param.someFunction()    // it's this line that kills Xcode
    }
}

let testingClass = TestingClass()
let conforms = Conforms()
testingClass.requires(conforms)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM