Constructing Collections with Literals
Most Swift types require constructors or factory methods to create instances:
| let instance = TypeConstructor(arguments...) |
However, most collections support literal initialization. When available, prefer literal initialization to constructors, especially for array and dictionary literals:
| let array: [String] = [] // yes |
| let dictionary: [AnyHashable: Any] = [:] // yes |
| let aSet: Set<String> = [] // yes |
| let array = [String]() // no |
| let array = Array<String>() // no |
| let dictionary = [AnyHashable: Any]() // no |
| let dictionary = Dictionary<AnyHashable: Any>() // no |
| let aSet = Set<String>() // no |
This is a guideline, not an absolute. Using ...
Get Swift Style now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.