Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a one-line version of "add to array if not nil, otherwise don't bother"?

Tags:

swift

Say I have an array of Ints.

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?

like image 272
Doug Smith Avatar asked Jul 01 '15 02:07

Doug Smith


4 Answers

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.

like image 185
Andrés Pizá Bückmann Avatar answered Oct 27 '22 19:10

Andrés Pizá Bückmann


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

like image 30
SuperGlenn Avatar answered Oct 27 '22 21:10

SuperGlenn


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)
}
like image 5
Wonjung Kim Avatar answered Oct 27 '22 19:10

Wonjung Kim


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 }
like image 2
theffc Avatar answered Oct 27 '22 21:10

theffc