Simultaneous accesses when using PropertyWrapper - ios

I want to create a property wrapper, that would store a callback block, and execute it every time, when it's value changes. Something like simple KVO. It works fine, but there is one problem with it. If I use the property itself in this callback block, then I get an error:
Simultaneous accesses to 0x6000007fc3d0, but modification requires exclusive access
From what I understand this is because the property itself is still being written to, while this block is executing, and this is why it can't be read.
Lets add some code, to show what I mean:
#propertyWrapper
struct ReactingProperty<T> {
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
public var wrappedValue: T {
didSet {
reaction?(wrappedValue)
}
}
public var projectedValue: Self {
get { self }
set { self = newValue }
}
private var reaction: ((_ value: T) -> Void)?
public mutating func setupReaction(_ reaction: #escaping (_ value: T) -> Void) {
self.reaction = reaction
}
}
And AppDelegate:
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
#ReactingProperty
var testInt = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// 1. This will pass correctly.
$testInt.setupReaction { (value) in
print(value)
}
testInt = 1
// 2. This will cause crash, because I access testInt in this block, that is executed when value changes.
$testInt.setupReaction { [unowned self] (value) in
print(self.testInt)
}
testInt = 2
return true
}
}
I have a few workarounds for this, but none of theme is really what I need for various reasons.
If I access the value in the block from this block argument instead, and pass this argument in value didSet, then it works fine. But this forces me to always use it this way, and I would like to use this with the code, that contains various other callbacks, and sometimes it would be more convenient for me to be able to access this value directly as well.
I can execute the callback block asynchronously (DispachQueue.main.async { self.block?(value) }). But this also is not the best for my case.
Use combine instead. I will probably, but I would also like to remain this functionality for now. Also Im just curious on this issue.
Can this somehow be overcome? What variable is actually causing this read-write access error? Is this the value inside propertyWrapper or struct with propertyWrapper itself?
I think it's propertyWrapper struct accessing that causes this, and not its internal value, but Im not sure.

I think I have found the right solution. Just change from struct to class. Then read/write access is no issue.
#propertyWrapper
class ReactingProperty<T> {
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
public var wrappedValue: T {
didSet {
reaction?(wrappedValue)
}
}
public lazy var projectedValue = self
private var reaction: ((_ value: T) -> Void)?
public mutating func setupReaction(_ reaction: #escaping (_ value: T) -> Void) {
self.reaction = reaction
}
}

Related

How do you write a Swift completion block that can only be called once?

Let's say I have a Swift class that stores a completion block, and does a few asynchronous tasks.
I want that block to be called by whichever of the tasks finishes first, but only that one - I don't want it to be called again when the second task finishes.
How can I implement this in a clean way?
As long as you don't need this to be thread safe, you can solve this problem with a fairly straightforward #propertyWrapper.
#propertyWrapper
struct ReadableOnce<T> {
var wrappedValue: T? {
mutating get {
defer { self._value = nil }
return self._value
}
set {
self._value = newValue
}
}
private var _value: T? = nil
}
Mark the completion block var with #ReadableOnce, and it will be destroyed after the first time it's value is read.
Something like this:
class MyClass {
#ReadableOnce private var completion: ((Error?) -> Void)?
init(completion: #escaping ((Error?) -> Void)) {
self.completion = completion
}
public func doSomething() {
// These could all be invoked from different places, like your separate tasks' asynchronous callbacks
self.completion?(error) // This triggers the callback, then the property wrapper sets it to nil.
self.completion?(error) // This does nothing
self.completion?(error) // This does nothing
}
}
I wrote up more of a detailed discussion of this here but the key thing to be aware of is that reading the value sets it to nil, even if you don't invoke the closure! This might be surprising to someone who isn't familiar with the clever property wrapper you've written.
There is already a standard expression of onceness. Unfortunately the standard Objective-C is unavailable in Swift (GCD dispatch_once), but the standard Swift technique works fine, namely a property with a lazy define-and-call initializer.
Exactly how you do this depends on the level at which you want onceness to be enforced. In this example it's at the level of the class instance:
class MyClass {
// private part
private let completion : (() -> ())
private lazy var once : Void = {
self.completion()
}()
private func doCompletionOnce() {
_ = self.once
}
// public-facing part
init(completion:#escaping () -> ()) {
self.completion = completion
}
func doCompletion() {
self.doCompletionOnce()
}
}
And here we'll test it:
let c = MyClass() {
print("howdy")
}
c.doCompletion() // howdy
c.doCompletion()
let cc = MyClass() {
print("howdy2")
}
cc.doCompletion() // howdy2
cc.doCompletion()
If you promote the private stuff to the level of the class (using a static once property), the completion can be performed only once in the lifetime of the entire program.

Swift Generics where T is undeclared

I have two questions involving Generics
a) I want to do an extension function where my Result class in the case of Success accepts a Generic of type T, however, I get the following error: Use of undeclared type 'T'
Here's my code:
extension Result<T> where Success == [T] {
/// Function extension for the .success case on a Result object. The result of the Result object are
/// multiple object, in case a list or an iterable in being wrapped.
/// - Parameter callback: Function that the will be executed when the .success case is triggered
func onSuccess(callback: ([T]) -> Void) {
switch self {
case .success(let results):
callback(results)
default:
return
}
}
}
also regarding the same problem, I want a UIViewController to accept an array of a Generic type:
:
class UIObservableTableViewController: UITableViewController, LifecycleOwner {
func addLiveData<T>(_ liveData: LiveData<T>) {
liveDataObservers.append(liveData)
}
private lazy var liveDataObservers = [LiveData<T>]()
However, I get the same error as the previous one, how can I implement T instead of Any, or could I cast T to Any or the other way around?
I have also tried the following code:
extension Result where Success == Collection {
/// Function extension for the .success case on a Result object. The result of the Result object are
/// multiple object, in case a list or an iterable in being wrapped.
/// - Parameter callback: Function that the will be executed when the .success case is triggered
func onSuccess(callback: (Success) -> Void) {
switch self {
case .success(let results):
callback(results)
default:
return
}
}
}
However, I get the following compilation error: Protocol 'Collection' can only be used as a generic constraint because it has Self or associated type requirements
LiveData is the following class:
/// Class for implementing the Observable Pattern. This is a Mutable Observable (it can change its value)
class LiveData<T> {
private (set) var value: T
private var valueChanged: ((T) -> Void)?
init(value: T) {
self.value = value
}
/// Function that sets a value on a main thread. This could throw an error is the setValue is not called inside the Main Thread
/// - Parameter value: T object
fileprivate func setValue(value: T) {
print("The value is of type: \(value)")
try! assertMainThread(methodName: "setValue")
self.value = value
valueChanged?(self.value)
}
/// Function that sets a value on a background thread. This could throw an error is the setValue is not called inside the Main Thread
/// - Parameter value: T object
fileprivate func postValue(value: T) {
DispatchQueue.main.async {
self.value = value
self.valueChanged?(self.value)
}
}
/// Function that checks if the current thread is the MainThread
private func assertMainThread(methodName: String) throws {
if !Thread.isMainThread {
throw CustomError("\(methodName) is not in the main thread")
}
}
/// Add closure as an observer and trigger the closure imeediately if fireNow = true
func observe(owner: LifecycleOwner, _ onChange: ((T) -> Void)?) {
valueChanged = onChange
onChange?(value)
// Add the live data into its LifecycleOwner
owner.addLiveData(self)
}
func removeObserver() {
valueChanged = nil
}
}
/// Class for implementing the Observable Pattern. This is a Mutable Observable (it can change its value)
class MutableLiveData<T>: LiveData<T> {
override func setValue(value: T) {
super.setValue(value: value)
}
override init(value: T) {
super.init(value: value)
}
override func postValue(value: T) {
super.postValue(value: value)
}
}

query regarding mocking singleton in swift ,ios using xctest?

this is not a question regarding that should we use singleton or not. but rather mocking singleton related.
this is just a sample example, as i was reading about mocking singleton is tough. so i thought let me give a try.
i am able to mock it but not sure is this a correct approach ?
protocol APIManagerProtocol {
static var sharedManager: APIManagerProtocol {get set}
func doThis()
}
class APIManager: APIManagerProtocol {
static var sharedManager: APIManagerProtocol = APIManager()
private init() {
}
func doThis() {
}
}
class ViewController: UIViewController {
private var apiManager: APIManagerProtocol?
override func viewDidLoad() {
}
convenience init(_ apimanager: APIManagerProtocol){
self.init()
apiManager = apimanager
}
func DoSomeRandomStuff(){
apiManager?.doThis()
}
}
import Foundation
#testable import SingleTonUnitTesting
class MockAPIManager: APIManagerProtocol {
static var sharedManager: APIManagerProtocol = MockAPIManager()
var isdoThisCalled = false
func doThis(){
isdoThisCalled = true
}
private init(){
}
}
class ViewControllerTests: XCTestCase {
var sut: ViewController?
var mockAPIManager: MockAPIManager?
override func setUp() {
mockAPIManager = MockAPIManager.sharedManager as? MockAPIManager
sut = ViewController(mockAPIManager!)
}
func test_viewController_doSomeRandomStuffs(){
sut?.DoSomeRandomStuff()
XCTAssertTrue(mockAPIManager!.isdoThisCalled)
}
override func tearDown() {
sut = nil
mockAPIManager = nil
}
}
The basic idea is right: Avoid repeated references to the singleton directly throughout the code, but rather inject object that conforms to the protocol.
What’s not quite right is that you are testing something internal to the MockAPIManager class. The mock is only there to serve a broader goal, namely to test your business logic (without external dependencies). So, ideally, you should be testing something that is exposed by APIManagerProtocol (or some logical result of that).
So, let’s make this concrete: For example, let’s assume your API had some method to retrieve the age of a user from a web service:
public protocol APIManagerProtocol {
func fetchAge(for userid: String, completion: #escaping (Result<Int, Error>) -> Void)
}
(Note, by the way, that the static singleton method doesn’t belong in the protocol. It’s an implementation detail of the API manager, not part of the protocol. No controllers that get a manager injected will ever need to call shared/sharedManager themselves.)
And lets assume that your view controller (or perhaps better, its view model/presenter) had a method to retrieve the age and create an appropriate message to be shown in the UI:
func buildAgeMessage(for userid: String, completion: #escaping (String) -> Void) {
apiManager?.fetchAge(for: userid) { result in
switch result {
case .failure:
completion("Error retrieving age.")
case .success(let age):
completion("The user is \(age) years old.")
}
}
}
The API manager mock would then implement the method:
class MockAPIManager: APIManagerProtocol {
func fetchAge(for userid: String, completion: #escaping (Result<Int, Error>) -> Void) {
switch userid {
case "123":
completion(.success(42))
default:
completion(.failure(APIManagerError.notFound))
}
}
}
Then you could test the logic of building this string to be shown in your UI, using the mocked API rather than the actual network service:
class ViewControllerTests: XCTestCase {
var viewController: ViewController?
override func setUp() {
viewController = ViewController(MockAPIManager())
}
func testSuccessfulAgeMessage() {
let e = expectation(description: "testSuccessfulAgeMessage")
viewController?.buildAgeMessage(for: "123") { string in
XCTAssertEqual(string, "The user is 42 years old.")
e.fulfill()
}
waitForExpectations(timeout: 1)
}
func testFailureAgeMessage() {
let e = expectation(description: "testFailureAgeMessage")
viewController?.buildAgeMessage(for: "xyz") { string in
XCTAssertEqual(string, "Error retrieving age.")
e.fulfill()
}
waitForExpectations(timeout: 1)
}
}
i was reading about mocking singleton is tough
The notion is that if you have these APIManager.shared references sprinkled throughout your code, it’s harder to swap them out with the mock object. Injecting solves this problem.
Then, again, if you’ve now injected this APIManager instance everywhere to facilitate mocking and have eliminate all of these shared references, it begs the question that you wanted to avoid, namely why use a singleton anymore?

Declaration 'subscribe' cannot override more than one superclass declaration (ReSwift)

I'm having a problem when overriding a function from the ReSwift Pod. I've got the following mock class:
import Foundation
import Quick
import Nimble
import RxSwift
#testable import MainProject
#testable import ReSwift
class MockReSwiftStore: ReSwift.Store<MainState> {
var dispatchDidRun: Bool = false
var subscribeWasTriggered: Bool = false
init() {
let reducer: Reducer<MainState> = {_, _ in MainState() }
super.init(reducer: reducer, state: nil)
}
required init(
reducer: #escaping (Action, State?) -> State,
state: State?,
middleware: [(#escaping DispatchFunction, #escaping () -> State?) -> (#escaping DispatchFunction) -> DispatchFunction]) {
super.init(reducer: reducer, state: state, middleware: middleware)
}
override func subscribe<SelectedState, S>(
_ subscriber: S,
transform: ((Subscription<MainState>) -> Subscription<SelectedState>)?)
where S: StoreSubscriber,
S.StoreSubscriberStateType == SelectedState {
subscribeWasTriggered = true
}
}
}
And when overriding the subscribe method I'm getting following errors
Then when using autocomplete it also shows 2 occurences:
However when looking for the original function there's only one which looks like this
open func subscribe<SelectedState, S: StoreSubscriber>(
_ subscriber: S, transform: ((Subscription<State>) -> Subscription<SelectedState>)?
) where S.StoreSubscriberStateType == SelectedState
{
// Create a subscription for the new subscriber.
let originalSubscription = Subscription<State>()
// Call the optional transformation closure. This allows callers to modify
// the subscription, e.g. in order to subselect parts of the store's state.
let transformedSubscription = transform?(originalSubscription)
_subscribe(subscriber, originalSubscription: originalSubscription,
transformedSubscription: transformedSubscription)
}
This is my compiler output
I'm out of ideas so any help is greatly appreciated
Thanks!
Here is your issue:
class Some<T> {
func echo() {
print("A")
}
}
extension Some where T: Equatable {
func echo() {
print("B")
}
}
class AnotherSome: Some<String> {
override func echo() {
print("Doesn't compile")
}
}
The problem is: ReSwift developers declare Store.subscribe behavior as a part of interface and as a part of extension (I am not sure why they chose to do it instead of introducing other objects). Swift can't figure out which part you are trying to override and thus it doesn't compile. Afaik there are no language instruments which allow you to resolve this issue.
A possible solution is to implement MockStore as a StoreType and use Store object to implement behavior for StoreType interface.

How to specify completion handler with one function not return [duplicate]

Error: Cannot convert the expression type (String, MyType) to ()
From the following code
Test(method: {[weak self] (message: String) in self?.callback(message)}, instance: self)
and if I add a return statement, it works, and the error goes away
Test(method: {[weak self] (message: String) in self?.callback(message); return}, instance: self)
Not sure how to handle the above without having to have the dummy return statement, any advise.
Here's my class Test
public class Test {
private var instance: AnyObject?
private var method: ((message: String) -> ())?
public init(method: (String -> ())?, instance: AnyObject) {
}
}
Edit
I've done a playground based minimalistic example (please copy paste for a test)
class Test {
private var _method: ((String) -> ())?
weak private var _instance: AnyObject?
init(method: (String -> ())?, instance: AnyObject?) {
_method = method
_instance = instance
}
}
class Another {
func register() {
//this doesn't need a return
Test(method: {(message: String) in self.callback(message)}, instance: self)
//this needs a return once I add [weak self]
Test(method: { [weak self] (message: String) in self?.callback(message); return}, instance: self)
}
func callback(message: String) {
println(message)
}
}
Not sure how to handle the above without having to have the dummy return statement, any advise.
You have solved the problem beautifully. Anonymous functions automatically use a one-line function body as a return value, so to prevent that from causing a type mismatch with the expected return type (Void) you have to add another line of code so that it is not a one-line function body. The dummy return statement, which itself returns Void, is a great way to handle it; I would just use that and move on. There are some snazzier workarounds but what you have is precisely what I would do.
EDIT: To understand the source of the type mismatch, try this:
struct Test {
func voider() -> Void {}
}
let testMaybe = Optional(Test())
let result = testMaybe?.voider()
Now result is not a Void; it's an Optional wrapping a Void. That is what's happening to you; a Void is expected but your one-line anonymous function returns an Optional wrapping a Void. By adding another line that returns Void explicitly, you solved the problem.
The implicit return is returning the result of your callback() method. That return value conflicts with the closure's return value of void. You thus need an explicit, if ugly, return.

Resources