13

I don't think the question mark in public init?(coder aDecoder: NSCoder) is about optionals. Also, when I override it I find I don't need to write the question mark at all.

So what does it mean exactly ?

--- Update ---

The comment below helped me figure that out. It is called a "failable initializer". Another example that can make the concept easier to understand is UIFont's convenience init because the UIFont may not exist.

public /*not inherited*/ init?(name fontName: String, size fontSize: CGFloat)
hippietrail
  • 15,848
  • 18
  • 99
  • 158
Qiulang
  • 10,295
  • 11
  • 80
  • 129

2 Answers2

10

It's called failable initializer. In the book, The Swift Programming Language, it describes it as

“It is sometimes useful to define a class, structure, or enumeration for which initialization can fail. This failure might be triggered by invalid initialization parameter values, the absence of a required external resource, or some other condition that prevents initialization from succeeding.”

Check the "Failable Initializers" section in the Swift Docs

T.V.
  • 793
  • 12
  • 33
Ch0k0l8
  • 827
  • 6
  • 14
1

init?() or Failable Initializers

init?() or Failable Initializers means that the initialiser can return nil. It means that object couldn't be constructed(creation fails) and it is useful to pass any parameter into init which is responsible to create an object or just fail because of some reason.

yoAlex5
  • 29,217
  • 8
  • 193
  • 205