ios - Swift iOS - 获取字典以接受零值

标签 ios arrays swift dictionary null

我有一个最多可以容纳 4 个值的数组。该数组将始终至少有 1 个值,但其他 3 个可能为零。我必须获取数组中的元素并将它们分配给类属性。

问题是,一旦我遍历数组,获取 nil 值,将它们分配给类属性,然后尝试将这些 nil 属性分配给我的字典,我就会崩溃。

我需要字典来接受带颜色的值并忽略 nil 值。所以我有两个问题。

  1. 数组中确实存在的颜色在 myDict 中显示为 nil
  2. 数组中的nil值是异常(exception)

我该如何解决这个问题?

代码:

class ColorClass{
    var colorOne:String?
    var colorTwo:String?
    var colorThree:String?
    var colorFour:String?
}

let colorClass = ColorClass()
var randColors: [String?] = []

//In this case I have 2 colors but sometimes randColors may have 1 color or 3 colors or 4 colors. It will always vary
randColors = ["purple","pink"]

for (index,element) in randColors.enumerate(){

    switch index {
    case 0:
        if let elZero = element{
            colorClass.colorOne = elZero
        }
    case 1:
        if let elOne = element{
            colorClass.colorTwo = elOne
        }
    case 2:
        if let elTwo = element{
            colorClass.colorThree = elTwo
        }
    case 3:
        if let elThree = element{
            colorClass.colorFour = elThree
        }
    default:
        break
    }
}

var myDict = [String:AnyObject]()
myDict.updateValue(colorClass.colorOne!, forKey: "firstKey")
myDict.updateValue(colorClass.colorTwo!, forKey: "secondKey")
myDict.updateValue(colorClass.colorThree!, forKey: "thirdKey")
myDict.updateValue(colorClass.colorFour!, forKey: "fourthKey")

崩溃发生在:

myDict.updateValue(colorClass.colorThree!, forKey: "thirdKey")
myDict.updateValue(colorClass.colorFour!, forKey: "fourthKey")

最佳答案

在字典中添加/更新值时,使用 if let 忽略 nil 值。

if let clrThree = colorClass.colorThree {
     myDict.updateValue(clrThree, forKey: "thirdKey")
}

if let clrFour = colorClass.colorFour {
     myDict.updateValue(clrFour, forKey: "fourthKey")
}

崩溃的原因是, 您在 colorClass.colorFour 之后使用 ! 即您正在使用 colorClass.colorFour!

When swift finds the value of the variable as nil and try to forcefully unwrap it the application will crash unexpectedly found nil while unwrapping

关于ios - Swift iOS - 获取字典以接受零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40676552/

相关文章:

JavaScript : How can I add X elements to an array

ios - 删除单元格后使用自定义布局调整 UICollectionView 的大小

ios - 如何将 swift pod 类导入 Objective C UIView 类

ios - 如何使用 Rxswift 获取 UIImageView 的 Observable is Empty?

ios - 如何将 iPhone 捕获的视频转换为 HTTP 实时流文件?

iOS 8 UIVisualEffect UIBlurEffect 和缩放/移动/调整大小

ios - 新版本以完全不同的配置文件发布到应用商店

python - 如何在python中找到两个numpy数组的最近点

c++ - 是否可以创建 3d 数组的指针数组?

ios - 带有翻转动画的导航 Controller