![](/img/trans.png)
[英]While loop with double conditional and || logical operator in Swift
[英]Swift 2 Logical AND(&) Operator
我是編程的新手,正在嘗試找到一種更簡單的方法來執行此操作:
if state[0] != 0 && state[1] != 0 && state[2] != 0 && state[3] != 0 && state[4] != 0 && state[5] != 0 && state[6] != 0 && state[7] != 0 && state[8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
我嘗試了下面的代碼,但它的反應像是OR或AND。
if state[0&1&2&3&4&5&6&7&8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
謝謝你的幫助!
假設您的目的是檢查所有數組元素是否均不為零,則最簡單的方法是
if !state.contains(0) { ... }
您的密碼
if state[0&1&2&3&4&5&6&7&8] != 0 { ... }
不能按預期工作,因為此處首先計算按位與AND 0&1&2&3&4&5&6&7&8
(結果為零),因此等於
if state[0] != 0 { ... }
let state = [0,1,2,0,4,5,6,7]
if state.filter{$0 != 0}.count > 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
試試這個
Array
的一般情況 短版
let indices = [4,2,9,6,5,3,8,0] if !indices.contains({ state[$0] == 0 }) { // ... }
第二個版本僅顯示Swift的可能性:
if !indices.lazy.map{ state[$0] }.contains(0) { // ... }
之所以使用lazy
是因為map
否則將對所有索引應用閉包,而lazy
平均僅將其應用於元素的一半( contains
確定閉包的執行次數)。
注意 :少量索引可能不會改善性能。 當然,第一個版本的速度更快(甚至略有提高)。
只需使用上面的方法
let indices = 5...9
或者直接對Array
的子序列ArraySlice
。
旁注 :盡管ArraySlice
( Array[Range<Int>]
返回類型)似乎是一個值類型,但在內部它是一個引用類型(如Array
),僅在突變時才復制自身。 另外, ArraySlice
只是數組的視圖(只要它們都不發生突變)。 因此,它可能比第一種方法更快。
if !state[24...42].contains(0) { // ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.