I've searched the Swift book, but can't find the Swift version of @synchronized. How do I do mutual exclusion in Swift?
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
I was looking for this myself and came to the conclusion there's no native construct inside of swift for this yet.
I did make up this small helper function based on some of the code I've seen from Matt Bridges and others.
Usage is pretty straight forward
There is one problem I've found with this. Passing in an array as the lock argument seems to cause a very obtuse compiler error at this point. Otherwise though it seems to work as desired.
Based on ɲeuroburɳ, test an sub-class case
Output:
Another method is to create a superclass and then inherit it. This way you can use GCD more directly
Using Bryan McLemore answer, I extended it to support objects that throw in a safe manor with the Swift 2.0 defer ability.
Analog of the
@synchronized
directive from Objective-C can have an arbitrary return type and nicerethrows
behaviour in Swift.The use of the
defer
statement lets directly return a value without introducing a temporary variable.In Swift 2 add the
@noescape
attribute to the closure to allow more optimisations:Based on the answers from GNewc [1] (where I like arbitrary return type) and Tod Cunningham [2] (where I like
defer
).I like and use many of the answers here, so I'd choose whichever works best for you. That said, the method I prefer when I need something like objective-c's
@synchronized
uses thedefer
statement introduced in swift 2.The nice thing about this method, is that your critical section can exit the containing block in any fashion desired (e.g.,
return
,break
,continue
,throw
), and "the statements within the defer statement are executed no matter how program control is transferred."1