1

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

}

2 Answers 2

2

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}]"
Sign up to request clarification or add additional context in comments.

2 Comments

I am very new in programming. I do not understand. You put that in the novaClass.swift, is that correct? and then how to check ?
@Nrc updated my answer with an example. Basically if you println your array, it will put there the result of description instead of _.novaClass
1

You should check it by

println(nouArray[0].text)
println(nouArray[0].img)

Printing array as object will print its title only

2 Comments

Ok. This prints the content of the text fields. But only the first values. Can I check if the array gets all the values entered before? (till the app. was open of course)
Ofcourse now it prints first pait of values because its index in 0. You can check what you need by nouArray.count maybe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.