N
N
norlin2016-02-06 12:10:41
Swift
norlin, 2016-02-06 12:10:41

How to use Array.contains for optional types?

Good afternoon!
Task: select unique strings from several arrays, put these strings into a new array, in which the first element should be nil.
I wrote this code:

// item.category = [String]()
var types:[String?] = [nil]
var typeNames = [String]()
        
for (item) in news! {
    for (type) in item.category {
        if (!typeNames.contains(type)) {
            types.append(type)
            typeNames.append(type)
        }
    }
}

The extra array is very embarrassing typeNames, but .containsit does not want to work on an array of type [String?] .
Is it possible to optimize all this somehow?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
norlin, 2016-02-09
@norlin

As a result, I refused to stuff nilit into the same array, I did everything through Set<String>+ a hardcoded handler for nil.

A
Alexander Tikhonov, 2016-02-06
@tikhonov666

If uniqueness is needed, I would use Set, instead, Arrayand try to avoid writing bicycles.

var uniqueStringSet = Set<String>()
uniqueStringSet.unionInPlace(["Vasa", "Petya", "Gena"])
uniqueStringSet.unionInPlace(["Sasha", "Nikita", "Petya", "Serega", "Vasa"])

print(uniqueStringSet)

let array = Array<String>(uniqueStringSet)
var newArray = array.map{Optional($0)}
newArray.insert(nil, atIndex: 0)
print(newArray)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question