Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of as!,init? in swift?

Sometime when I use "as" ,xcode prompts failed and suggests change to "as!".Also I see some construstors is "init?".I know some variables could be difined as optional.What the meaning of a constructor to be optionsal?

I looked up the questions in "the swift programming language",but failed to get the answer.

like image 649
user2219372 Avatar asked Jan 23 '26 22:01

user2219372


2 Answers

Use

as

When you believe that a constant or variable of a certain class type may actually refer to an instance of a subclass.

Using

as?

will always return an optional value and if the downcasting wasn't possible it will return nil.

Using

as!

is forced unwrapping of the value. Use "as!" when you're sure that the optional has a value.

init? 

is used to write fail-able initialisers. In some special cases where initialisations can fail you write fail-able initiasers for your class or structure.

like image 141
Vakas Avatar answered Jan 26 '26 17:01

Vakas


For your as!-Question please look here. as! force unwraps your optional.

Regarding your init?-Question: This is called a failable initializer. Basically this means your init-method can fail and it will return nil. See the Swift Blog for reference.

like image 30
heikomania Avatar answered Jan 26 '26 16:01

heikomania



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!