简体   繁体   English

如何在 swift 中创建具有特定类型别名的闭包?

[英]How to create closure with specific typealias in swift?

I'm using the swift package OnboardKit and it requires a specific closure type that I cannot figure out.我正在使用 swift package OnboardKit ,它需要一种我无法弄清楚的特定闭合类型。 The class OnboardPage requires a type OnboardPageAction for the parameter action . class OnboardPage需要类型OnboardPageAction作为参数action

public typealias OnboardPageCompletion = ((_ success: Bool, _ error: Error?) -> Void)
public typealias OnboardPageAction = (@escaping OnboardPageCompletion) -> Void
OnboardPage(title: "Title",
            description: "description",
            action: action)

This is my latest attempt, I tried several variations along those lines.这是我最近的尝试,我尝试了这些方面的几种变化。

let action: ((_ success: Bool, _ error: Error?) -> ()) = {_,_ in
    print("help")
}

XCode fails with the error message: XCode 失败并显示错误消息:

Cannot convert value of type '(Bool, Error?) -> Void' to expected argument type 'OnboardPageAction?'无法将类型“(布尔,错误?) - > Void”的值转换为预期的参数类型“OnboardPageAction?” (aka 'Optional<(@escaping (Bool, Optional) -> ()) -> ()>') (又名'可选<(@escaping(布尔,可选)->())->()>')

What am I doing wrong here?我在这里做错了什么? Is the mistake in my closure definition or in the way I use it in the OnboardPage() call?是我的闭包定义错误还是我在 OnboardPage() 调用中使用它的方式错误? Thanks:)谢谢:)

(I learned details about closures here Closures Swift How To , but I am not able to define the right closure type that the package expects) (我在这里了解了有关闭包的详细信息Closures Swift How To ,但我无法定义 package 期望的正确闭包类型)

Judging from the context, I guess that the purpose of the action parameter is to allow you run some code when an OnboardPage is presented.从上下文来看,我猜想action参数的目的是让您在出现OnboardPage时运行一些代码。 This "action" might take some time (it might not finish when action returns), so it gives you a completion handler parameter that you can call to indicate that what you want to do is done.这个“动作”可能需要一些时间(当action返回时它可能不会完成),因此它为您提供了一个完成处理程序参数,您可以调用该参数来指示您想要做的事情已经完成。

If you just want to print Hello, you can just call the parameter after you printed hello to indicate that you finished what you want to do:如果你只是想打印 Hello,你可以在打印 hello 之后调用参数来表明你完成了你想要做的事情:

OnboardPage(title: "Title",
        description: "description",
        action: { completion in
            print("Hello")
            completion(true, nil)
        })

or simply或者干脆

OnboardPage(title: "Title",
        description: "description") {
            print("Hello")
            $0(true, nil)
        }

The first argument indicates whether the action is successful, the second contains an optional error for when it fails.第一个参数表示操作是否成功,第二个参数包含一个可选的错误,当它失败时。

The declaration of an action should look like this to match the defintions provided:动作的声明应如下所示以匹配提供的定义:

let action: OnboardPageAction = { (_ closure: ((_ success: Bool, _ error: Error?) -> Void)) in
    print("action")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM