Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift store array with UserDefaults

Tags:

arrays

ios

swift

So I'm trying to store some posts id's basically so I can know what the user has read so I can show a "seen" button.

var actual_data = UserDefaults.standard.array(forKey: "seen_posts")
UserDefaults.standard.setValue(actual_data?.insert(321, at: 0), forKey: "seen_posts")

I have tried this, but it doesn't seem to work, Ambiguous use of 'insert(_:at:)'

Updated

var actual_data = UserDefaults.standard.array(forKey: "seen_posts")
UserDefaults.standard.set(actual_data?.append(["miodrag"]), forKey: "seen_posts")
like image 797
Uffo Avatar asked Mar 10 '26 15:03

Uffo


1 Answers

The reason of the error is that the compiler cannot infer the type of the array.

Spend an extra line to read, change and write the data, for example:

let defaults = UserDefaults.standard
var seenPosts : [Int]
if let actual = defaults.array(forKey: "seen_posts") as? [Int] {
     seenPosts = actual
} else {
     seenPosts = [Int]() 
}
seenPosts.insert(321, at: 0)
defaults.set(seenPosts, forKey: "seen_posts")

or if the default key seen_posts is registered – as recommended – simpler

let defaults = UserDefaults.standard
var seenPosts = defaults.array(forKey: "seen_posts") as! [Int]
seenPosts.insert(321, at: 0)
defaults.set(seenPosts, forKey: "seen_posts")
like image 151
vadian Avatar answered Mar 13 '26 09:03

vadian