2017-08-30 1 views
-3

Voici mon code. Cela semble une erreur. Quelqu'un peut-il aider s'il vous plait.Comment puis-je enregistrer un tableau à UserDefaults, puis récupérer ce tableau et imprimer

class PopUpVC: UIViewController { 
    var myArray1 = ["1","2","3"] 
    var myArray2 = [String]() 
    UserDefaults.standard.set(myArray1, forKey: "array") 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    self.myArray2 = (UserDefaults.standard.string(forKey: "array") as? [String])! 
    print(self.myArray) 
    } 
+0

https://developer.apple.com/documentation/foundation/userdefaults/1416414-stringarray – Paulw11

Répondre

0
class PopUpVC: UIViewController { 
    var myArray1 = ["1","2","3"] 
    var myArray2 = [String]() 

override func viewDidLoad() { 
     super.viewDidLoad() 
     UserDefaults.standard.set(myArray1, forKey: "array") 
     self.myArray2 = UserDefaults.standard.stringArray(forKey: "array")! 
     print(self.myArray2) 
} 
+0

Cette réponse est tout simplement faux. Vous ne récupérez pas un tableau de chaînes en utilisant 'Userdefaults.string (forKey:)', vous le faites en utilisant 'array (forKey:)' ou 'object (forKey:)', puis le transtypez en '[String]'. Avez-vous déjà testé ce code? Il ne serait même pas compilé, puisque vous essayez de donner une valeur par défaut '[String]' à une variable 'String?'. –

+0

j'ai utilisé n'est pas 'String (forKey:)' J'ai utilisé est 'StringArray (forKey:)' –

+0

Ouais c'est correct, j'ai été accepté votre édition. –