How to transfer data added to swift 2 global array

Before I start, I just wanted to say that I am very new to application development in general, I have been doing this for only a month, so do not be shy, as far as possible, haha.

Okay, that's why I'm working on a quote application, so I created an array that I can access from any controller. This will contain the “liked” quotes that are added from another view.

Here is my global "liked Array". It is in its own fast file.

import Foundation

struct Globals {

    static var likedArray: [String] = ["Touch 'Liked' To Continue..."]

}

Quotes are added to your favorite Array by this method, from another view controller file.

@IBAction func likedbuttonPressed(sender: AnyObject) {

    Globals.likedArray.append(quoteLabel.text)
}

And the “liked” quotes are shown in another view using this method

// Like button method to move forward in array
@IBAction func likedButtonTouched(sender: AnyObject) {

    self.favouritesLabel.fadeOut(completion: {
        (finished: Bool) -> Void in

    self.currentlikedArrayIndex++
    if self.currentlikedArrayIndex < Globals.likedArray.count {
        self.favouritesLabel.text = Globals.likedArray[self.currentlikedArrayIndex]
    } else {
        self.currentlikedArrayIndex--
    }

     self.favouritesLabel.fadeIn()

    })  
}

, , , .

, : ? , . .

+4
1

, , NSUserDefaults, , ,

jist :

//for writing to storage
let defaults = NSUserDefaults.standardUserDefaults()
let array = ["Hello", "World"]
defaults.setObject(array, forKey: "SavedArray")

//for reading
let array = defaults.objectForKey("SavedArray") as? [String] ?? [String]()

, setter , , , NSUserDefaults, NSUserDefaults

update: ( )

struct Globals {

    static var likedArray: [String] = ["Touch 'Liked' To Continue..."]

    func addLikedString(likedString: String) {

        self.likedArray.append(likedString)
        NSUserDefaults.standardUserDefaults().setObject(self.likedArray, forKey: "SavedArray")
    }

    func getLikedStringAtIndex(index:Int) -> Int {
        return self.likedArray[index] 
    }

}

//inside your app delegate, or somewhere appropriate, to load the array when the app starts

Globals.likedArray = NSUserDefaults.standardUserDefaults().objectForKey("SavedArray") as? [String] ?? [String]()
+2
source

Source: https://habr.com/ru/post/1629086/


All Articles