Save a tuple in NSUserDefaults

后端 未结 5 1652
梦毁少年i
梦毁少年i 2021-01-12 13:14

I\'m using a tuple to store something like this.

var accessLavels: (hasInventoryAccess: Bool, hasPayrolAccess: Bool)
accessLavels = (hasInventoryAccess: true         


        
5条回答
  •  情歌与酒
    2021-01-12 13:51

    I had a tuple with 3 values.

    The following code was used for saving the tuple. Basically, I created a string from tuple (with components separated by a comma).

    let defaultsLoad = NSUserDefaults.standardUserDefaults()
    if appSingleton.runwayDestShared != nil
    {
       // Creating a String from the tuple
       let runwayDestString = appSingleton.runwayDestShared!.0 + "," + appSingleton.runwayDestShared!.1  + "," + appSingleton.runwayDestShared!.2
       defaultsLoad.setObject(runwayDestString, forKey: "RunwayDest")
    }
    

    To retrieve the tuple, I retrieved the string, broke it into array and used the array to re-create a tuple.

    let runwayDestString = defaultsLoad.stringForKey("RunwayDest")
    if let runwayDestString = runwayDestString
    {
        let runwayDestArray = runwayDestString.componentsSeparatedByString(",")
        appSingleton.runwayDestShared = (runwayDestArray[0],runwayDestArray[1],runwayDestArray[2])
    }
    

提交回复
热议问题