CollectionOfOne in Swift
2 min readJul 4, 2023
Apple says: You can use a
CollectionOfOne
instance when you need to efficiently represent a single value as a collection.
In simple words by using CollectionOfOne we can use any single value as collection
Suppose take an Example I have array of users :
let arrUsers = ["Pawan", "John", "Mike"]
Now I want new users array with new user
var arrUsers = ["Pawan", "John", "Mike"]
let newUser = "Brock" // New user
let arrNewUsers = arrUsers + [newUser]
So I created new user variable by appending into new users array by using [], but we have CollectionOfOne which can help us here to do it in better and cleaner way
var arrUsers = ["Pawan", "John", "Mike"]
let newUser = "Brock" // New user
let arrNewUsers = arrUsers + CollectionOfOne(newUser)
This is possible because CollectionOfOne confirms to collection protocol.
For more visit: https://ioslifee.blogspot.com
Thanks for reading, Happy Coding 💻