2

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?

4
  • in this Array<UIImageView!>, what is the exclamation mark doing here exactly? Commented Jul 30, 2014 at 15:26
  • Defining the UIImageView as optional. Commented Jul 30, 2014 at 15:27
  • @holex: UIImageView! is an implicitly-unwrapped optional of UIImageView Commented Jul 30, 2014 at 20:42
  • This is not reproducible with the latest beta Commented Aug 10, 2014 at 22:24

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

3 Comments

But implicitly-unwrapped optional can also store nil. The problem is with bridging.
@user102008 Yes because, as the error says, you cannot bridge an implicitly unwrapped optional containing nil. If he wants to bridge to Objective-C (which using UIImageView requires), he has to use a normal Optional.
@drewag: Of course you can bridge implicitly-unwrapped optionals. They get bridged to Objective-C object pointer type. nil gets bridged to nil pointer. It's just putting it in an NSArray that fails. Also, on the contrary, a normal Optional cannot be bridged to Objective-C. That's why your code worked -- by preventing the array from being bridged to NSArray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.