我有一个不断更新的数组。我如何检查所有内容是否相同?对于前。
var Array:[String] = ["1", "2", "1", "1", "1", "2"]
if //all array contents are equal to 1 {
println("Array = 1")
}
感谢
答案 0 :(得分:5)
更好的解决方案是使用集合
//var set = NSSet(array: [2,3,3,2,1])
var set = NSSet(array: [1,1,1,1,1])
if set.count == 1 {
println("All the same")
}
答案 1 :(得分:0)
这只是一个例子,只是为了说明一种方法:
var myArray = ["1","1","2","1"]
func checkOut(array: [String]) -> Bool {
var number = 0
for index in 0..<array.count {
if array[index] == "1" {
number++
}
}
if number == array.count {
return true }
else {
return false }
}
checkOut(myArray)
答案 2 :(得分:0)
//let array = ["1", "2", "1", "1", "1", "2"]
let array = ["1", "1", "1", "1", "1", "1"]
//just check if all elements *equal*
let set = NSSet(array: array)
if set.count == 1 {
println("all elements equal")
}
//just check if all elements are equal to X
let set = NSSet(array: array)
if(set.count == 1) {
let myObj = set.anyObject() as String!
let equalTo = "1"
if myObj == equalTo {
println("all elements equal 1")
}
}