简体   繁体   English

Swift Array闭合扩展名引发错误

[英]Swift Array closure extension raises an error

I have an extension on Array instances for looping over with indices in mind like so: 我在Array实例上有一个扩展,可以像这样循环遍历索引:

extension Array {
    func fun (_ iterator: (Int, Element) -> Void) -> Void {
        for (key,value) in self.enumerated() {
            iterator(key,value)
        }
    }
}

Now, I want to call it : 现在,我想称它为:

[.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
}

However that raises an error: Type of expression is ambiguous without more context. 但是,这会引发一个错误:表达式类型不明确,没有更多上下文。 When I remove the line ("THAT LINE" in the snippet) - it works. 当我删除该行(代码段中的“该行”)时,它会起作用。 When I add this or any other code, even some variable declarations - it gives me the same exception. 当我添加此代码或任何其他代码时,甚至添加了一些变量声明-它给了我相同的异常。

This error appears ONLY in Xcode, in terminal it works: 此错误仅出现在Xcode中,在终端中起作用:

🐄  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

Seems like type of array elements issue. 似乎是数组元素类型的问题。

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

And constant: CGFloat(c) instead of constant: c . 并且constant: CGFloat(c)而不是constant: c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM