Swift Constants and variables

Source: Internet
Author: User

Defined
    • letDefines constants that are not allowed to be modified once assigned
    • varDefine variables that can still be modified after assignment
//: # 常量//: 定义常量并且直接设置数值let x = 20//: 常量数值一经设置,不能修改,以下代码会报错// x = 30//: 使用 `: 类型`,仅仅只定义类型,而没有设置数值let x1: Int//: 常量有一次设置数值的机会,以下代码没有问题,因为 x1 还没有被设置数值x1 = 30//: 一旦设置了数值之后,则不能再次修改,以下代码会报错,因为 x1 已经被设置了数值// x1 = 50//: # 变量//: 变量设置数值之后,可以继续修改数值var y = 200y = 300
Automatic derivation
    • Swift can deduce the exact type of the variable according to the code on the right.
    • Typically at development time, you do not need to specify the type of the variable
    • If you want to specify a variable, you can use it after the variable name: And then follow the type of the variable

Important tip: Option + Click To see the types of variables

No implicit conversions!!!
    • Swift is extremely strict with data type requirements
    • No implicit conversions are made at any time.

If you want to perform calculations on different types of data, you must explicitly convert

let x2 = 100let y2 = 10.5let num1 = Double(x2) + y2let num2 = x2 + Int(y2)
Let & var options
    • You should select constants as much as possible before you need to modify them tovar
    • In Xcode 7.0, if the variable is not modified, Xcode will prompt to change tolet

Swift constants and variables

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.