Achieving the effect of a sealed class in Swift
Asked Answered
A

2

6

I'm trying to achieve the effect of Kotlin sealed class in Swift, so that I can implement a class-based alternative to enums with associated types.

The following results in a compiler error:

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

Is there a way to effectively "seal" a Swift class from further subclassing but still allow subclassing in the first place?

Achernar answered 2/1, 2017 at 16:7 Comment(0)
F
14

I would give a look at this Using Kotlin’s sealed class to approximate Swift’s enum with associated data and (mostly) this Swift Enumerations Docs

Kotlin:

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

and then:

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

While in Swift:

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

And then do things like:

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

or:

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)")
}
Fransen answered 9/4, 2018 at 15:4 Comment(1)
This is so elegant! clean! yes! Well after 9 years of android development and 3 with Kotlin, I really loved the way Kotlin treats its users with clean and tidy code, so this approach makes swift code even cleaner! love it!Prato
T
4

You could put it and its subclass in a framework and mark it public. A public class cannot be subclassed by its importer (as opposed to an open class which can).

Tola answered 2/1, 2017 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.