Skip to content

Instantly share code, notes, and snippets.

@taji-taji
Created February 9, 2022 08:20
Show Gist options
  • Save taji-taji/2d09529dc2bf1ed169367367591d1ecb to your computer and use it in GitHub Desktop.
Save taji-taji/2d09529dc2bf1ed169367367591d1ecb to your computer and use it in GitHub Desktop.
1回だけ更新可能、1回だけ実行可能
import Foundation
@propertyWrapper
class OnceExecutable {
@OnceUpdatable
private var execute: () -> Void
private var isExecuted = false
var wrappedValue: () -> Void {
get { execute }
set {
execute = {
guard !self.isExecuted else {
assertionFailure("can't execute twice!")
return
}
self.isExecuted = true
newValue()
}
}
}
init(wrappedValue: @escaping () -> Void = {}) {
execute = wrappedValue
}
}
import Foundation
@propertyWrapper
struct OnceUpdatable<Value> {
private var value: Value
private var maxUpdatableCount = 1
private var updatedCount = 0
var wrappedValue: Value {
get { value }
set {
guard updatedCount < maxUpdatableCount else {
assertionFailure("can't update any more!")
return
}
updatedCount += 1
value = newValue
}
}
init(wrappedValue: Value, maxUpdatableCount: Int = 1) {
value = wrappedValue
self.maxUpdatableCount = maxUpdatableCount
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment