Swift Tour Summary (3), swifttour

Source: Internet
Author: User

Swift Tour Summary (3), swifttour

About Optional Control Flow

If let constantName = someOptional {

Statements

}

If the Optional is nil, if is not entered; otherwise, the execution and constantName are the value of the Optional.

Example:

If let actualNumber = possibleNumber. toInt (){

Println ("\ (possibleNumber) has an integer value of \ (actualNumber )")

} Else {

Println ("\ (possibleNumber) cocould not be converted to an integer ")

}

// Prints "123 has an integer value of 123"

About nil

Optional can be assigned a value of nil.

For example:

Var serverResponseCode: Int? = 404

ServerResponseCode = nil

 

Var surveyAnswer: String?

// SurveyAnswer is automatically set to nil

 

Expansion of optional: Implicitly Unwrapped Optionals

Sometimes, an optional will be safe after the first assignment, and nil check is not required.

Definition: String! Instead of String?

Example:

Let possibleString: String? = "An optional string ."

Println (possibleString !) // Requires an exclamation mark to access this value

// Prints "An optional string ."

 

Let assumedString: String! = "An implicitly unwrapped optional string ."

Println (assumedString) // no exclamation mark is needed to access its value

// Prints "An implicitly unwrapped optional string ."

 

For this special type (IUO), general optional usage is applicable:

If assumedString {

Println (assumedString)

}

 

Assertions-debugging

Let age =-3

Assert (age> = 0, "A person's age cannot be less than zero ")

// Assertion trigger

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.