You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法从字典中获取非字符串类型值的技术求助

Fixing Int Cast Failures from Your Dictionary

Hey there, let's break down why those non-string values like departmentID and smat_Leader1ID are always returning 0 when you try to cast them to Int.

The Root Cause

Chances are, those numeric values in your dictionary aren't stored as Swift native Int types—they're probably NSNumber instances. This is super common when dealing with dictionaries that come from Objective-C APIs (like JSON parsers or legacy code). When you try to cast an NSNumber directly to Int with as? Int, it fails because the types don't match, so you hit the nil coalescing operator (?? 0) and get your default value.

Quick Fixes

Here are a couple of reliable ways to get the correct integer values:

1. Cast to NSNumber first, then extract the Int value

This is the simplest approach for most cases:

// For departmentID
var departmentID = (self.dictionary["departmentID"] as? NSNumber)?.intValue ?? 0

// For smat_Leader1ID
var smatLeader1ID = (self.dictionary["smat_Leader1ID"] as? NSNumber)?.intValue ?? 0

NSNumber has a handy intValue property that safely converts it to a Swift Int. If the value is nil or can't be converted, you still get your default 0.

2. Use Pattern Matching for Robustness

If you want to handle more edge cases (like if some values might actually be Int or even string-formatted numbers), use a switch statement with pattern matching:

func getIntValue(from key: String) -> Int {
    guard let value = self.dictionary[key] else { return 0 }
    
    switch value {
    case let intValue as Int:
        return intValue
    case let nsNum as NSNumber:
        return nsNum.intValue
    case let stringValue as String:
        // Bonus: handle if the number is stored as a string
        return Int(stringValue) ?? 0
    default:
        return 0
    }
}

// Usage
var departmentID = getIntValue(from: "departmentID")
var smatLeader1ID = getIntValue(from: "smat_Leader1ID")

This covers more scenarios and makes your code more resilient to unexpected value types.

Verify the Actual Type

If you're still unsure what type is stored in the dictionary, add a print statement to check:

print(type(of: self.dictionary["departmentID"]!))

This will tell you exactly if it's NSNumber, Int, or something else—helping you tailor your casting logic even better.

内容的提问来源于stack exchange,提问作者user987654

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:47:54