Hello I'm trying to do this function in variable - ios

let fun:() -> () = func function() -> (){
print("Hello Function")
}
fun()
error: consecutive statements on a line must be separated by ';'

This is how you'd do it in Swift with closures:
let fun:() -> () = {
print("Hello Function")
}
fun()
Or you can do it this way:
func function() {
print("Hello Function")
}
let fun:(() -> ()) = function
fun()

Related

How do I combine observe two result rx sequences and subscribe with one closure arguments?

My sample is create call rest api two observable of result from load rx.request api from moya
func dataOneObservable() -> Observable<ObJectOneClass> {
return myprovider.rx.request(API.loadDataDetail())
.asObservable()
.retry()
.observeOn(MainScheduler.instance)
.filterSuccessfulStatusAndRedirectCodes()
.catchObjectError()
.mapObject(ObJectOneClassResult.self)
.map({ (response) -> ObJectOneClass in
if ObJectOneClass.data != nil {
if let item = response.data {
return item
}
return ObJectOneClass()
}
return ObJectOneClass()
})
}
func dataTwoObservable() -> Observable<ObJectTwoClass> {
return myprovider.rx.request(API.loadDataProfile())
.asObservable()
.retry()
.observeOn(MainScheduler.instance)
.filterSuccessfulStatusAndRedirectCodes()
.catchObjectError()
.mapObject(ObJectTwoClassResult.self)
.map({ (response) -> ObJectTwoClass in
if ObJectTwoClass.data != nil {
if let item = response.data {
return item
}
return ObJectTwoClass()
}
return ObJectTwoClass()
})
}
Then I want to combine result by use combineLastest of RxSwift but when I use .subscribe my response event can't passing result
my function call is same this:
func testCombine(completion:#escaping(_ result:Result<(ObJectOneClass,ObJectTwoClass),Error>) -> ()){
_ = Observable.combineLatest(dataOneObservable(), dataTwoObservable())
.asObservable()
.subscribe({ event in
//Event<(ObJectOneClass,ObJectTwoClass)>
//case .next((a, b)):
switch event{
case .next(response):
completion(.success(response))
case let .error(error):
completion(.failure(error as NSError))
default:
break
}
})
}
Then
please help me guide to syntax completion this.
Here's an interesting solution:
func testCombine(completion: #escaping(_ result: Result<(ObJectOneClass, ObJectTwoClass), Error>) -> ()) {
_ = Observable.combineLatest(dataOneObservable(), dataTwoObservable())
.map(Result.success)
.catch(combine(Result.failure, Observable.just))
.subscribe(onNext: completion)
}
func combine<A, B, C>(_ f: #escaping (A) -> B, _ g: #escaping (B) -> C) -> (A) -> C {
{ g(f($0)) }
}
That map to Result.success, catch just Result.failure is really common when you are dealing with Result types. It's so common that you might want to make a single operator to capture the notion.
extension Observable {
func toResult() -> Infallible<Result<Element, Error>> {
map(Result.success)
.asInfallible(onErrorRecover: combine(Result.failure, Infallible.just))
}
}
In response to your comment, here's a somewhat less advanced version:
extension Observable {
func toResult() -> Infallible<Result<Element, Error>> {
map(Result.success)
.asInfallible(onErrorRecover: { Infallible.just(Result.failure($0)) })
}
}
OK This my topic can fix problem by declare let in .next
func testCombine(completion:#escaping(_ result:Result<(ObJectOneClass,ObJectTwoClass),Error>) -> ()){
_ = Observable.combineLatest(dataOneObservable(), dataTwoObservable())
.asObservable()
.subscribe({ event in
switch event{
case .next((let one,let two)):
completion(.success((one,two)))
case let .error(error):
completion(.failure(error as NSError))
default:
break
}
})
}

How to pass a function to another class in Swift

I need some help passing a function to my second class. I have tried many things but it still not work.
class Main {
func one() {
let test = Sub(function: two)
}
func two(val: Int, completion: ((Int, String)?)->()) { }
}
class Sub {
var function: (Int, ((Int, String)?)->())
init(function: (Int, ((Int, String)?)->())) {
self.function = function
}
}
Why is it that i get error on this line
let test = Sub(function: two)
which says: Cannot convert value of type '(Int, ((Int, String)?) -> ()) -> ()' to expected argument type '(Int, ((Int, String)?) -> ())'
What is the reason?
Function has a return value plus the completion , you need to change syntax of function var inisde Sub and the init also
class Main {
func one() {
let test = Sub(function: two)
}
func two(val: Int, completion: ((Int, String)?)->()) { }
}
class Sub {
var function: ((Int, ((Int, String)?)->())) -> ()
init(function:#escaping ((Int, ((Int, String)?)->())) -> ()) {
self.function = function
}
}
#escaping need to be added
class Main {
func one() {
let test = Sub(function: two)
}
func two(val: Int, completion: (Int, String)?)->() { }
}
class Sub {
var function: (Int, (Int, String)?)->()
init(function: #escaping (Int, (Int, String)?)->()) {
self.function = function
}
}

Callbacks in iOS swift 3

Hello is it possible to make a callback like such? I want to pass a function as a parameter to be able run the callback function after some task is finished.
class ConnectBLE {
var callBackFunc: ()->()
init(callFunc: #escaping () -> ()){
callBackFunc = callFunc
}
func runCallBackFunc() {
callBackFunc()
}
}
class DelegateARC {
private let object = ConnectBLE(callFunc: RaspakHC05)
func RaspakHC05() {
print("hello from a callback")
}
}
But I'm having an error.
Cannot convert value of type '(DelegateARC) -> () -> ()' to expected argument type '() -> ()'
You cannot run non-lazy code on the top level of the class which requires self (RaspakHC05).
Apart from that you have to call runCallBackFunc() in ConnectBLE somewhere to execute the closure.
You could do (in a Playground)
class ConnectBLE {
var callBackFunc: ()->()
init(callFunc: #escaping () -> ()){
callBackFunc = callFunc
}
func runCallBackFunc() {
callBackFunc()
}
}
class DelegateARC {
init() {
ConnectBLE(callFunc: RaspakHC05).runCallBackFunc()
}
func RaspakHC05() {
print("hello from a callback")
}
}
DelegateARC() // prints "hello from a callback"
Another way (use Optional to delay giving object its real value until initialization has otherwise fully taken place):
class ConnectBLE {
var callBackFunc: ()->()
init(callFunc: #escaping () -> ()){
callBackFunc = callFunc
}
func runCallBackFunc() {
callBackFunc()
}
}
class DelegateARC {
private var object : ConnectBLE! //*
init() {
self.object = ConnectBLE(callFunc: RaspakHC05) // *
}
func RaspakHC05() {
print("hello from a callback")
}
}
You are trying to pass a function instead a closure. You have to use a closure and lazy instantiation to make it work:
class DelegateARC {
private lazy var object: ConnectBLE = {
return ConnectBLE(callFunc: self.RaspakHC05)
}()
var RaspakHC05: () -> () {
return {
print("hello from a callback")
}
}
}

What is return type " () "?

I have a function, which takes several other functions as arguments:
class Iterator {
func iterateItems(itemArray: [Items], removeItem: (Items) -> Void, addItem: (inout Items) -> Void, calculateEfficiency: () -> Void) -> [Items] {
// function body
}
}
And I call it in its class' subclass like this:
class WPCalculator: Iterator {
func removeWeaponItem(item: WeaponItems) { ... }
func addWeaponItem(item: inout WeaponItems) { ... }
func calcWeaponDamage() { ... }
func iterateWPItems() {
return iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem as! (Items) -> Void, addItem: addWeaponItem as! (inout Items) -> Void, calculateEfficiency: calcWeaponDemage)
}
}
Also the WeaponItems class is a subclass of Items class:
class WeaponItems: Items { ... }
Xcode gives me a warning on addWeaponItem:
Cast from (inout WeaponItems) -> () to unrelated type (inout Items) -> Void always fails
I can't understand the -> () return type, clearly its not what my function does, the other functions passed as arguments without inout parameters just worked fine
Your function iterateItems has removeItem addItem calculateEfficiency parameter is function type. So you must use function name as params when call function.
like this:
iterateItems(itemArray: WeaponItems.weaponItems, removeItem: removeWeaponItem, addItem: addWeaponItem, calculateEfficiency: calcWeaponDamage)
I think () same as Void
The warning occurs because WeaponItems and Items do not match
http://ericasadun.com/2015/05/11/swift-vs-void/

Using same then/catch/finally blocks for two promises of different types

I have the following operations:
class CreateObjectOperation {
// ...
func promise() -> Promise<Object>
}
class DeleteObjectOperation {
// ...
func promise() -> Promise<Void>
}
I want to be able to use the same then/catch/finally blocks for both. I tried the following:
let foo: Bool = ...
firstly {
(foo ?
CreateObjectOperation().promise() :
DeleteObjectOperation().promise()
) as Promise<AnyObject>
}.then { _ -> Void in
// ...
}.finally {
// ...
}.catch { error in
// ...
}
but this does not compile. Is there any working solution (apart from moving the code from blocks to separate functions, which I would like to avoid)?
Found it:
firstly { _ -> Promise<Void>
(foo ?
CreateObjectOperation().promise().then { _ in Promise<Void>() } :
DeleteObjectOperation().promise()
) as Promise<AnyObject>
}.then { _ -> Void in
// ...
}

Resources