Answer the question
In order to leave comments, you need to log in
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)
}
}
}
typeNames
, but .contains
it does not want to work on an array of type [String?] . Answer the question
In order to leave comments, you need to log in
As a result, I refused to stuff nil
it into the same array, I did everything through Set<String>
+ a hardcoded handler for nil
.
If uniqueness is needed, I would use Set
, instead, Array
and 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 questionAsk a Question
731 491 924 answers to any question