How to use (?) And (!) In Swift

I am new to fast and have difficulty understanding how to use (!) And (?)

As far as I know, we can use (?) When there are instances in which the variable can be equal to zero. And use (!) When you are 100% sure that the element is not zero.

1. Small workers - optional

var john:String?
john = "Is my name"
println(john!)

2. Runtime crashes -! should not be nil - means that this is correct

var john:String?
println(john!)

3. Works well

var dict: [String:AnyObject] = Dictionary()
dict["name"] = "John"
var str: String = dict["name"]! as String <--- Taking away the (!) says it not convertible to String

4. I can not start / create - for me it is like 1.

var dict: [String:AnyObject]? = Dictionary() ---error says does not have a member named 'subscript'
dict["name"] = "John"
var str: String = dict["name"]! as String

5. Unexpectedly found nil when deploying an optional value

var dict: [String:AnyObject] = Dictionary()
dict["name"]? = "John"
var str: String = dict["name"]! as String

It would be great if someone helped me understand these things. Thank!

+4
source share
1 answer

, ! '' ivar, 100% nil. . , , , , nil.

, :

var text: String! = "hello"
text = nil;
println(text)

a nil .

, , - nil, , .


# 4

:

var dict: [String:AnyObject]? = Dictionary() // from OP

dict , , :

dict["name"] = "John" // from OP
var str: String = dict["name"]! as String // from OP

dict, - , :

  • (A) ;
  • (B) ;

()

dict?["name"] = "John" // optional chaining

, name, nil, , .

:

var str: String = dict!["name"]! as String // forcibly unwrapped

, nil ( : a nil), str John .

(B)

dict!["name"] = "John" // forcibly unwrapped

name, dict; dict nil, (aka crash), nil (. ).


# 5

:

var dict: [String:AnyObject] = Dictionary() // from OP

dict nil, , , name.

dict["name"]? = "John" // from OP
var str: String = dict["name"]! as String // from OP

, - , , , , , , (. ).

, :

dict["name"] = "John"

, /, :

dict["name"] = "John"
dict["name"]? = "Jack"

Jack, , name , ; :

dict["name"] = nil
dict["name"]? = "Jack"

.


. , . Apple Swift Resources.

+5
source

All Articles