【问题标题】:What is this Swift code doing? func somefunc(where: (_: NSLayoutConstraint) -> Bool)这段 Swift 代码在做什么? func somefunc(其中:(_:NSLayoutConstraint)-> Bool)
【发布时间】:2020-06-04 14:51:51
【问题描述】:

我习惯了 Objective-C,但不习惯 Swift。我了解 Swift 的基础知识,我尝试自己阅读文档并掌握它,但不能。让我感到困惑的是函数声明,我不明白发生了什么,它接受了哪些参数(或其他函数?)以及它对内部的where 做了什么。如果有人可以用 Objective-C 来翻译它,那就太好了,它会向我解释。

// extension of UIView
    func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
         if let constrainIndex = constraints.firstIndex(where: `where`) {
              removeConstraint(constraints[constrainIndex])
         }
    }

这就是它在其他代码部分(UIView 的子类)中的调用方式:

trackView.removeFirstConstraint { $0.firstAttribute == widthAttribute }

removeFirstConstraint(where: { $0.firstAttribute == oldConstraintAttribute && $0.firstItem === self && $0.secondItem == nil })

这也让我感到困惑,因为where的区别和用法。

【问题讨论】:

    标签: ios objective-c swift iphone cocoa-touch


    【解决方案1】:

    removeFirstConstraint 函数参数是所谓的闭包,即。一个函数。

    更多关于关闭的信息:https://docs.swift.org/swift-book/LanguageGuide/Closures.html

    在您的情况下,闭包必须具有签名(_: NSLayoutConstraint) -> Bool,即。它应该以layoutConstraint 作为参数并返回一个布尔值。 因此,对于您的情况,removeFirstConstraint 函数将对 UIView 的每个约束调用闭包,并删除第一个作为参数传递给闭包时将返回 true 的闭包。


    函数的两个调用是等价的,你可以将闭包作为函数的普通参数传递,

    trackView.removeFirstConstraint (where: { /*closure code*/ }) 
    

    或者这样简化:

    trackView.removeFirstConstraint { /*closure code*/ }
    

    $0 代表闭包的第一个参数。 因此,代码

    trackView.removeFirstConstraint { $0.firstAttribute == widthAttribute }
    

    将删除firstAttribute 等于widthAttribute 的第一个约束。


    哦,在代码中

    func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
             if let constrainIndex = constraints.firstIndex(where: `where`) {
                  removeConstraint(constraints[constrainIndex])
             }
        }
    

    作为参数传递给removeFirstConstraint 函数的where 闭包直接传递给函数firstIndex,该函数也将闭包作为参数。 firstIndex,在数组上调用,返回使闭包返回 true 的第一项的索引。

    where 周围的引号是必要的,因为 where 是一个 swift 关键字,因此必须对其进行转义才能用作标识符。

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多