此Swift代码在做什么? func somefunc(其中:(_:NSLayoutConstraint)-> Bool)

问题描述 投票:0回答:1

我习惯了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个回答
0
投票
更多有关闭包的信息: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]) } }

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

where周围的引号是必需的,因为在哪里是一个迅速的关键字,因此必须转义以用作标识符。
© www.soinside.com 2019 - 2024. All rights reserved.