Created
February 9, 2022 08:20
-
-
Save taji-taji/2d09529dc2bf1ed169367367591d1ecb to your computer and use it in GitHub Desktop.
1回だけ更新可能、1回だけ実行可能
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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