AJ Z.
AJ Z.

Reputation: 495

How to cache array of Doubles in Swift

The following code

let cache = NSCache<NSString, [Double]>()

gives me the error:

'NSCache' requires that '[Double]' be a class type

How can I cache an array of Doubles using String as the key?

Upvotes: 3

Views: 3165

Answers (3)

Fernando Mazzon
Fernando Mazzon

Reputation: 3591

As mentioned by others, NSCache is an objC type and will only work with NSObject subclasses. You can use type bridging into NSArray for this.

let cache = NSCache<NSString, NSArray>()
let doubleArray: [Double] = [2.0, 3.0, 4.0]
cache.setObject(doubleArray as NSArray, forKey: "key")

// ...

if let doubleArray = cache.object(forKey: "key") as? [Double] {
    // Got my array back
}

Upvotes: 6

AjinkyaSharma
AjinkyaSharma

Reputation: 1979

Here is an example of how you can to do

let cache = NSCache<NSString,NSArray>()

cache.setObject([NSNumber.init(value: 2.0),NSNumber.init(value: 3.0)], forKey: "value1")

print(cache.object(forKey: "value1")!)

Upvotes: 2

matt
matt

Reputation: 535925

NSCache is in the Cocoa Objective-C world so you have to play by Cocoa Objective-C rules. You could declare cache as an NSCache<NSString, NSArray>, for example.

Upvotes: 3

Related Questions