vendredi 31 juillet 2015

Array element checking in swift

Currently implementing a favourite function to my application which is based on quotes. I would like to perform a check for if the user has already saved an element to an array. If they have, I would change a favour button to unfavour button.

   var favouriteQuotesArray: [String]? = NSUserDefaults.standardUserDefaults().objectForKey("thekey") as? [String]

    func makeQuoteFavourite() {
        if favouriteQuotesArray == nil {
            favouriteQuotesArray = []
        }
        let currentQuote = dreamFact.dreamArray[factIndex]
        favouriteQuotesArray!.append(currentQuote)
        NSUserDefaults.standardUserDefaults().setObject(favouriteQuotesArray!, forKey: "thekey")
    }

    @IBAction func favour(sender: AnyObject) {

        if liketext.currentTitle == "Like"{

            liketext.setTitle("Unlike", forState: UIControlState.Normal)

     makeQuoteFavourite()


        } else if liketext.currentTitle == "Unlike" {

            liketext.setTitle("Like", forState: UIControlState.Normal)


        }

See the issue at currenttitle, the dependency on upon the text which is unreliable because if the user reopens the app, the element would still be saved instead of starting out with the default unlike. If the element is found in the array. How would I perform a search inside my favouriteQuotesArray if the element exists like:

if elementfound statement {

button.settitle(unlike)
removearrayatindex statement.

} else {
button.settitle(like)
makeQuoteFavourite()
}

How would the array checking statement look like? P.S If you can please give tips on building the delete class?

Aucun commentaire:

Enregistrer un commentaire