2

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")
vadian
  • 274,689
  • 30
  • 353
  • 361
Uffo
  • 9,628
  • 24
  • 90
  • 154

1 Answers1

2

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")
vadian
  • 274,689
  • 30
  • 353
  • 361
  • let array = defaults.object(forKey:"seen_posts") as? [String] ?? [String]() debugPrint(array) So I have added this to test it, and I get an empty array – Uffo Jan 21 '17 at 19:30
  • According to your (first) code the array is `[Int]`. – vadian Jan 21 '17 at 19:31