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

一曲冷凌霜 提交于 2020-01-01 04:03:11

问题


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



来源:https://stackoverflow.com/questions/38877229/swift-3-nscache-generic-parameter-keytype-could-not-be-inferred

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!