问题
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)?
回答1:
- In the first Swift 3 betas
NSCachehas been changed toCache. - 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)
来源:https://stackoverflow.com/questions/38877229/swift-3-nscache-generic-parameter-keytype-could-not-be-inferred