Reputation: 9787
How to save the text of 2 textfields in an array?
This is what I tried. I use println to check if the values are in the array. But it seems it doesn't work.
Can anyone explain it and please, explain each step. Thank you
1- I create a swift file: novaClass.swift. I create an struct inside
struct novaClass {
var img : String
var text : String
}
2- ViewController.swift Declare an array
var nouArray = [novaClass]()
3- save the text field in the array
@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
}
Upvotes: 1
Views: 3076
Reputation: 9321
That's the expected behaviour in Swift. Swift objects don't have a description property by default, so println
defaults to printing the class name.
Your class can adopt the Printable
protocol (which have been renamed to CustomStringConvertible
in Swift 2) to provide more detailed printouts:
struct novaClass: Printable {
var img : String
var text : String
var description: String {
get {
return "{img: \(img), text: \(text)}"
}
}
}
Now try it:
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}]"
Upvotes: 2
Reputation: 2324
You should check it by
println(nouArray[0].text)
println(nouArray[0].img)
Printing array as object will print its title only
Upvotes: 1