Ios 这个Swift代码在做什么?func-somefunc(其中:(\uu:NSLayoutConstraint)->;Bool)
我习惯了Objective-C,但不习惯Swift。我了解Swift的基本知识,我试着阅读文档并自己掌握,但不行。让我困惑的是函数声明,我不知道发生了什么,它接受了什么参数(或其他函数?),以及它在Ios 这个Swift代码在做什么?func-somefunc(其中:(\uu:NSLayoutConstraint)->;Bool),ios,objective-c,swift,iphone,cocoa-touch,Ios,Objective C,Swift,Iphone,Cocoa Touch,我习惯了Objective-C,但不习惯Swift。我了解Swift的基本知识,我试着阅读文档并自己掌握,但不行。让我困惑的是函数声明,我不知道发生了什么,它接受了什么参数(或其他函数?),以及它在where中做了什么。如果有人能用Objective-C来翻译,那就太好了,它会向我解释的 // extension of UIView func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
where
中做了什么。如果有人能用Objective-C来翻译,那就太好了,它会向我解释的
// extension of UIView
func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
if let constrainIndex = constraints.firstIndex(where: `where`) {
removeConstraint(constraints[constrainIndex])
}
}
代码的其他部分(UIView的子类)就是这样调用它的:
及
这也让我感到困惑,因为
的区别和用法,其中函数参数是所谓的闭包,即函数
有关闭包的更多信息,请参见:
在您的情况下,闭包必须具有签名(uuu: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
,该函数也将闭包作为参数<对数组调用code>firstIndex
,返回使闭包返回true的第一项的索引
where
周围的引号是必需的,因为where是swift关键字,所以必须将其转义以用作标识符
trackView.removeFirstConstraint { $0.firstAttribute == widthAttribute }
func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
if let constrainIndex = constraints.firstIndex(where: `where`) {
removeConstraint(constraints[constrainIndex])
}
}