Array element checking in swift

后端 未结 3 620
迷失自我
迷失自我 2021-01-15 18:38

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

相关标签:
3条回答
  • 2021-01-15 18:58

    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)
     }
    
    0 讨论(0)
  • 2021-01-15 19:17

    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)
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-15 19:21

    Try this:

    let currentQuote = dreamFact.dreamArray[factIndex]
    if find(favouriteQuotesArray!, currentQuote) != nil {
        //Do something
    }
    
    0 讨论(0)
提交回复
热议问题