在 Swift 中将函数作为参数传递

2024-05-05

在 iOS 8 中,我的以下功能按我的预期工作:

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String,
    secondBtnStr:String,
    caller:UIViewController) {
        let userPopUp = UIAlertController(title:title,
            message:msg, preferredStyle:UIAlertControllerStyle.Alert)
        userPopUp.addAction(UIAlertAction(title:firstBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in}))
        userPopUp.addAction(UIAlertAction(title:secondBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in}))
        caller.presentViewController(userPopUp, animated: true, completion: nil)
}

我想做如下的事情,以便将触摸一个或另一个按钮时要执行的方法作为参数传递:

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String, firstSelector:Selector,
    secondBtnStr:String, secondSelector:Selector,
    caller:UIViewController) {
        let userPopUp = UIAlertController(title:title,
            message:msg, preferredStyle:UIAlertControllerStyle.Alert)
        userPopUp.addAction(UIAlertAction(title:firstBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in caller.firstSelector()}))
        userPopUp.addAction(UIAlertAction(title:secondBtnStr, style:UIAlertActionStyle.Default,
            handler:{action in caller.secondSelector()}))
        caller.presentViewController(userPopUp, animated: true, completion: nil)
}

显然我没有对firstSelector和secondSelector做正确的事情,因为我到目前为止所尝试的方法都不起作用。我想我没有使用正确的语法来实现我想要的,但我确信可以做我想做的事情。知道如何正确地做到这一点吗?


你的问题的一个字答案是Closures https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

闭包的默认语法是() -> ()

您可以直接提及方法定义,而不是选择器

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String, firstSelector:(sampleParameter: String) -> returntype,
    secondBtnStr:String, secondSelector:() -> returntype,
    caller:UIViewController) {
    //Your Code
}

但使用它会产生可读性问题,所以我建议你使用 typeAlias

typealias MethodHandler1 = (sampleParameter : String)  -> Void
typealias MethodHandler2 = ()  -> Void

func showConfirmBox(msg:String, title:String,
                    firstBtnStr:String, firstSelector:MethodHandler1,
                    secondBtnStr:String, secondSelector:MethodHandler2) {

    // After any asynchronous call
    // Call any of your closures based on your logic like this
    firstSelector("FirstButtonString")
    secondSelector()
}

你可以这样调用你的方法

func anyMethod() {
   //Some other logic 

   showConfirmBox(msg: "msg", title: "title", firstBtnStr: "btnString", 
         firstSelector: { (firstSelectorString) in
              print(firstSelectorString) //this prints FirstButtonString
         }, 
         secondBtnStr: "btnstring") { 
           //Invocation comes here after secondSelector is called

         }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swift 中将函数作为参数传递 的相关文章

随机推荐

  • SignalR 与 android(Java) 有问题

    我想在 android 应用程序和 net core 服务器项目之间进行实时通信 我在 stackoverflow 中尝试了一个问题 我跟着这个one https stackoverflow com questions 32573823 h
  • 如何获取字符串宽度

    我需要在类库中构建一个函数 该函数接受一个字符串和该字符串的特定字体 然后获取字符串的宽度 那么我怎样才能得到字符串边界宽度呢 另一种方法是使用TextRenderer 并致电its MeasureString http msdn micr
  • 无法在 Silverlight 样式中添加系统颜色?

    我在 XAML 中为 SystemColors 定义了资源 如果我将 Foregroung 属性直接设置为 TextBlock 效果会很好 但是 如果我在样式中分配前景属性 则会收到如下所示的错误 我不确定问题是什么以及如何解决 任何想法都
  • Python NET 调用具有返回值和输出参数的 C# 方法

    我有以下静态 C 方法 public static bool TryParse string s out double result 我想使用 Python NET 包从 Python 调用它 import clr from System
  • 将每个 http 块映射到特定的身份验证提供程序

    我想根据用户的上下文路径来设置 Spring Security 配置 如果用户反对某个网址http 路径1 资源1 http path1 resource1我想将他们定向到特定的身份验证提供商 如果他们进来http 路径2 资源2 http
  • C 或 C++ 中是否有轻量级的多部分/表单数据解析器? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在考虑将多部分表单数据解析集成到 Web 服务器模块中 以便可以减轻后端 Web 应用程序 通常用动
  • 带有 Spock Stub 的泛型

    我无法为泛型类编译 Spock 存根 构造函数的签名如下 SomeClass SerSup
  • Windows 中的 TPM PCR 生成

    我有一台带有 TPM 的计算机 并且在其上运行 Windows 7 我有一段代码 我想运行它并获取当时的 PCR 寄存器值 我怎样才能做到这一点 其次 如果我在其他机器上运行相同的代码 我可以获得相同的 PCR 值吗 如果我不能 那么有什么
  • 一个阻塞但非模态的 QDialog?

    我有一堆图像 我想对其执行一些操作 处理完每个图像后 我的程序应该弹出一个对话框 提示用户是否要继续处理下一个图像或中止 在此之前 他们应该有机会对图像或参数进行一些手动更改 无论如何 他们必须能够访问应用程序的窗口 而调用对话框的方法的执
  • 类模板的可变参数构造函数模板的特化

    这是一个带有可变参数构造函数的类 它专门用于从临时对象进行复制和移动 template
  • 在家庭和办公室进行开发,GIT 会比使用 xcopy 的 SVN 更容易吗?

    如果出于安全原因 源代码只能存储在我的家庭计算机和办公室计算机上 如果传输代码的唯一方法是 USB 密钥 那么哪种源代码控制是最好的 SVN还是GIT 注意 两台计算机之间没有网络连接 我推荐git 无论哪种方式 您都需要 USB 密钥上的
  • Java中的字符算术

    在玩的过程中 我遇到了一些对我来说似乎很奇怪的事情 以下不是有效的 Java 代码 char x A x x 1 possible loss of precision 因为其中一个操作数是整数 所以另一个操作数被转换为整数 结果无法分配给字
  • 垂直对齐 li 内的图像和文本

    我试图将列表元素中的图像和一些文本垂直对齐到中间 但没有运气 eg ul li img src somepath sometext li li img src somepath2 sometext2 li ul 我该怎么做 谢谢 假设您的列
  • 如何以编程方式从 Gitlab LFS 检索文件?

    Question 当需要身份验证时 如何以编程方式从 Gitlab 下载文件 Context 我想以编程方式从 Gitlab 检索 LFS 文件 这API https docs gitlab com ee api不幸的是 没有提供正确的终点
  • Sails.js 升级到 v1 反向区分大小写查询

    升级到 sails v1 后 控制器中的所有请求都变得区分大小写 尽管这是预料之中的 但在这里评论道 https sailsjs com documentation concepts models and orm models case s
  • 为什么 SNMP 通常在 UDP 上运行而不是 TCP/IP 上?

    今天早上 工作中出现了大问题 因为 SNMP 陷阱没有 通过 因为 SNMP 是通过 UDP 运行的 我记得在大学网络课上 UDP 不能像 TCP IP 那样保证传输 维基百科说 SNMP 可以在 TCP IP 上运行 但 UDP 更常见
  • Accelerate 和 Repa 是否有不同的用例?

    我一直在玩 Repa 和 Accelerate 它们都很有趣 但我不知道何时使用其中一个 何时使用另一个 他们是一起成长 是竞争对手 还是只是为了解决不同的问题 Repa 是一个用于高效数组构建和遍历的库 用 Haskell 编程并在 Ha
  • 是否可以用 Rust 编写 Quake 的快速 InvSqrt() 函数?

    这只是为了满足我自己的好奇心 是否有这样的实现 float InvSqrt float x float xhalf 0 5f x int i int x i 0x5f3759df i gt gt 1 x float i x x 1 5f x
  • 当从搜索表单动态构建 WHERE 子句时,如何防止 SQL 注入?

    我知道在 Java 中保护 SQL 查询免受 SQL 注入的唯一真正正确的方法是使用准备好的语句 然而 这样的语句要求基本结构 选择的属性 连接的表 WHERE条件的结构 不会改变 我这里有一个 JSP 应用程序 其中包含一个带有大约十几个
  • 在 Swift 中将函数作为参数传递

    在 iOS 8 中 我的以下功能按我的预期工作 func showConfirmBox msg String title String firstBtnStr String secondBtnStr String caller UIView