What does the question mark mean in public init?(coder aDecoder: NSCoder)?
Asked Answered
E

2

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)
Embryologist answered 22/2, 2016 at 8:42 Comment(2)
I just downloaded the latest 2.2 version and found it called "failable initializer". The 2.1 version didn't mean it. Thanks!Embryologist
It's not just for public init() but for any init()Dentistry
A
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

Arterialize answered 22/2, 2016 at 9:20 Comment(1)
Yes I have figured that out (Swift 2.1 book didn't mention it, see my comments above). ThanksEmbryologist
S
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.

Shaveling answered 2/10, 2020 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.