>  Q&A  >  본문

swift - ubuntu中遇到NSMutableDictionary错误

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

import Foundation

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

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

伊谢尔伦伊谢尔伦2734일 전555

모든 응답(1)나는 대답할 것이다

  • 阿神

    阿神2017-04-24 09:13:33

    개인적 이해:

    1. Swift에서 사전을 직접 사용하지 않고 NSMutableDictionary를 사용하는 이유

    2. oc에서 클래스를 사용하는 경우 키에 대해 NSCopying 프로토콜을 구현해야 합니다. 즉, Swift String 유형을 사용할 수 없지만 NSString을 사용합니다

    회신하다
    0
  • 취소회신하다