Junior — Middle
Can different data structures store data types inside?
sobes.tech AI
Answer from AI
Yes, various data structures in iOS (such as arrays, dictionaries, sets) can store objects of different types, but with some features:
- In Swift, collections are usually type-safe, meaning arrays have a specific element type, for example
[Int]or[String]. - If you need to store different types in one collection, you can use the
AnyorAnyObjecttype, for example[Any]— an array that can contain objects of any type.
Example:
var mixedArray: [Any] = ["String", 42, 3.14, UIView()]
for element in mixedArray {
print(type(of: element))
}
- In Objective-C, collections (
NSArray,NSDictionary) can contain objects of any class, as they work with theidtype.
Thus, data structures can store different types, but in Swift, it is recommended to use specific types for safety and convenience.