One of Swift's detailed--------variable declarations

Source: Internet
Author: User

Variable declaration 1, normal variable Swift, like JavaScript, can infer the type intelligently, and he will infer the type of the variable based on the value of our variable.

var age = 10Int
var name ="lily"//The compiler will automatically infer the string
static let name = "MyClass"//Static constants direct access to eg through the class name:ClassName.name

2. Storage type variable or storage type attribute

Grammar:var variable name: type = expression

Example:

    var   str:String  = "hellp world"     //指定str是String类型    var   age:Int = 10 //指定为int类型

You can use this form to declare a variable in a global, function, or declaration (context) of a class and struct. When a variable is declared in this form within a global or a function, it represents a stored-type variable. When it is declared in a class or struct, it represents a stored-type variable property.

3. Computational type and computed type properties

Grammar:

 var variable name: type {    get {                statements        }        set(setter name) {                statements        }}

Example:

private var _aa :String = ""var aa:String  {    get{        return  self._aa;    }    set{        self._aa=newValue;    }}

And then in the invocation of the very simple ClassName.aa="xxx" this equivalent to call the set, print(ClassName.aa) this is equivalent to call the get. Of course, the set is able to receive a parameter, you can not accept the default is newValue , you can also define yourself, as set(myValue) { self._aa = myValue; } of course I am just a very simple example, in the real project may be in the get or set worth the time to judge the value or a series of calculations after the return. Depends on the actual project.

4. Storage type variable monitor and property monitor

Grammar:

var variable name: type = expression {    willSet(setter name) {        statements    }    didSet(setter name) {        statements    }}

Example:

<swift>var age:Int = 0 {    willSet {          print("willset an new Value \(newValue)")      //willset监视器只有在变量或属性值被改变之前运行newvalue    }    didSet {         print("didset an old value \(oldValue)  will change to age \(age)")        //didset监视器在变量或属性值被改变后立即运行oldvalue    }}</swift>

Here Willset monitors are only run before variables or property values are changed. The new value passes through the Willset monitor as a constant, so you cannot change it in the Willset statement. The Didset Monitor runs immediately after a variable or property value has been changed. In contrast to the Willset monitor, in order to prevent you still need to get the old data, the old variable values or attributes go through the Didset Monitor. This means that if you set a value in the Didiset Monitor statement of the variable or property itself, the new value you set will replace the value that you just passed in the Willset Monitor.

I have this block of code Demo1 written in the class, called when the following:

  let dm = Demo1()    dm.age=20    dm.age=38

Results of the console printing:

Willset an new Value 20
Didset an old value 0 would change to age 20
Willset an new Value 38
Didset an old value--the change to age 38

5, in the variable! And?

Swift does not automatically assign an initial value to the variable, which means that the variable does not have a default value, so it must be initialized before using the variable, and if not initialized, it will be an error.

varString    >variable‘str‘ used before being initialized

The reason for the error is that the variable is not initialized before using the STR variable, which means that the variable does not have the memory at all

At this point we can use the optional type, which is followed by one?

varstr1:String?//如果str1 == nil 就不会调用hashValue方法 也就不会执行if语句块//如果str1 != nil  执行其hashValue方法 赋值给valif  let val = str1?.hashValue{    print("has value")}else{    print("no value"no

? is trying to split the package! is forced unpacking

var str2:String?str2="1"//! 表示 确定str2一定有值  如果没有值 就会报错  一般在保证有值得情况下才会这么做print(str2!.hashValue)   //"4799450059485597623\n"
//使用这种方式声明 在调用的时候不用加? or ! ,表示 调用的时候 肯定是有值的 如果没有值 就会报错varString"111"print(str3.hashValue)

Of course there is a lot to use! And? Places such as commissioned, here is to fill in the details, about the variables here first summed up so much later there will be more relevant to continue to add.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

One of Swift's detailed--------variable declarations

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.