我有一个最多可以容纳 4 个值的数组。该数组将始终至少有 1 个值,但其他 3 个可能为零。我必须获取数组中的元素并将它们分配给类属性。
问题是,一旦我遍历数组,获取 nil 值,将它们分配给类属性,然后尝试将这些 nil 属性分配给我的字典,我就会崩溃。
我需要字典来接受带颜色的值并忽略 nil 值。所以我有两个问题。
- 数组中确实存在的颜色在 myDict 中显示为 nil
- 数组中的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/