Skip to content

Instantly share code, notes, and snippets.

@yuu
Last active November 13, 2019 02:34
Show Gist options
  • Save yuu/843d5438d5bdc166f55829ea3dd36b7b to your computer and use it in GitHub Desktop.
Save yuu/843d5438d5bdc166f55829ea3dd36b7b to your computer and use it in GitHub Desktop.
[swift] note

swift properties

https://docs.swift.org/swift-book/LanguageGuide/Properties.html

  • ストアドプロパティ
    • Lazy Stored Property
  • コンピューテッドプロパティ
var width = 0, height = 0, depth = 0
var volume: Double {
  return width * height * depth
}
  • インスタンスプロパティ
  • スタティックプロパティ
  • クラスプロパティ
  • Property Observers
class StepCounter {
  var totalStep: Int = 0 {
    willSet(newTotalSteps) {
      print("\(newTotalSteps)")
    }
    didSet {
      if totalSteps > oldValue {
        print("Added \(totalSteps - oldValue) steps")
      }
    }
  }
}
  • Property Wrapper
@propertyWrapper
struct TwelveOrLess {
    private var number = 0
    var wrappedValue: Int {
        get { return number }
        set { number = min(newValue, 12) }
    }
}
struct SmallRectangle {
    @TwelveOrLess var height: Int
    @TwelveOrLess var width: Int
}

var rectangle = SmallRectangle()
print(rectangle.height)
// Prints "0"

rectangle.height = 10
print(rectangle.height)
// Prints "10"

rectangle.height = 24
print(rectangle.height)
// Prints "12"

分類

  1. 再代入の可否による分類
  1. var
  2. let
  1. 値の保持有無による分類
  1. ストアドプロパティ
  • didSet {} or willSet {}
  1. コンピューテッドプロパティ
  • get {} or set {}
  1. 紐づく対象による分類
  1. インスタンスプロパティ
  2. スタティックプロパティ
  3. クラスプロパティ
  • class keyword
  • need computed property syntax
  • available override that class property
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment