Say I have an array of Int
s.
var nums = [5, 4, 3, 2, 1]
var maybeNum: Int?
nums.append(maybeNum)
But this results in an error. Do I really have to check if it has a value, and only insert it if it does?
You can use the following extension:
extension Array {
public mutating func append(_ newElement: Element?) {
if let element = newElement {
self.append(element)
}
}
}
This way, you can still use the original append
method. When appending a non-optional element, the regular method will be used. When appending an optional element, this method will be used and the element will only be appended when it is not nil.
Use map(_:) with optional binding, i.e. will only append when maybeNum is not nil:
var nums = [5, 4, 3, 2, 1]
var maybeNum: Int?
maybeNum.map { nums.append($0) }
Apple documentation: https://developer.apple.com/documentation/swift/optional/1539476-map
First, you have to 'unwrap' maybeNum
whose type is Int?
.
After unwraing, num
's type is Int
which can be appened to nums: [Int]
if let num = maybeNum {
nums.append(num)
}
I'm quite late to this question, but there is an option as well by using compactMap()
. This method will call the function you pass to it in every element of the array, and then exclude null elements from the result. So, by passing a function that just return the element, you can transform an array of type [Int?]
into [Int]
.
let onlyNumbers = [1, 2, 3, nil, 4].compactMap { $0 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With