Swift中多协议中的相同类型约束

时间:2016-09-05 10:44:37

标签: swift protocols

我必须为一种类型设置一个约束到多个协议:

public protocol Test: Hashable { }

public protocol Foo {
    func function() -> Test
}

public protocol Bar {
    func function(argument: Test) -> Test
}

我想在一个类中使用这些协议:

public class Baz<T: Test> {
    var FooImpl: Foo
    var BarImpl: Bar
}

在我能做到之后:

class TestImpl : Test { }

let baz = Baz()
baz.BarImpl.function(TestImpl())

你有什么想法吗?

编辑:具体地说,我尝试将Generator,Merger,Mutator和FitnessEvaluator分开的遗传算法实现,所以我有:

public protocol Genotype : Hashable {
}

public protocol CandidateGenerator{
    func generateRandomly<T: Genotype>() -> T
}

public protocol CandidateMerger {
    func merge<T: Genotype>(first: T, second: T) -> T
}

public protocol CandidateMutator {
    func mutate<T: Genotype>(candidate: T) -> T
}

public protocol FitnessEvaluator {
    func evaluate<T: Genotype>(genotype: T) -> Double
}

public class GeneticAlgorithm<T: Genotype> {
    private let generator: CandidateGenerator
    private let merger: CandidateMerger
    private let mutator: CandidateMutator
    private let evaluator: FitnessEvaluator
// ...
}

// at use 
class Test : Genotype { ... }

class Generator : CandidateGenerator {
    func generateRandomly<T: Genotype>() -> T {
        let a = Test()
        return a // <- Error here : cannot convert return expression of type 'Test' to return type 'T'
    }
}

编辑:

我尝试使用associedtype但是我不能将它约束到Genotype,所以我的协议可以接受不实现我的协议的各种类型:

protocol CandidateGenerator {
    associatedtype Genottype

    func generateRandomly() -> Genottype
}

class CandidateGenImpl : CandidateGenerator {
    typealias Genottype = Test

    func generateRandomly() -> Test {
        return /* random */ Test()
    }
}

class Other { } // not implement Genotype

class CandidateGenImpl2 : CandidateGenerator {
    typealias Genottype = Other

    func generateRandomly() -> Other {
        return /* random */ Other()
    }
}

我试着这样做:

associatedType Genottype = Genotype

但它不起作用......

希望这有助于理解

0 个答案:

没有答案