Swift中Block的语法

 zxcvbnm89 发布于 2023-01-11 17:33

我试图从Objective-C重写为Swift,我无法弄清楚语法或理解文档

这是Objective-C中的一个简化示例我写道:

[UIView animateWithDuration:10.0 animations:^{self.navigationController.toolbar.frame = CGRectMake(0,10,0,10);}];

我如何在Swift中写这个?

这是自动完成模板给出的:

UIView.animateWithDuration(duration: NSTimeInterval, animations: (() -> Void))

67cherries.. 16

这是swift闭包格式:

{(parameter:type, parameter: type, ...) -> returntype in
    //do stuff  
}

这是你应该做的:

//The animation closure will take no parameters and return void (nothing).
UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in
    //Animate anything.
})

这是闭包的文档.

3 个回答
  • 这是swift闭包格式:

    {(parameter:type, parameter: type, ...) -> returntype in
        //do stuff  
    }
    

    这是你应该做的:

    //The animation closure will take no parameters and return void (nothing).
    UIView.animateWithDuration(duration: NSTimeInterval, animations: {() -> Void in
        //Animate anything.
    })
    

    这是闭包的文档.

    2023-01-11 17:36 回答
  • 由于预期的参数类型和动画参数的返回类型是已知的,因此编译器可以毫无问题地推断它们.这应该工作(虽然我目前没有可用的游乐场:

    UIView.animateWithDuration(10.0, animations: {
      self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
    })
    

    有关闭包的更多信息,请参阅swift文档中的章节

    请注意CGRect()- 开发人员文档显示CGRect()在swift代码中使用.也许它需要导入?

    更新注释:您还可以使用如下的尾随闭包:

    UIView.animateWithDuration(10.0) {
      self.navigationController.toolbar.frame = CGRect(x:0.0, y:10.0, width:10.0, height:0.0)
    }
    

    2023-01-11 17:36 回答
  • 以下代码可以指导您编写自己的块.

    class func testFunc(completion: ((list : NSArray!) -> Void)?) {
        //---  block code.
        if completion! != nil {
            completion! (list: NSArray())
        }
    }
    

    你可以称之为 -

    className.testFunc {
    (list: NSArray!) -> Void in
    }
    

    2023-01-11 17:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有