Mohammed Nabil
Mohammed Nabil

Reputation: 157

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

Upvotes: 0

Views: 673

Answers (1)

Bartosz Jarosz
Bartosz Jarosz

Reputation: 310

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])
}

Upvotes: 1

Related Questions