简体   繁体   English

如何将 function 传递给 Swift 中的另一个 class

[英]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 Subinit的语法

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.

相关问题 如何将UIViewController传递给Swift中的另一个类? - How to pass UIViewController to another class in Swift? 无法将变量从类中的函数传递给Swift中的另一个函数 - cannot pass a variable from a function in a class to another function in Swift 如何调用位于 Swift 中另一个类中的函数? - How to call a function that is located in another class in Swift? Swift:如何将闭包参数从类方法传递给类中的函数 - Swift: How to pass closure argument from a class method to a function in the class 如何查找在ViewDidLoad中调用的UIImage的值,并传递到Swift中的另一个函数 - How to find value of UIImage called in ViewDidLoad, pass to another function in Swift 如果在 Swift 中触发了另一个 function,如何编写将通过的单元测试 - How to write a unit test which will pass if another function was triggered in Swift 如何在Swift 2中将NSDictionary传递给函数并返回另一个NSDictionary - How to pass an NSDictionary to a function and return another NSDictionary in Swift 2 如何将特定元素从数组传递到另一个视图或 function? Swift - How to pass specific element from array to another view or function? Swift 如何将纬度和经度传递给另一个函数 - 快速定位 - How to pass latitude and longitude to another function - swift location 在另一个类Swift中调用函数 - Calling a function in another class Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM