[英]How to pass a function to another class in Swift
I need some help passing a function to my second class.我需要一些帮助将 function 传递给我的第二个 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)?) -> ())'
它说:
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 Function 有一个返回值加上完成,你需要改变
function
var inisde Sub
和init
的语法
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 @escaping 需要添加
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.