+ 2

Which choice is the output value of the following code: var a = 0 let b = ++a let c = a++ print("\(a) \(b) \(c)")

Can you explain why a = 1 while var a =0? its states print("\(a) \(b) \(c)") which includes var and let unless I missed something.

6th Sep 2016, 7:34 AM
Fetsi Hlase
Fetsi Hlase - avatar
2 Respuestas
+ 4
first of all, you should forget about "a++" now, because it's get rid of from swift forever. It is replace by "a += 1" now, it means "get the value of a, add one more, than assign back to a again" so the code should run like this: var a = 0 a += 1 //a become 1 now let b = a // assign a(1) to b, so b is 1 a += 1 // a become 2 now let c = a // assign a(2) to c, so c is 2 print("\(a) \(b) \(c)") //print out "0 1 2"
17th Sep 2016, 3:43 PM
Nplus Chang
Nplus Chang - avatar
+ 4
The answer to this code is 2 1 1 How? let's see Firstly keep in mind that the first value of 'a' is assigned to be =0 and in any of the following operations the value of 'a' = 0 will be executed.But a++ and ++a operators assign the value of 'a' = a+1 and at each step the initial value of '' a'' will increase(or decrease with respect to the operations done) irrespective to the fact that any other variable will only request the (a)'s first value, i.e 0. var a = 0 //Here the value of a is assigned to be = 0 let b = ++a //b is a constant which = ++a i.e a=a+1=b ,so b=1,a=1 let c = a++ //c is a constant which = a++ i.e a=a+1=c ,so c=1,but a=2 print("\(a)\(b)\(c)") Output:-> 211
11th Dec 2016, 6:36 AM
Himanshu Kumar
Himanshu Kumar - avatar