在尝试此代码时,我遇到了each()方法的奇怪行为:
def xml = new XmlSlurper().parseText('''
<list>
<item a="1">a</item>
<item a="2">b</item>
<item a="1">c</item>
</list>
''')
def i = 0
xml.'**'.findAll { it.@a=='1' }.each {
println "hi" + i
}
结果只有hi0
,但我希望hi0hi1
。这种行为是错误还是每种语言设计?第二个结果只有在我写println "hi" + i++
而不是当前的闭包体时才提供,所以当每个项目的内容不同时......
答案 0 :(得分:5)
您的 @IBOutlet weak var WebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.redColor()
let alert = UIAlertView(title: "This App needs internet connection",
message: "If not connected now, please make sure your device connect to internet and restart it.",
delegate: nil,
cancelButtonTitle: "OK")
alert.show()
let URL = NSURL(string: "http://saloonjob.com/catering")
WebView.loadRequest(NSURLRequest(URL: URL!))
}
变量没有增加,因为没有任何东西可以告诉它增加。您的代码当前编写的方式,我希望输出为:
i
我认为你要找的是hi0
hi0
,它为闭包提供了两个参数 - 当前项和项的索引。您的代码将如下所示:
eachWithIndex
这导致输出:
def xml = new XmlSlurper().parseText('''
<list>
<item a="1">a</item>
<item a="2">b</item>
<item a="1">c</item>
</list>
''')
xml.'**'.findAll { it.@a=='1' }.eachWithIndex { item, i ->
println "hi" + i
}