3

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.

user2219372
  • 2,385
  • 5
  • 23
  • 26

3 Answers3

7

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.

Vakas
  • 6,291
  • 3
  • 35
  • 47
2

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.

Community
  • 1
  • 1
heikomania
  • 445
  • 6
  • 13
2

If your object can only be created if some condition is met then init? makes sense, since it could return an object or nil. As for as! you should only use that if you're absolutely certain the object is of that type, otherwise use this paradigm: if let object = obj as? String { ... } .

cjnevin
  • 311
  • 2
  • 8