Search code examples
arraysswiftstringuserdefaults

How to print single element of string array in swift


I am a beginner in swift, how do i print the single element after saving string array in UserDefaults. Below is the swift code

let userDefaults = UserDefaults.standard
let array = [requestModel.latitude, requestModel.longitude] //"24.7256", "46.67820"
userDefaults.set(array, forKey: "myKey")
let strings = userDefaults.object(forKey: "myKey")
print(strings[0]) // expecting to print the latitude value

Solution

  • when you read from userdefaults compilator doesn't know type of object so you need to cast it

    let userDefaults = UserDefaults.standard
    let array = [location.latitude, location.longitude] //"24.7256", "46.67820"
    userDefaults.set(array, forKey: "myKey")
    if let strings = userDefaults.object(forKey: "myKey") as? [Double] {
      print(strings[0])
    }