生成相同类型类的SequenceTypes数组的类型是什么

时间:2015-08-18 23:12:52

标签: swift generics

我有一堆非常不同的类,除了它们都能够返回MyProtocol类型的对象。

所以对于每个班级我都有

namespace AccessorizeForLess.ViewModels
{
    public class PayWithCCViewModel
    {
        .... // other proeprties

        [Required(ErrorMessage="Card type is required")]
        public string CardType { get; set; }

        public Enums.Enums.CreditCardtTypes Cardtypes { get; set; }
    }
}

我想将这些类的集合传递给可以执行

的函数
extension MyClass : SequenceType {
    func generate() -> GeneratorOf<MyProtocol> {
        var index = -1;
        return GeneratorOf< MyProtocol > {
            index += 1
            return index < self.values.count
                ? self.values[index]
                : nil
        }
    }
}

func printAll (containers : ????) { for container : containers { for myProtocolValue : container { print (myProtocolValue.myProtocolFunc()) } } } 有哪些类型?

1 个答案:

答案 0 :(得分:1)

最好的解决方案是制定新协议。所有类都符合它,并且没有自己的要求才能使用异构数组:

protocol MyProtocolContainer {
    func generate() -> GeneratorOf<MyProtocol>
}

// the implementation of the generate function stays the same but you conform to MyProtocolContainer

extension MyClass : SequenceType, MyProtocolContainer { ... }

// the printAll function has the following implementation
func printAll (containers : [MyProtocolContainer]) {
    for container in containers {
        // you have to call generate manually since MyProtocolContainer is no SequenceType
        // in order to be used in a heterogenous collection
        for myProtocolValue in container.generate() { 
            print (myProtocolValue.myProtocolFunc())
        }
    }
}

旁注:

在Swift中没有for ... : ...循环,:应该是in

为了简化生成函数的实现,我建议使用Generator本身的Array

class MyClass: MyProtocolReturnable, SequenceType {
    func generate() -> GeneratorOf<MyProtocol> {
        return GeneratorOf(self.values.map{ $0 as MyProtocol }.generate())
        // if the array is of type [MyProtocol] you can also use
        return GeneratorOf(self.values.generate())
    }
}