我正在开发一个快速的应用程序,在某个时候我有一个类似于以下代码:
import UIKit
class ViewController: UIViewController {
private var a: UIImageView!
private var b: UIImageView!
private var c: UILabel!
private var d: UILabel!
private var e: UILabel!
private var f: UILabel!
private var g: UIView!
private var h: UIView!
private var i: UIView!
private var j: UIView!
private var k: UIImageView!
private var l: UIView!
private var m: UIView!
private var n: UIView!
private var o: UIView!
private var p: UIScrollView!
private var q: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let viewBindingsDict = ["a" : a,
"b" : b,
"c" : c,
"d" : d,
"e" : e,
"f" : f,
"g" : g,
"h" : h,
"i" : i,
"j" : j,
"k" : k,
"l" : l,
"m" : m,
"n" : n,
"o" : o,
"p" : p]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
由于某种原因,当我添加此代码时,xcode卡住了,我无法做其他任何事情。
打开活动监视器,它显示sourcekitservice和使用100%以上CPU的swift。
我已经使用上面的代码创建了这个示例项目:https
:
//dl.dropboxusercontent.com/u/1393279/aaaaaaa.zip
我已经尝试过清理派生数据,重新安装Xcode,重新启动,等待几分钟等等。这根本不起作用。
几次类似的事情发生在我身上,我通过 将长语句分成多行来解决 。
我在操场上测试了您的代码,立即注意到SourceKitService进程占用了100%的CPU。
在您的代码中,我看到的最长的语句是字典初始化,因此第一种方法是使其可变并以每行较少的项目数进行初始化。
Swift没有+=
为字典提供运算符,因此我们首先需要一个
func +=<K, V> (inout left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
return left
}
使用工具集中的字典,可以按以下方式初始化字典:
var viewBindingsDict = ["a" : a, "b" : b, "c" : c, "d" : d, "e" : e]
viewBindingsDict += ["f" : f, "g" : g, "h" : h, "i" : i, "j" : j]
viewBindingsDict += ["k" : k, "l" : l, "m" : m, "n" : n, "o" : o]
viewBindingsDict += ["p" : p]
每行最多选择5个项目。
但是在您的代码中,您将字典声明为不可变的-swift在声明之后不提供任何语句来初始化不可变的-幸运的是,我们可以使用闭包来实现这一点:
let viewBindingsDict = { () -> [String:UIView] in
var bindings = ["a" : self.a, "b" : self.b, "c" : self.c, "d" : self.d, "e": self.e]
bindings += ["f": self.f, "g" : self.g, "h" : self.h, "i" : self.i, "j" : self.j]
bindings += ["k" : self.k, "l" : self.l, "m" : self.m, "n" : self.n, "o" : self.o]
bindings += ["p": self.p]
return bindings
}()