Swift Note-IF statement

Source: Internet
Author: User

1. Basic use

Let num = 23

If num > 10 {

Print ("num is big")

}else If num < 0 {

Print ("num is Fushu")

}else{

Print ("num is mid")

}

In Swift, the conditional statement followed by if must be a booltype expression, as if (num) in OC cannot be used in swift

2.if Let's understanding

var optionalname:string? = Nil

var greeting = "Hello!"

If let name = optionalname {

Greeting = "Hello!!! \ (name) "

}

The If let ... in this sentence makes me confused for a long time

Why is the if followed by let name = Optionalname instead of optionname! = nil?

var optionalname:string? = Nil

var greeting = "Hello!"

If optionalname! = Nil {

Greeting = "Hello!!! \ (name) "

}

See an explanation on the StackOverflow, feel more reasonable. Link http://stackoverflow.com/questions/24004443/ Reason-for-assigning-optional-to-new-variable-in-conditional-statement-in-swift

His explanation is that the 1.if-let structure allows you to get a definite value (non-nil) and avoid crashing, because Swift is a very clear language, which avoids the possibility of errors due to developers not taking all the circumstances into account. 2. Examples are as follows:

var optionalname:string? {

get {

If Checktouchid () {

Print ("Get Optionalname")

Return "John Appleseed"

} else {

return Nil

}

}

}

var greeting = "Hello!"

If optionalname! = Nil {

Greeting = "Hello, \ (optionalname)"

}

In this code, because Optionalname's getter method is declared, the IF optionalname! = Nil and greeting = "Hello, \ (optionalname)" There are getter methods called Optionalname, that is, the Getter method executes 2 times, so there are some problems in the actual development, such as Getter method is obtained from the network, or getter method execution payment operation, 2 times is unreasonable.

So if you switch to the IF-LET structure, you won't have this problem.

Swift Note-IF statement

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.