Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int with no value (set int to no value)

I want to create an Int that has no value (an already existent variable). If I do this;

number = Int()

then it still has the value 0. I want nothing, a nonexistent value.

like image 273
Rappe Stegarn Avatar asked Nov 30 '22 09:11

Rappe Stegarn


2 Answers

Every type can actually be set to an empty value aka nil!

To create a variable that can be set to nil, you need to write the type name explicitly with a ? or ! (I'll talk about the difference later) at the end.

For example, if you want an Int that can be set to nil, declare a variable with the type name:

var myInt: Int

and then you add a ?:

var myInt: Int?

Then, you can set myInt to nil, or whatever values you want:

myInt = nil
myInt = 0

This type-name-with-? notation is known as "Optional Types" in Swift.

Not only can you use optionals in variables and constants, you can also use it in method/function signatures:

func myUselessFunc(value: Int?) -> Int? {
    return value
}

Okay, so what's the difference between ! and ??

! acts like reference types in Java and C#. And ? is like a safer version of !.

Let's say there's an optional Int called myInt. You want to access its description.

If myInt were declared as let myInt: Int?,

myInt?.description

If myInt were declared as let myInt: Int!

myInt.description

Notice that with the question mark, you need to add a question mark at the end every time you need to access property/method of myInt. This is called "Unwrapping an optional type".

A type with the ! suffix is called an "Implicitly Unwrapped Optional Type". When working with these types, you don't need to unwrap it. However, if myInt is nil, there will be an error! This doesn't happen with ? types because the whole expression will just return nil if myInt is nil.

That's just something I think you should note when you work with optionals the first time.

like image 56
Sweeper Avatar answered Dec 04 '22 11:12

Sweeper


You need an Optional Int. By putting a question '?' mark you initialize that varaible by nil.

var number: Int?

Refer this link for more details https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

like image 30
Ashish Verma Avatar answered Dec 04 '22 12:12

Ashish Verma