Swift's optional selectable values

Source: Internet
Author: User

    • Optionalis a major feature of Swift and the most confusing problem for swift beginners
    • When a variable is defined, the variable is represented if it is specified 可选的可以有一个指定类型的值,也可以是 nil
    • When defining a variable, add one after the type ? to indicate that the variable is optional
    • The default value of a variable's optional option isnil
    • Constant options have no default values and are primarily used to set initial values in constructors for constants
//: num 可以是一个整数,也可以是 nil,注意如果为 nil,不能参与计算let num: Int? = 10
    • If the Optional value is nil not allowed to participate in the calculation
    • Only 解包(unwrap) then can we participate in the calculation
    • Add one after the variable to ! forcibly unpack the package

Note: You must ensure that the value after unpacking is not nil, otherwise it will be an error

//: num 可以是一个整数,也可以是 nil,注意如果为 nil,不能参与计算let num: Int? = 10//: 如果 num 为 nil,使用 `!` 强行解包会报错let r1 = num! + 100//: 使用以下判断,当 num 为 nil 时,if 分支中的代码不会执行if let n = num { let r = n + 10}
Common errors

unexpectedly found nil while unwrapping an Optional value

Translation

在[解包]一个可选值时发现 nil

??Operator
    • ??The operator can be used to determine 变量/常量 if the numeric value is nil , or if it is, use the following value instead
    • Simplifies code writing when using Swift development ??
    • Equivalent to three mesh operation
let num: Int? = nillet r1 = (num ?? 0) + 10print(r1)

Swift's optional selectable values

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.