Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 NSCache Generic parameter 'KeyType' could not be inferred

Tags:

ios

swift

swift3

This code worked in Swift 2.x:

/// An internal in-memory cache
private var dataCache = NSCache.init()

In Swift 3 it causes compilation error:

Generic parameter 'KeyType' could not be inferred

Why is that so and how should I refactor this (Migration tool did not pick this up)?

like image 539
Lukasz Avatar asked Aug 10 '16 15:08

Lukasz


1 Answers

  • In the first Swift 3 betas NSCache has been changed to Cache.
  • In the latest betas (currently 5) it has been reverted to NSCache.

Anyway NSCache is now a generic.

public class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject { ...

so the most general syntax is

private var dataCache = NSCache<AnyObject, AnyObject>()

The explicit init() is not needed (not even in Swift 2)

like image 190
vadian Avatar answered Oct 21 '22 04:10

vadian