1

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.
import UIKit

class DreamViewController: UIViewController {

    @IBOutlet var liketext: UIButton!
    @IBOutlet var QuoteImage: UIImageView!
    @IBOutlet weak var DreamLabel: UILabel!
    var counter = 1

    var factIndex = 0

    let dreamFact = Dream()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        DreamLabel.text = dreamFact.dreamArray[factIndex]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func LeftSwipe() {
        factIndex--
        var number = dreamFact.dreamArray.count - 1
        if (factIndex < 0){
            self.factIndex = number

        }
        DreamLabel.text = dreamFact.dreamArray[factIndex]
        if counter == 1 {

            counter = 36

        } else {

            self.counter--

        }

        QuoteImage.image = UIImage(named: "frame\(counter).jpg")

    }
@IBAction func RightSwipe() {
        factIndex++
        if factIndex >= dreamFact.dreamArray.count {
            self.factIndex = 0
        }
        DreamLabel.text = dreamFact.dreamArray[factIndex]
    if counter == 36 {

    counter = 1

    } else {

    self.counter++

    }
    QuoteImage.image = UIImage(named: "frame\(counter).jpg")
}
    struct Constants {
        static let defaults = NSUserDefaults.standardUserDefaults()
        static let fqKey = "FavoriteQuotes"
        static let like = "Like"
        static let unlike = "Unlike"
    }
    class DreamViewController {




        var favouriteQuotesArray = Constants.defaults.objectForKey(Constants.fqKey) as? [String] ?? [String]() {
            didSet {
                Constants.defaults.setObject(favouriteQuotesArray, forKey: Constants.fqKey)
            }



    }

         @IBOutlet weak var likeButton: UIButton! {

            didSet {
                let favourite = dreamArray[factIndex]
                if let foundIndex = find(favouriteQuotesArray, favourite) {
                    likeButton.setTitle(Constants.unlike, forState: .Normal)
                }
                else {
                    likeButton.setTitle(Constants.like, forState: .Normal)
                }
            }



        }

        @IBAction func likeButtonClicked(sender: UIButton) {
        }

        }
}

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? Update:

 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 likeButton() {

        if contains(favouriteQuotesArray, dreamFact.dreamArray[factIndex]) {
        liketext.setTitle("Unlike", forState: UIControlState.Normal)
        }
9
  • first find the index of the element that you want to remove from the array ...and then call method arr.removeAtIndex(index)..this will work Commented Aug 1, 2015 at 3:51
  • @anish parajuli in reference to my NSUserdefaults statement? Commented Aug 1, 2015 at 3:51
  • what type is this currentQuote ??? Commented Aug 1, 2015 at 3:52
  • @anish parajuli a string array I believe Commented Aug 1, 2015 at 4:01
  • its string..so find the string in the array on the button click and do as... if let temp = find(favouriteQuotesArray,"value"){favouriteQuotesArray.removeAtIndex(temp)} and then again save it into userDefaults Commented Aug 1, 2015 at 4:07

3 Answers 3

3

Do it this way; some cleaner coding techniques to cut through the rubble included.

The declaration of favouriteQuotesArray is a gold star one liner. Got it all?

import UIKit

struct Constants {
    static let defaults = NSUserDefaults.standardUserDefaults()
    static let fqKey = "FavoriteQuotes"
    static let like = "Like"
    static let unlike = "Unlike"
}

class Page2ViewController: UIViewController {
    var dreamArray = [String]() // place holder so class compiles
    var factIndex = 0           // place holder so class compiles

    var favouriteQuotesArray = Constants.defaults.objectForKey(Constants.fqKey) as? [String] ?? [String]() {
        didSet {
            Constants.defaults.setObject(favouriteQuotesArray, forKey: Constants.fqKey)
        }
    }

    @IBOutlet weak var likeButton: UIButton! {
        didSet {
            let favourite = dreamArray[factIndex]
            if let foundIndex = find(favouriteQuotesArray, favourite) {
                likeButton.setTitle(Constants.unlike, forState: .Normal)
            }
            else {
                likeButton.setTitle(Constants.like, forState: .Normal)
            }
        }
    }

    @IBAction func likeButtonClicked(sender: UIButton) {
        let favourite = dreamArray[factIndex]
        if let foundIndex = find(favouriteQuotesArray, favourite) {
            sender.setTitle(Constants.like, forState: .Normal)
            favouriteQuotesArray.removeAtIndex(foundIndex)
        }
        else {
            sender.setTitle(Constants.unlike, forState: .Normal)
            favouriteQuotesArray.append(favourite)
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

do i add this to my view controller?
It is a complete View Controller. You should be able to adapt it to yours by filling in the gaps. Try to understand the whole code to see what it replaces in yours.
If that's too confusing to do, modify your question with your entire ViewController.swift file. I'm finding this happens frequently with Xcode / UI problems. Never enough context.
can you send me a chat request I believe this question is better resolved there?
Great detailed answer but it does have some issues while attaching to my code, hope we can get in contact to make things easier for me and you. Gave an upvote but needs further communication for it to be an accepted answer
|
1

Try this:

let currentQuote = dreamFact.dreamArray[factIndex]
if find(favouriteQuotesArray!, currentQuote) != nil {
    //Do something
}

3 Comments

@NewBeginnings sorry, I didn't quite understand where you needed to put the check. Could you give a little more context?
I need to see if a string existed in an array or not.
Ok. I updated my answer to reflect that. If this doesn't work, replace the currentQuote variable with the string you need to find. Good luck with your app :)
1

The better and quick way to find out an element in an array is:

if contains(yourFavArray, stringStatement){
  //Contains you can write your logic
}

Change your favouriteArray as below:

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

Edited:

 if let foundIndex = find(favouriteQuotesArray, dreamFact.dreamArray[factIndex]) {
     sender.setTitle(Constants.like, forState: .Normal)
     favouriteQuotesArray.removeAtIndex(foundIndex)
 }

8 Comments

Cannot find an overload for 'contains' that accepts an argument list of type '([String]?, String)' on line if contains(favouriteQuotesArray,dreamFact.dreamArray[factIndex])
Cannot assign to the result of this expression
I see if contains(favouriteQuotesArray, dreamFact.dreamArray[factIndex]) with error. Cannot find an overload for 'contains' that accepts an argument list of type '([String]?, String)'
removes the error I mentioned tho but it generates Binary operator '==' cannot be applied to operands of type '[String]' and 'nil' here func makeQuoteFavourite() { if favouriteQuotesArray == nil { favouriteQuotesArray = [] }
@NewBeginnings Can you please update your code with the latest changes?
|

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.