-1

I study swift. I have a question about initializers init().
For example, I want to initialize Int.

var number: Int  = 20
var number = Int(20)
var number = Int.init(20)

All expression is same?
Second, Why this expression occurs?

var check = "123"
var phoneNum:Int?
if((phoneNum = Int.init(check)) != nil)
{
    print("Success");
}

There is no error!

var check = "123"
var phoneNum:Int? = Int.init(check)

if(phoneNum != nil)
{
    print("Success");
}
Arc676
  • 4,445
  • 3
  • 28
  • 44

2 Answers2

3
  1. Yes, these all have the same effect:

    var number: Int  = 20
    var number = Int(20)
    var number = Int.init(20)
    

    And this is one more way to do it:

    var number = 20
    
  2. This produces an error:

    var check = "123"
    var phoneNum:Int?
    if((phoneNum = Int.init(check)) != nil)
    {
        print("Success");
    }
    

    You get an error (“error: value of type '()' can never be nil, comparison isn't allowed”) because assignment in Swift returns (), the sole value of type Void, but nil is type Optional, which is different than Void. Assignments in Swift cannot generally be used as expressions.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
2

I wanted to add this as a comment to rob's answer but since I don't have enough reputation, here's my answer as? a comment (pun intended ;).

Regarding the last two examples you can also use optional binding to help in an assignment:

var check = "123"

var phoneNumber: Int?

if let number = Int.init(check) {
    phoneNumber = number
    print("Success")
}

print(phoneNumber)

// Success
// Optional(123)

Changing the check value:

var check = "A23"

var phoneNumber: Int?

if let number = Int.init(check) {
    phoneNumber = number
    print("Success")
}

print(phoneNumber)

// nil

I hope this helps too.

Community
  • 1
  • 1