在Swift中访问数组内部结构中的字符串

时间:2015-03-15 13:10:03

标签: arrays swift struct

我发布了这个问题https://stackoverflow.com/questions/29056111/converting-a-string-back-to-an-array-in-swift,但下面通常是我尝试做的事情。结果不匹配:

var str = "Hello, playground"

struct myStruct {
    var name: String? = ""
}

let myArray: [myStruct] = [myStruct(name: "Gary")]

var userName = "Gary"

let instanceofStruct = myStruct()

if userName == instanceofStruct.name {
    println("match")
}
else {
    println("no match")
}

1 个答案:

答案 0 :(得分:0)

使用'=='代替'==='来比较Strings

来自The Swift Programming Language

  

请注意“与...相同”(由三个等号表示,或===)   并不等同于“等于”(由两个等于​​表示)   标志,或==):

     

•“与...相同”表示类类型的两个常量或变量   指的是完全相同的类实例。

     

•“等于”表示两个实例被视为“相等”或   “等价”的价值,对于某些适当的“平等”含义,如   由类型的设计师定义。

请注意,StringStruct,是值类型,而不是类。


问题更新后:

var userName = "Gary"

let instanceofStruct = myStruct() // instanceofStruct.name is "" here

if userName == instanceofStruct.name { // "Gary" != ""
    println("match")
}
else {
    println("no match")
}

您可能想要做的是:

let myArray: [myStruct] = [myStruct(name: "Gary")]

var userName = "Gary"

var structireWithNameGary: myStruct? = nil
for structure in myArray {
    if userName == structure.name {
        println("match")
        structireWithNameGary = structure
        break
    }
}

if structireWithNameGary != nil {
    println("found a stucture with name Gary in myArray")
} else {
    println("couldn't find a stucture with name Gary in myArray")
}