swift - ubuntu中遇到NSMutableDictionary错误

浏览:42日期:2022-08-17

问题描述

我尝试在linux(ubuntu16.04,swift-3.0.1-release,clang-3.8.0)中运行swift代码如下:

import Foundationlet a = NSMutableDictionary()a.setObject('value',forKey:'key' as NSCopying)

在a中写入一个键值对,但是遇到了一个编译错误:

error: repl.swift:4:30: error: cannot convert value of type ’NSCopying’ to expected argument type ’AnyHashable’a.setObject('a',forKey:'xxx' as! NSCopying) ~~~~~~^~~~~~~~~~~~~ as! AnyHashable

当我将as NSCopying去掉或换成AnyHashable时编译通过,运行又报错了:

Could not cast value of type ’Swift.AnyHashable’ (0x7ffff7dcc508) to ’Foundation.NSObject’ (0x7ffff46874a0).Execution interrupted. Enter code to recover and continue.Enter LLDB commands to investigate (type :help for assistance.)

。。。。请问大神这是什么原因呢?

问题解答

回答1:

个人理解:

为社么不直接用swift中的dictionary,而要用NSMutableDictionary

如果用了oc中的类,那么对于key来说就要实现NSCopying协议,也就是不能用swift的String类型而要用NSString

相关文章: