swift - 发现可选值为 nil?

标签 swift

我就是想不通:

print(module)
print(Globals.sharedInstance.dataModuleName)
let kind:NSString = module[Globals.sharedInstance.dataModuleName] as! NSString

将打印这个,然后由于一个奇怪的原因而崩溃:

( //dic print
        {
        meta = no;
        module = IN;
        subject = LT;
        variable = A2;
    }
)
module    // print the right field we are looking for inside the dictionary .

fatal error: unexpectedly found nil while unwrapping an Optional value

但是您可以看到该模块是一个有效的字典,也是 dataModuleName

let kind 行崩溃。有什么问题吗?

最佳答案

你的模块是 DictionaryArray 而不是直接 Dictionary,所以你需要先访问它的第一个对象然后是模块键,就像这样

let kind:String = module[0][Globals.sharedInstance.dataModuleName] as! String

注意: 一个问题,在 swift 中使用 String 而不是 NSString

您还可以使用 if letguard 进行初始化以避免崩溃。

关于swift - 发现可选值为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932192/

相关文章:

ios - NSError 为 nil 但进入 not nil 状态

swift - SKMutableTexture 中的透明像素

ios - 如何使用Out @State 变量更新 SwiftUIView?和段错误问题

swift - UIImageView 的移动和跳跃动画 : Swift 4

ios - 截图时没有相机 View ,只有白色背景

ios - 在图像上运行 CIFilter 会在上方和下方产生不需要的偏移

iOS 应用程序在 macOS Finder 中不可见

swift - 如何快速从结构中过滤

ios - Realm swift : Update an object inside a closure

xcode - 当动画从两个容器子 UIViews 过渡时,UIViews 在第三次过渡后为空,这是怎么回事?