dispatch_async in Swift - iphone

I am really new to this programming language called swift.
I use
dispatch_async(dispatch_get_main_queue(), ^{
});
this method for async-dispatch-queue in xcode 5.
I want implement it in swift language.
how do i implement dispatch queue in or swift?

For those of you viewing this post three years later as I did, the Swift functions have been improved. Now you can write:
DispatchQueue.main.async(execute: { () -> Void in
// Your code here
})

You can use this syntax:
dispatch_async(dispatch_get_main_queue(), {
println("hello")
})
However, when the last argument is a block, Swift lets you put it outside the parentheses. This makes the function seem more like a control structure (like a for or if statement). Thus you can do this:
dispatch_async(dispatch_get_main_queue()) {
println("hello")
}

Xcode gives you an easy help with that....
Just type in
dispatch_async and hit enter... Than XCode gives you something like this...
dispatch_async(queue: dispatch_queue_t!, block: dispatch_block_t! () -> Void)
now take your mouse and double-click on block: dispatch_block_t! () -> Void and XCode will automatically change this to a working closure expression :-)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Your Code here
})

Related

Is it possible to Extend functions in swift

I would like to ask if it's possible to extend functions or have some way to use them like this. Because I don't want to open task closure for every async function. I couldnt find any Nominal Type for functions in swift to extend.
func doSometingAsync() async -> Void {
}
// Non - desired
Task {
await doSometingAsync()
}
func makeItAsync() {
Task {
await self()
}
}
// Desired
doSometingAsync().makeItAsync()
// Extending those also not working
typealias Function = () -> Void
typealias AsnyFunction = () async -> Any?
Thank you!
You definitely shouldn't create a Task for every async function. If you are, something else is likely wrong. But your desired syntax is definitely impossible. You cannot attach methods to functions. Swift does not support it. It's not logically impossible (Go uses it regularly). It's just not a Swift feature, and I expect it will never be a Swift feature. It's not the direction Swift is evolving.
The following is legal if you want it:
func makeAsync(_ f: #escaping () async -> Void) {
Task { await f() }
}
makeAsync(doSometingAsync)
This is shorter than your proposed solution by a few characters, if that matters to you.
All said, though, if you need this a lot, you probably have an async design problem, and should investigate that.

swift syntax confusion dispatchqueue async [duplicate]

I'm new to Swift and looking at how the dispatch_async function works. The API doc shows dispatch_async having two parameters. However, I'm able to pass in one argument and it's okay.
dispatch_async(dispatch_get_main_queue()) {
}
How come I don't need to pass in two arguments?
Thank you,
API Doc:
It is a trailing closure syntax
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({
// closure's body goes here
})
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
This is how the dispatch_async looks like..
dispatch_async(dispatch_get_main_queue(), ^{
});
this part
^{
}
is the second parameter to your function, which is an anonymous code block used for callBack implementation.

Ambiguous use of DispatchQueue on trying to use main thread

This is a weird issue and I can't seem to find any help. On Swift 3, trying to make a call on the main thread I try to use DispatchQueue.main.async, but it doesn't compile.
Any ideas would be helpful.
Try this code instead, this is the Swift 3.0 syntax:
DispatchQueue.main.async(execute: { () -> Void in
})
For Swift 4.x you can also use:
DispatchQueue.main.async {
}

Completion Handlers in Swift

I'm fairly new at swift development and trying to get a handle on closures and completion handlers. I have a function with the following declaration inside a struct called ObjectData
func getData(id1:Int, id2:Int, completion: (dataObject? -> Void))
I am trying to call this function like
ObjectData.getData(1, id2: 2){
(let myObject) in
}
but i get the following error
Cannot invoke 'getData' with an argument list of type '(NSNumber, id2:
NSNumber, (_) -> _)'
Please can someone help
For better readability, change the header to this. Remember that you have to declare types, not variable names:
func getData(id1:Int, id2:Int, completion: (ObjectData?) -> (Void))
Now I personally use this syntax to use closures:
self.getData(1, id2: 1) { (data) -> (Void) in
// Some code executed in closure
}
If you want to study further, you can find full syntax of closures here (notice appropriate name of the website).
Hope it helps!
Far away from my Mac now, so I can't test, but try this:
ObjectData.getData(1, id2: 2, (dataObject) -> {
...code...
});
Also can't check now, but I think this also should work:
ObjectData.getData(1, id2: 2)(dataObject){
...code...
}
try to initialize your class first (ex. var objectData = ObjectData()) , and then call function with objectData.getData... it should work that way ..
In SWIFT 3,It is known as completion closure.
func getData(id1:Int, id2:Int, completion:#escaping(dataObject?) -> (Void)) {
//Do the stuff before calling completion closure
completion(value as? dataObject)
}
ObjectData.getData(id1:1, id2: 2,completion:{(data) -> (Void) in
//Do the completion stuff here
}

How NSAnimationContext completionHandler work with Swift Language

i couldn't port this to swift, rest of NSAnimationContext straight forward.
[[NSAnimationContext currentContext] setCompletionHandler:^(void) {
//doSomething here...
}];
in docs it says var completionHandler: (() -> Void)! it did not mean anything to me.
Thank you.
() -> Void is the signature for a Swift closure that takes no parameters and returns nothing. Use it much like you would an ObjC block:
NSAnimationContext.currentContext().completionHandler = {
// do something here
}
Note that since it's declared as a property, you should set it like one -- ObjC getter/setter pairs don't translate to Swift.