var arr = [String]()
if !arr.contains(element) {
arr.append(element)
}
or
extension Array where Element: Equatable {
mutating func appendIfNotExists(_ element: Element) {
if !self.contains(element) {
self.append(element)
}
}
}
// Usage example
var myArray = [1, 2, 3]
myArray.appendIfNotExists(2) // Will not append since 2 already exists
myArray.appendIfNotExists(4) // Will append since 4 does not exist
print(myArray) // Output: [1, 2, 3, 4]