搜尋

首頁  >  問答  >  主體

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

。 。 。 。請問大神這是什麼原因呢?

伊谢尔伦伊谢尔伦2856 天前602

全部回覆(1)我來回復

  • 阿神

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

    個人理解:

    1. 為社麼不直接用swift中的dictionary,而要用NSMutableDictionary

    2. 如果用了oc中的類,那麼對於key來說就要實現NSCopying協議,也就是不能用swift的String類型而要用NSString

    回覆
    0
  • 取消回覆