arrays - Swift:将文本字段保存在数组中

标签 arrays swift class

如何将 2 个文本字段的文本保存在一个数组中?

这是我试过的。我使用 println 检查值是否在数组中。但它似乎不起作用。

谁能解释一下,请解释每一步。谢谢

1- 我创建了一个 swift 文件:novaClass.swift。我在里面创建了一个结构

struct novaClass {
    var img : String
    var text : String
}

2- ViewController.swift 声明一个数组

    var nouArray = [novaClass]()

3-将文本字段保存在数组中

@IBAction func save(sender: AnyObject) {

    //I put the text of 2 text fields in the array
    var nouText = novaClass(img: textField1.text, text: textField2.text) 
    nouArray.append(nouText)

    //I check the array
    println(nouArray) // this gives "[_.novaClass]" I do not understand

}

最佳答案

这是 Swift 中的预期行为。 Swift 对象默认没有 description 属性,所以 println 默认打印类名。

您的类可以采用 Printable 协议(protocol)(在 Swift 2 中已重命名为 CustomStringConvertible)来提供更详细的打印输出:

struct novaClass: Printable {

    var img : String
    var text : String

    var description: String {
        get {
            return "{img: \(img), text: \(text)}"
        }
    }
}

现在试试看:

var array = [novaClass]()
let x = novaClass(img: "foo", text: "bar")
let y = novaClass(img: "foo2", text: "bar2")
array.append(x)
array.append(y)
println(array) // will print: "[{img: foo, text: bar},{img: foo2, text: bar2}]"

关于arrays - Swift:将文本字段保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32119371/

相关文章:

c# - 类变量是 UML 聚合吗?

javascript - Mootools 类 protected 处理程序?

arrays - 下标超出范围 VBA Excel 数组

java - 给定一个未排序的数组,在 O(n) 时间内找到 A[j] - A[i] 的最大值,其中 j>i..

c - sizeof(&a[0]) 对于 int 数组 'a' 意味着什么?

javascript - 使用特定数字的最后一个访问 JavaScript 数组中的位置

ios - 在 UItableView 单元格中快速播放视频

ios - 编码新手,正在工作书中的一个示例,该示例是为 xcode 6.2 编写的,我有最新版本。

c++ - 为什么 std::tie 不能与 const 类方法一起使用?

ios - 如何手动将下一个信号发送到 RxSwift 中的可观察对象?