相关疑难解决方法(0)

Swift协议继承和通用函数

考虑以下游乐场:

import Foundation

protocol StringInitable {
    init( string:String )
}

class A : StringInitable {
    var stored:String

    required init ( string:String ) {
        stored = string
    }
}

class B : A /*, StringInitable */ {
    var another_stored:String

    required init ( string:String ) {
        another_stored = "B-store"

        super.init(string: string)
    }
}

func maker<T:StringInitable>(string:String) -> T {
    return T(string: string)
}

let instanceA = A(string: "test-maker-A")
let instanceB = B(string: "test-maker-B")

let makerA:A = maker("test-maker-A")
let makerB:B = maker("test-maker-B")

let typeInstanceA …
Run Code Online (Sandbox Code Playgroud)

inheritance protocols swift swift-playground

8
推荐指数
1
解决办法
550
查看次数

标签 统计

inheritance ×1

protocols ×1

swift ×1

swift-playground ×1