Structure instance property value [duplicate] - swift

This question already has answers here:
Why constant constraints the property from a structure instance but not the class instance?
(2 answers)
Closed 6 years ago.
I can update property value of class instance using dot notation However It doesn't work for structure.
Here is example:
struct Resolution {
var width = 0
}
class VideoMode {
var interlaced = false
}
let someResolution = Resolution()
let someVideoMode = VideoMode()
For class:
someVideoMode.interlaced // false
someVideoMode.interlaced = true //true
someVideoMode.interlaced // now true
For Struct :
someResolution.width // 0
someResolution.width = 200 // throws an error says : someResolution is constant
Question is :
someResolution and someVideoMode both are constants.
I can change the property value of class instance without error not saying someVideoMode is constant.However
I can not change the property value of struct.It throws an error says someResolution is constant
Why ?
Thank you !

structs are Value types, while classes are References.
While you can set properties of a constant reference type, you can not change the reference itself.
let someVideoMode = VideoMode()
someVideoMode = VideoMode()
would cause an error.
You can find a detailed description in the documentation you actually got this sample from.

Related

var to let type conversion or vice versa in swift: [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Can a var type be changed into let type or vice versa in swift. I try to search it online but there is no such content available online.
You cannot change the mutability of a variable once it has been declared. However, you can create a mutable/immutable copy of any variable.
let immutable = 21
var mutableCopy = immutable
mutableCopy = 2
var mutable = 3
let immutableCopy = 4
You also have to be aware though that mutability and copying means different things for reference and value types.
conversion from let to var
let a = "" /* Constant */
var b = a /* Variable */
b = "b"
conversion from var to let
var c = "" /* Variable */
let d = c /* Constant */
Declaring Constants and Variables Constants and variables must be declared before they’re used. You declare constants with the let
keyword and variables with the var keyword. source
Struct (Value Type) vs Class (Reference Type)
class TotoClass {
var str = "str"
}
struct TotoStruct {
var str = "str"
}
let classToto = TotoClass()
let structToto = TotoStruct()
classToto.str = "new Str"
structToto.str = "new Str"
last line doesn't compile and there will be an error
Cannot assign to property: 'structToto' is a 'let' constant

Cannot use instance member 'ie' within property initializer [duplicate]

This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 5 years ago.
The code:
class man: human {
var ie = "ie/1/3/1///"
let pe = "pe/1/3/3///"
let ol = "ol/1/1/1///"
let sejong = "sejong/3/1/1///"
let gong = "gong/1/1/1///"
let mans = [ie, pe, ol, sejong, gong]
}
The error:
Col 15: cannot use instance member 'ie' within property initializer;
property initializers run before 'self' is available
How can I debug this?
Instance variables cannot be used upon non-lazy initialization of each other.
Consider your code taking into account the following thing: it doesn't matter in which order you define and initialize a variable. From your (developer) perspective, they will all get initialized simultaneously (they are, of course, not from low-level perspective).
It means that when you write:
let mans = [ie,pe,ol,sejong,gong]
You basically tell compiler to make up an array of something not yet initialized. None of the constituents of your array are existent when you make this assignment.
Common solution is to make your initialization - that which relies on other instance variables - lazy:
class man {
var ie = "ie/1/3/1///"
let pe = "pe/1/3/3///"
let ol = "ol/1/1/1///"
let sejong = "sejong/3/1/1///"
let gong = "gong/1/1/1///"
lazy var mans : [String] = {
[ie,pe,ol,sejong,gong]
}()
}
Unlike ordinary, lazy variable obtains its value on first use of this variable, but not instantly once an object has been created. You tell compiler: I don't mean to make up an array right away, but make me one when I firstly use this variable, after the object has already been created:
let theMan = man()
On this stage, theMan.mans property is not yet initialized. However, suffice it to perform even basic operation, like printing:
print(theMan.mans)
that this property is initialized. This is called lazy initialization and this is the way you can make up an array consisting of other instance variables upon initialization. Of course, you should remember that any dependent data may be modified and affect the init.

what does constant property means in swift? [duplicate]

This question already has answers here:
What is the difference between `let` and `var` in Swift?
(32 answers)
Closed 5 years ago.
I am learning SWIFT. I don't understand one sentence while reading book. What does the sentence below means?:
“Add a constant property called elementList to ViewController.swift
and initialize it with the following element names: let elementList =
["Carbon", "Gold", "Chlorine", "Sodium"]”
does it mean create new class or I have to create struct?
In you situation, you are creating an array of string and store it into a constant variable called elementList. When you use let to create this variable, it means that the value cannot be changed afterwords. So you cannot add or remove element after declaring this array in this way, etc
class ViewController: UIViewController {
var intValue = 1 //This is a property, but it is variable. That means its value can be changed in future.
let doubleValue = 3.14 // This is a property too, but it is constant. That means its value can't be change
// Both `intValue` & `doubleValue` will be in memory till ViewController's existence.
}
IN YOUR CASE:
let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]
elementList is a array of String, since let keyword denotes that it is a constant property
To Add a constant property called elementList to ViewController.swift and initialize it. IT WOULD LOOK SOMETHING LIKE THIS
class ViewController: UIViewController {
let elementList = ["Carbon", "Gold", "Chlorine", "Sodium"]
//..
}

I'm getting a constant 'error' used before being initialized message [duplicate]

This question already has an answer here:
Constant unassigned optional will not be nil by default
(1 answer)
Closed 6 years ago.
The following code works fine
struct carConfi {
var owner: String?
let brand: String = "BMW"
var currentMile: Double = 2000
}
let tomCar = carConfi()
However, if I change the type of the property owner to constant, there will be an error at the initializer
struct carConfi {
let owner: String? // Change to constant
let brand: String = "BMW"
var currentMile: Double = 2000
}
let tomCar = carConfi() //error: missing argument for parameter 'owner' in call
I did a bit search, it turns out that it is because the optional variables automatically have a default value of nil
I guess: Because once the constant is set, it then cannot be changed, if the optional constant automatically received an nil then it will keep as an unchangeable nil that's very silly and may against the users will
Question: My college doesn't fully convinced by the guess, he told me there must be more reasons for that. I would very appreciate if someone can explain that to me
Thx
Not setting a read-only (constant) field with either an:
initialization expression
initializer
is almost certainly an indication of an error in your program.
Since you have no other opportunity to set the value of your let field, the value of the field is going to remain nil (or some other default). It is rather unlikely that a programmer would find such behavior desirable, and request it on purpose.
That is why Swift marks this situation as an error. On the other hand, if you actually wanted your String constant to remain nil, you could add an expression to set it to nil, and silence the error:
let owner: String? = nil // Pretty useless, but allowed
Constants are set once, and once only. If you wanted it to be null or 0, then you would set it. You always define a constant on initiation.

Class Instantiation in Apple Swift [duplicate]

This question already has answers here:
What is the difference between `let` and `var` in Swift?
(32 answers)
Closed 8 years ago.
Why to instantiate a class I have to do it as a constant with let,
class car {
var type: Int?
var wheels: Int?
}
let auto = car()
I can use var as well:
var auto = car()
What is the difference?, thanks
A constant can only be assigned to, or initialized, once:
let constantAuto = car()
constantAuto.type = 1 // changing properties is fine
constantAuto.wheels = 4
constantAuto = car() // error - can't do this
whereas a variable can be assigned to multiple times:
var variableAuto = car()
variableAuto.type = 1 // changing properties is fine here too
// etc
// need to reset:
variableAuto = car()
Essentially, when you know you're only going to need to create the instance once, use let, so the compiler can be more efficient about the code it creates.
if you're using let you're defining a constant, whereas with var you're declaring a variable.
"A constant declaration defines an immutable binding between the constant name and the value of the initializer expression; after the value of a constant is set, it cannot be changed. That said, if a constant is initialized with a class object, the object itself can change, but the binding between the constant name and the object it refers to can’t."
from https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Declarations.html
to sum it up:
you can change the object a variable refers to, but you can't do that to a constant