本文介绍了无法推断Swift 3 NSCache通用参数'KeyType'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在Swift 2.x中有效:

This code worked in Swift 2.x:

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

Swift 3 中会导致编译错误:

Generic parameter 'KeyType' could not be inferred

为什么会这样,我应该如何重构它(迁移工具未进行修改)?

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

推荐答案

  • 在第一个Swift 3 beta中,NSCache已更改为Cache.
  • 在最新的Beta(目前为5个)中,它已还原为NSCache.
    • In the first Swift 3 betas NSCache has been changed to Cache.
    • In the latest betas (currently 5) it has been reverted to NSCache.
    • 无论如何,NSCache现在是通用名称.

      Anyway NSCache is now a generic.

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

      所以最通用的语法是

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

      不需要显式的init()(甚至在Swift 2中也不需要)

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

      这篇关于无法推断Swift 3 NSCache通用参数'KeyType'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:39