Why do enums have computed properties but not stored properties in Swift?

后端 未结 4 1797
轻奢々
轻奢々 2020-12-08 18:58

I am new to Swift and just came across this in the documentation:

Computed properties are provided by classes, structures, and enumerations. Stored

4条回答
  •  星月不相逢
    2020-12-08 19:47

    I use a small trick to store properties that are not accesible on initialization.

    First, I create a class Future which will store the stored property in the future:

    class Future {
      var value: T?
      init(value: T? = nil) {
          self.value = value
      }
    }
    

    Then I create my enum:

    enum Sample {
      case Test(future: Future)
    }
    

    Instantiate:

    let enumTest = Sample.Test(future: Future())
    

    Later in the code:

    switch enumTest {
      case let .Test(future):
      future.value = "Foo"
    }
    

    And later on, you can access the value:

    switch enumTest {
      case let .Test(future):
      // it will print Optional("Foo")
      print("\(future.value)")
    }
    

    This is not something you should abuse, but it can be helpful in some cases.

    Hope it helps.

提交回复
热议问题