Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Create mutable array with empty fields

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?

like image 869
BadmintonCat Avatar asked Mar 16 '26 15:03

BadmintonCat


1 Answers

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)
like image 157
drewag Avatar answered Mar 19 '26 04:03

drewag