Reputation: 19592
I have an array that can hold up to 4 values. The array will always have at least 1 value but the other 3 may be nil. I have to take the elements inside the array and assign them to class properties.
The problem is once I iterate through the array, get nil values, assign them to the class properties and then try to assign those nil properties to my dictionary, I get a crash.
I need the dictionary to accept the values with colors and ignore the nil values. So I have 2 problems.
How would I go about fixing this?
code:
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")
The crashes occur on:
myDict.updateValue(colorClass.colorThree!, forKey: "thirdKey")
myDict.updateValue(colorClass.colorFour!, forKey: "fourthKey")
Upvotes: 1
Views: 507
Reputation: 4941
Use if let
to ignore nil
values while adding/updating the values in the dictionary.
if let clrThree = colorClass.colorThree {
myDict.updateValue(clrThree, forKey: "thirdKey")
}
if let clrFour = colorClass.colorFour {
myDict.updateValue(clrFour, forKey: "fourthKey")
}
Reason of Crashes is,
you are using !
after the colorClass.colorFour
i.e. you are using as 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
Upvotes: 2