Lukasz Lukasz - 3 months ago 857
Swift Question

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

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)?

Answer
  • 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)