Swift数组闭包扩展会引发错误

时间:2016-12-29 17:35:34

标签: ios arrays swift

我在Array实例上有一个扩展,用于循环使用索引,如下所示:

[.leading,.trailing,.bottom,.top].fun {
    (index, element) in

    var c : Int = index % 2 == 0 ? 20 : -20 // THAT LINE
    NSLayoutConstraint(item: subView, attribute: element, relatedBy: .equal, toItem: self.view, attribute: element , multiplier: 1, constant: c ).isActive = true
}

现在,我想称之为:

  swift
Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). Type :help for assistance.
  1>  
  2>  
  3> extension Array { 
  4.     func fun (_ iterator: (Int, Element) -> Void) -> Void { 
  5.         for (key,value) in self.enumerated() { 
  6.             iterator(key,value) 
  7.         } 
  8.     } 
  9. }
 10> [0,1,2,3,4].fun { 
 11.     (index, element) in 
 12.  
 13.     var c : Int = index % 2 == 0 ? 20 : -20 // THAT LINE 
 14.     print(c)
 15. } 
20
-20
20
-20
20

然而,这会引发错误:表达式的类型不明确,没有更多的上下文。 当我删除该行(" THAT LINE"在代码段中) - 它可以工作。当我添加这个或任何其他代码,甚至一些变量声明时 - 它给了我相同的异常。

此错误仅出现在Xcode中,在它工作的终端中:

site.pp

1 个答案:

答案 0 :(得分:0)

似乎类似于数组元素问题。

尝试使用[NSLayoutAttribute.leading, NSLayoutAttribute.trailing, NSLayoutAttribute.bottom, NSLayoutAttribute.top]代替[.leading,.trailing,.bottom,.top]

constant: CGFloat(c)代替constant: c