towry
6/21/2017 - 3:33 AM

demonstration of using trait and protocol in swift.

demonstration of using trait and protocol in swift.

//: Playground - noun: a place where people can play

import Foundation

protocol PrimitiveSequenceType {
    associatedtype Element
    associatedtype TraitType
    
    func append(item: Element)
}

struct PrimitiveSequence<Trait, E> {}

enum SingleTrait {}
enum MaybeTrait {}

extension PrimitiveSequence: PrimitiveSequenceType {
    typealias Element = E
    typealias TraitType = Trait
    
    func append(item: E) {
        print("append in E")
    }
}

extension PrimitiveSequenceType where TraitType == SingleTrait {
    func create() {
        print("create:SingleTrait called");
    }
}

extension PrimitiveSequenceType where TraitType == MaybeTrait {
    func create() {
        print("create:MaybeTrait called");
    }
}

let single = PrimitiveSequence<SingleTrait, Int>()
let maybe = PrimitiveSequence<MaybeTrait, String>()

single.create()
maybe.create()