How to create shared closures in Swift

I would like to create a function that uses a generic block in swift.

My first attempt was as follows:

func saveWithCompletionObject(obj : AnyObject, success : AnyObject -> Void, failure : Void -> Void)

But as soon as I call this function with another block, for example:

func doSomething(success : String -> Void, failure : Void -> Void)
{
    saveWithCompletionObject("Example", success, failure)
}

I get an error message: 'AnyObject' is not a subtype of 'String'

Thanks in advance!

+3
source share
1 answer

You cannot pass a type closure to a type String->Voidparameter AnyObject->Void.

However, you can define a generic function:

func saveWithCompletionObject<T>(obj : T, success : T -> Void, failure : Void -> Void) {
    // ...
    success(obj)
}

Now the compiler can verify that it objhas the same type as the parameter success, for example:

func doSomething(success : String -> Void, failure : Void -> Void)
{
    saveWithCompletionObject("Example", success, failure)
}

func doSomethingElse(success : Int -> Void, failure : Void -> Void)
{
    saveWithCompletionObject(13, success, failure)
}

But I would recommend that I saveWithCompletionObjectjust take the Void->Void parameter (no generics):

func saveWithCompletionObject(success : Void -> Void, failure : Void -> Void) {
    // ...
    success()
}

and the caller wraps it closes:

func doSomething(success : String -> Void, failure : Void -> Void)
{
    saveWithCompletionObject( { success("Example") } , failure)
}

func doSomethingElse(success : Int -> Void, failure : Void -> Void)
{
    saveWithCompletionObject( { success(13) }, failure)
}

, . :

func andNowForSomethingCompletelyDifferent(success : (Int, Double) -> Void, failure : Void -> Void)
{
    saveWithCompletionObject( { success(13, M_PI) }, failure)
}
+4

Source: https://habr.com/ru/post/1624551/


All Articles