簡體   English   中英

swift強制將objective-c int指定為Int32然后崩潰

[英]swift forcing objective-c int to be assigned as Int32 then crashing

我有一個已被聲明為的客觀c屬性

@property int xmBufferSize;

如果我做sharedExample.xmBufferSize = 1024它只是工作正常,但當我試圖從另一個變量設置該屬性的整數值

var getThat:Int = dict["bufferSize"]!.integerValue
sharedExample.xmBufferSize = getThat

它不能做到以上

Cannot assign a value of type 'Int' to a value of type 'Int32'

如果我強迫這個

sharedExample.xmBufferSize =dict["bufferSize"] as! Int32

它正在崩潰與錯誤

Could not cast value of type '__NSCFNumber' to 'Swift.Int32 '

編輯::::
Dict init,除了整數之外還有dict中的其他對象

var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]

dict的值是NSNumber ,無法NSNumber轉換或直接轉換為Int32 您可以先獲取NSNumber ,然后在其上調用intValue

if let bufferSize = dict["bufferSize"] as? NSNumber {
    sharedExample.xmlBufferSize = bufferSize.intValue
}

if let … as? 允許你驗證該值確實是一個NSNumber ,因為(如你所說)在dict可以有其他類型的對象。 then-branch只有在dict["bufferSize"]存在並且是NSNumber時才會執行。

(注意:如果intValue給出了錯誤的類型,你也可以嘗試integerValue ,或者根據需要轉換生成的整數 - CInt(bufferSize.integerValue) integerValue不會在不同的整數類型之間進行隱式轉換,所以你需要完全匹配。 )

您需要將NSNumber轉換為Int32。

sharedExample.xmBufferSize = dict["bufferSize"]!.intValue

使用類型轉換,而不是:

sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)

這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM