Block conversion in swift from Objective-c - ios

How to convert following block from Objective-C to Swift. Am using Objective-C files in Swift using bridge header. But small confusion in block conversion
Objective-C Block:
+ (void) while:(id)obj name:(void(^)(type*))callback;
Sample output:
[Sub while:keeper viewControllerChanged:^(NSString* newNickname) {
NSLog(#"\nVC2- Now screen is in: %#", newNickname);
}];
How to convert this in swift ?
EDIT:
Swift block error is
Sub.while(obj: AnyObject!, viewControllerChanged: ((String!) -> Void)!)

When you define :
class func while1(obj:AnyObject, callback name:((newNickname:NSString?) -> Void)) {
}
And when call function :
self.while1(self) { (newNickname) -> Void in
print("\nVC2- Now screen is in:" + "\(newNickname)")
}
EDIT :
Okay, Then you just want to call it from swift..right..? Then use this statement :
ClassName.while1(obj as AnyObject) { (nickName:String!) -> Void in
print(nickName)
}
But first make sure that in your definition statement "type" indicates for what DataType, so please define there actual DataType
+ (void)while:(id)obj name:(void(^)(type*))callback;
to --> For example :
+ (void)while1:(id)obj name:(void(^)(NSString *))callback;
And one more thing to note that while in built in keyword, please do not use it if possible.

You can call like this:
YourClassName.while2(Yourparameter , name: {(nickName : String) -> Void in
})
I hope this help.

I'm not sure if you are asking how to write blocks in swift or if I'm not completely getting your question. But if it's the first then...
(void(^)(type*))callback
becomes
callback: (param:type*)->(returnType*)
i.e.
func doSomething(callback:((number:Int)->()))
is called like
doSomething(callback:{number in
print("\(number)")
})

Related

Firebase Swift 3 Database crashes on setValue withCompletionBlock

I am using Firebase on iOS with Swift 3.
When I use
FIRDatabase.database().reference().child("child").setValue("value") {
(error: Error?, databaseReference: FIRDatabaseReference) in
print("Error while setting value \(error)")
}
The app crashes on runtime with the following log:
*** Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(nodeFrom:priority:) Cannot store object of type _SwiftValue
at . Can only store objects of type NSNumber, NSString, NSDictionary,
and NSArray.'
I tried to use the same function but without the trailing closure and for some reason, it works!
FIRDatabase.database().reference().child("child").setValue("value",
withCompletionBlock: {
(error: Error?, databaseReference: FIRDatabaseReference) in
print("Error while setting value \(error)")
})
Is there something special about trailing closures and Swift 3?
tl;dr: Firebase provides a setValue(_ value: Any?, andPriority priority: Any?) which is incorrectly matched when using a trailing closure with setValue(_ value: Any?, withCompletionBlock: (Error?, FIRDatabaseReference) -> Void).
Solution: When using an API that has many varieties, avoid using trailing closures. In this case, prefer setValue(myValue, withCompletionBlock: { (error, dbref) in /* ... */ }); do not use setValue(myValue) { (error, dbref) in /* ... */ }.
Explanation
This appears to be a Swift bug. As in other languages, such as Java, Swift generally chooses the most specific overload. E.g.,
class Alpha {}
class Beta : Alpha {}
class Charlie {
func charlie(a: Alpha) {
print("\(#function)Alpha")
}
func charlie(a: Beta) {
print("\(#function)Beta")
}
}
Charlie().charlie(a: Alpha()) // outputs: charlie(a:)Alpha
Charlie().charlie(a: Beta() as Alpha) // outputs: charlie(a:)Alpha
Charlie().charlie(a: Beta()) // outputs: charlie(a:)Beta
However, when overloaded functions match a trailing closure, Swift (at least, sometimes) selects the more general type. E.g.,
class Foo {
func foo(completion: () -> Void) {
print(#function)
}
func foo(any: Any?) {
print(#function)
}
}
func bar() {}
Foo().foo(completion: bar) // outputs: foo(completion:)
Foo().foo(any: bar) // outputs: foo(any:)
Foo().foo() { () in } // outputs: foo(any:)
// ^---- Here lies the problem
// Foo().foo(bar) will not compile; can't choose between overrides.
Any? is a more general type than () -> Void -- i.e., "anything, even null" is more broad than "a function receiving 0 parameters and returning something of type Void". However, the trailing closure matches Any?; this is the opposite of what you would expect from a language that matches the most specific type.
While there is an accepted answer, which provides some clarity, explaining that it's a Swift bug is not really accurate. That being said, the explanation is accurate but not for this issue.
Allowing the closure to be added to setValue in the first place is the real bug.
A more accurate answer is that there is no completion block/closure for the setValue function, which is why it fails.
The specific function -setValue: does NOT have a closure, which is why it's crashing. i.e. it's an incorrect implementation in your code. Per the docs:
func setValue(_ value: Any?)
note that the setValue function does NOT have a closure and if you add one the function will have no idea what to do with that data.
To use a completion block/closure, you must call the correct function which is
-setValue:withCompletionBlock:
Bottom line is you can't randomly add a parameter or call to a function that's not designed to accept it.
This is obviously not valid but conceptually it's the same error.
let a = "myString"
a.append("x") { (error: Error?) }
In this case the compiler knows the the string.append function doesn't have a closure option and catches it before compiling.
So go a tad further, this code complies & runs but also generates an error
ref.child("child").setValue("value") { }
Again, setValue doesn't have a closure so this code is improperly implemented.
To clarify, given a class
class MyClass {
var s = ""
var compHandler = {}
func setValue(aString: String) {
self.s = aString
}
func setValue(aString: String, someCompletionHandler: completionHandler) {
self.s = aString
self.compHandler = someCompletionHandler
}
}
Note that setValue:aString is a totally different function than setValue:aString:someCompletionHandler
The only parameter that can be based to setValue:aString is a String as the first and only parameter.
The setValue:aString:someCompletionHandler will be passed two parameters, a String in the first position and a completionHandler in the second position.
The actual completion block is the second parameter passed.
param1, param2
------, ---------------
string, completionBlock
This is why
setValue(value) {}
is improperly formatted whereas
setValue(value, withBlock: {})
is properly formatted.

Cannont convert value of type () -> Void

I have been converting over to the new swift syntax. I'm having trouble tweaking a third party SQLITE party into Swift 3.0. It appears there has been an update to closures: https://github.com/apple/swift-evolution/blob/master/proposals/0103-make-noescape-default.md
I cannont figure out for the life of me how to pass the variable "task" to my function to be added to the GCD queue Here's what my code looks like when I call my function "put on thread."
let foo: ()->Void = {
let interesting = "confusing"
print("Swift 3.0 Conversion has been " + interesting + " with some parts!")
}
/// Compiler error: Cannot convert value of type () -> Void to expected argument SwiftData
putOnThread(foo)
///I have also tried this and I get a different compiler error:
SwiftData.putOnThread(foo)
//Compiler error: Use an instance member 'putOnThread' on type 'SwiftData'. Did you mean to use a value type of SwiftData instead?
Here's what the putOnThread method looks like:
extension SwiftData {
public func putOnThread(closure: #escaping ()->Void) {
SQLiteDB.sharedInstance.queue.sync {
closure()
}
}
}
Note: SwiftData is a struct. Any help would be greatly appreciated! Maybe once I'm finished, I can happily commit my Swift 3.0 changes back to github!

Convert a swift closure into a block

I need to pass a callback parameter from a swift class to an Objective-C one.
I have searched for the way to do it, but I am struggling, I got this:
public typealias RequestCallBackObject = (gbRequest: AnyObject!, status: ServiceStatus, response: AnyObject?) -> ()
But how would it be in Objective-C ?
It should be something like this:
-(void) testMethod:(void(^) (id gbRequest, ServiceStatus *serviceStatus, id response) ) blockName {
}
Swift's AnyObject equivalent is id in Objective-C.

Specify Objective-C closure variable names from Swift

I'm writing some Swift code that i'd like to use in Objective-C. The headers are all generated automatically but when using closures (that become blocks in objective-c), the variable names are missing.
For Example:
#objc public func doSomething(success: (result: String) ->())
becomes
-(void)doSomething:(NSString * _Nonnull)success;
Where i would have expected it to be:
-(void)doSomething:(NSString * result)success;
Is this an Xcode bug or is there a way to specify what the variable should be named?
function and closure in Swift are the same type, you can try something like
// what you have
func boo(mf: String->Void) { mf("alfa") }
boo { (str) -> Void in
print(str)
} // "alfa"
// try this
func foo(str: String) { print(str + " beta") }
// and see the signature in Objective C
boo(foo)
/*
alfa
alfa beta
*/

Closure declaration in swift 2.0

In swift 2.0, what is the correct closure declaration? I've seen examples done like below, but it doesn't seem to work for me.
In SomeClass:
var successBlock: (Bool) -> () = { _ in }
and it would be called like this:
self.successBlock(true)
Then in SomeOtherClass:
let someClass = SomeClass
someClass.successBlock {
success in
//code here
}
Bit this gives me an error: (_) -> is not convertible to Bool
I've tried googling around a bit but with no luck...
Is there a syntax change with swift 2.0 or is it me?
If you're trying to set the successBlock, you should do it with an = sign:
someClass.successBlock = { success in
// code here
}
EDIT: You mentioned that you only want your other class to "listen", but what does "listen" mean? If you want to listen to every time the closure gets called with some value and do something depending on it, you may want to have an array of closures instead:
var successBlocks : [Bool -> Void] = []
which you can invoke like this:
let value = true
successBlocks.forEach{ $0(value) }
When you want to listen to invocations, you can do this:
someClass.successBlocks.append( { success in
// do the stuff
} )
which won't override any other closures already in the array, so probably that's what you wanted to do.

Resources