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 ar
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)
}
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)
}
}
}
Try this:
let currentQuote = dreamFact.dreamArray[factIndex]
if find(favouriteQuotesArray!, currentQuote) != nil {
//Do something
}