5

我正在尝试在 Swift 中实现 Kotlin 密封类的效果,以便我可以实现基于类的替代方法来替代具有关联类型的枚举。

以下导致编译器错误:

final class Foo {
    class Bar: Foo {}  // Error: inheritance from a final class "Foo"
}

有没有办法有效地将 Swift 类从进一步的子类化中“密封”,但仍然首先允许子类化?

4

2 回答 2

11

我会看看这个 使用 Kotlin 的密封类来近似 Swift 的枚举与相关数据和(主要)这个 Swift Enumerations Docs

科特林

sealed class Barcode {
   class upc(val numberSystem: Int, val manufacturer: Int, val product: Int, val check: Int) : Barcode()
   class qrCode(val productCode: String) : Barcode()
}

接着:

fun barcodeAsString(barcode: Barcode): String =
   when (barcode) {
      is Barcode.upc -> “${barcode.numberSystem} ${barcode.manufacturer} 
   ${barcode.product} ${barcode.check}”
      is Barcode.qrCode -> “${barcode.productCode}”
}

Swift中:

enum Barcode {
   case upc(Int, Int, Int, Int)
   case qrCode(String)
}

然后执行以下操作:

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("SDFGHJKLYFF")

或者:

switch productBarcode {
case .upcA(let a, let b, let c, let d):
    print("UPC: \(a),\(b),\(c),\(d)")
case .qrCode(let code):
    print("QR Code: \(code)")
}
于 2018-04-09T15:04:26.960 回答
4

你可以把它和它的子类放在一个框架中并标记它public。一个public类不能被其导入器子类化(与可以的open类相反)。

于 2017-01-02T16:10:59.003 回答