Swift optional type (supplemental)

Source: Internet
Author: User

Optional Type

Optional Type: This value either exists equal to Xor the value does not exist at all

var serverresponsecode: Int? = 404 //? This means that this only exists for 404, or that this value does not exist as nil .

let possbilenumber = "123"

Let Covernumber:int? = Possbilenumber.toint ()

var responsecode: Int? = 404 // exists as 404

Responsecode = nil // or absent as nil

The optional type is similar to the value of the pointer nil in objective-c, but nil is only useful for classes (class), where theobject does not exist, and the Nil is not a pointer, it represents a value of a particular type that does not exist. The value of any type of optional class can be assigned to Nil, not just the object type.

/*

Nilin 1.Swift, cannot be used for non-selectable types

2. if a variable or constant in your code requires that the adaptation value does not exist, be sure to declare it as the appropriate optional type

3. If the defined optional type does not provide a default value, the default is nil

*/

var strvalue: String? = "Hello"

let hasValue = strvalue?. hashValue // question mark means asking if the optional quantity responds to this method later

Print("HasValue is \(hasValue)")

/* summary ? The usage scenario

1. declared as Optional variable

2. declared as Optional variable, whether to respond to the following method

*/

Swift optional type (supplemental)

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.