what does constant property means in swift? [duplicate] - swift

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"]
//..
}

Related

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.

Print contents of array with custom class swift [duplicate]

This question already has answers here:
Overriding description method in NSObject on swift
(1 answer)
How can I change the textual representation displayed for a type in Swift?
(7 answers)
Closed 5 years ago.
I have an array of type custom class as seen below. It has strings, ints, and double values.
class TrendData: NSObject {
var earlyTime = Date()
var recentTime = Date()
var earlyTimePrice = Double()
var recentTimePrice = Double()
}
I have an array as follows
let dataArray = [TrendData]()
I have filled in 2 values into the dataArray.
Right now when I use a print command as follows
print ("Label: \(dataArray)")
it prints this Label: [<App.TrendData: 0x600000472440>] ** [<App.TrendData: 0x600000472440>]
This is the correct behavior but I want to see all the values within each of these elements in the array. What is the best way to do that? I don't want to explicitly list out each element or even put it into a loop if I can avoid it. I am able to do it, it is just really messy right now. Is there any function or command that does this automatically?

Structure instance property value [duplicate]

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.

Swift ViewController class name as String [duplicate]

This question already has answers here:
Get class name of object as string in Swift
(32 answers)
Closed 8 years ago.
I have a viewController called 'MyViewController' in which I want to save some values to the user defaults. As key I wanted to use the class name "MyViewController" and append some string. Is it possible in Swift to get the String out of a class name? Thanks for any help :)
There may be a better way to do this, but as far as I know, you can get at the class name via classForCoder() (NSObject subclasses only). From there, you can use NSStringFromClass to convert the class name to an NSString. Only problem is the the name will often come out mangled, maybe "__lldb_expr_690.MyViewController". You can get around this by explicitly setting the name, ex:
#objc(MyViewController) class MyViewController: UIViewController {
func aMethod() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Some Object", forKey: NSStringFromClass(self.classForCoder))
defaults.synchronize()
// Has set "Some Object" for key "MyViewController"
}
}
class MyOwnClass {
}
var myVar1 = NSString()
var myVar2 = MyOwnClass()
println(_stdlib_getTypeName(myVar1)) // Gives "NSString"
println(_stdlib_getTypeName(myVar2)) // Gives "_TtC15__lldb_expr_26410MyOwnClass"

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