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
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)
}
}
}