简体   繁体   中英

Swift Syntax Error and init()?

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");
}
  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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM