I want to create an array in Swift that is of type UIImageView but should initially have some empty fields (nil) that act as placeholders. Is that possible? It was easy to create in Objective-C, like:
[self.pageViews addObject:[NSNull null]]
In Swift I define the array like this:
var pageViews:Array<UIImageView> = [];
override func viewDidLoad()
{
super.viewDidLoad();
for i in 0 ..< 5
{
pageViews.append(nil);
}
}
Of course that doesn't work. If I define the array with
var pageViews:Array<UIImageView!> = [];
I wont get a compile-time error but the app throws a fatal error:
fatal error: attempt to bridge an implicitly unwrapped optional containing nil
Is there any good workaround for this problem?
If you want to be able to store nil in the array, you have to define its type as storing an Optional value. You can also use the count:repeatedValue: initializer for convenience:
var pageViews = [UIImageView?](count: 5, repeatedValue: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With