Swift 5/Xcode 12.4.
I know how to initialize an empty array:
var myarray = [String]()
I know how to initialize an optional String:
var mystring:String? = ""
How do I create an empty, optional Array and initialize it? I don't want the contents to be optional but the array itself, so I can set it to/check it for nil.
This answer suggests using var myArray = [String]?() but this just shows a "No exact matches in call to initializer " error in playground.
var myarray:[String]? = () also displays an error ("Cannot convert value of type '()' to specified type '[String]?'").
var myarray:[String]? = []?Optional<Array>is an anti-pattern in Swift. You can represent the lack of value with an empty array, there's no need to wrap it in anOptional.niland you should only use an optional to a type that can either have a value or not,nilrepresents the lack of value. However, in case of collections, you can represent the lack of value using an empty collection, hence it's discouraged to use optional collections, since they just complicate your interface without any benefits (in most cases).