I have an array in a plist that contains 2 integer values. I can read the first value no problem by using this code
let mdic = dict["m_indices"] as? [[String:Any]]
var mdicp = mdic?[0]["powers"] as? [Any]
self.init(
power: mdicp?[0] as? Int ?? 0
)
Unfortunately, some of the plists do not have a 2nd index value. So calling this
power: mdicp?[1] as? Int ?? 0
return nil. How can I check whether there is an index there or not so it only grabs values when a value is present? I've attempted to wrap it in an if-let statement
if let mdicp1 = mdic?[0]["powers"] as? [Any]?, !(mdicp1?.isEmpty)! {
if let mdicp2 = mdicp1?[1] as! Int?, !mdicp2.isEmpty {
mdicp2 = 1
}
} else {
mdicp2 = 0
}
But my attempts so far have let to multiple console errors.
If you're dealing with array of integers and are only worried about the first two items, you can do something like:
let items: [Int] = [42, 27]
let firstItem = items.first ?? 0
let secondItem = items.dropFirst().first ?? 0
Whether you really want to use the nil coalescing operator, ??
to make missing values evaluate to 0
, or just leave them as optionals, is up to you.
Or you could do:
let firstItem = array.count > 0 ? array[0] : 0
let secondItem = array.count > 1 ? array[1] : 0