ios - How handle different threads in recursive function in swift? -
i have recursive function calculate factorial , want make calculation in background thread, how handle it? i'm trying this:
func factorial(of number: double) -> double { var result: double = 0 if number > 170 { return double.infinity } if number != double(int(number)) || number < 1 {return 0} if number == 1 { return 1 } dispatchqueue.global(qos: .background).async { result = number * factorial(of: number - 1) } return result }
i understand wrong, don't understand how have do. thank's help!
my recommendation split synchronous , asynchronous functions:
func factorial(of number: double, completion: @escaping (double) -> ()) { dispatchqueue.global(qos: .background).async { let result = factorial(of: number) dispatchqueue.main.sync { //i don't know thread you're intending use, picked main :) completion(result) } } } func factorial(of number: double) -> double { var result: double = 0 if number > 170 { return double.infinity } if number != double(int(number)) || number < 1 {return 0} if number == 1 { return 1 } result = number * factorial(of: number - 1) return result }
this allows meat of work happen in whichever way want, without having worry potential threading issues.
Comments
Post a Comment