Stored property initialisation for non optional - ios

I am pretty new to swift .
I found the following document from Apple.
Classes and structures must set all of their stored properties to an
appropriate initial value by the time an instance of that class or
structure is created. Stored properties cannot be left in an
indeterminate state.
You can set an initial value for a stored property within an
initializer, or by assigning a default property value as part of the
property’s definition. These actions are described in the following
sections.
but the below piece of code noOfTyres is not initialised and the compiler doesn't complain ,please explain this .
class Vehicle
{
var noOfTyres: Int!
var engineCapacity: Int
init()
{
engineCapacity = 10
}
}

In your case, the compiler won't complain, until you try to use that value. Because you have the value un-wrapped (!) it assumes that it will never be nil and trying to access the value, will crash.
In this case I would add a default value to the property noOfTyres.
var noOfTyres: Int = 2
Or, you can add the value in the constructor to make sure that everytime an object gets created, the value must be set.
class Vehicle
{
var noOfTyres : Int!
var engineCapacity :Int
init(noOfTyres: Int)
{
self.noOfTyres = noOfTyres
engineCapacity=10;
}
}
Remember, if it's not optional, you are saying, the property will never be nil.
Another thing, by convention class names must be capitalized.

You can declare a stored property without assigning it an initial value if you make this property an optional. The property then either has a value or it is nil. An optional property is either declared with
var myOptional : Int?
or
var myOptional : Int!
And therefore noOfTyres is not initialized, while it is an optional and currently it is set to nil.
For more information, please, read the Apple documentation.
Additional information. The different types of optional declaration (! and ?) are explained in this post.

I am not sure ,if this can be the answer
The documentation says ,
Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter.
Hence its expected by the compiler as initialised ,definitely containing a value.But If we access it without a value during run time it will crash
If using an optional as a stored property ,it will have atlas a nil value & for other stored properties ,need an initialisation.

Related

Swift: why lazy, computed property, and property observer can not be let

I have been searching on why lazy, computed property, and property observer can not be (let) constant, I know for example lazy are not assigned until it is accessed, but why it can not be (let), does that mean lazy will be holding a nil value or whatever value before it's being accessed and assigned to the value we assigned? please explain the same thing for computed property, and property observer.
Lazy properties : You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
computed property : whereas computed properties calculate (rather than store) a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
property observer : property observers is to monitor changes in a property’s value, if you define it let then how you can monitor changes because let is one type of constant which you can not change after init.
Rules:-
You can declare a property with either let or var keyword.
In swift, let variable must be initialized before the owner of the let variable is initialized.
Once you assign a value to the let variable, you can't change its value again.
Now let's see all three types of properties one by one:-
lazy variable - It initializes after the owner is initialized. So, rule 2 violates here.
computed variable - Whenever you access a computed variable, it returns the value after some calculation/operation. So, rule 3 violates here.
property observer - didSet or willSet of property observer gets called when you change its value. So, rule 3 violates here.

Swift optionals, unwrapping

I am learning the swift syntax and got a little confused with the optional type.
So, from the defination a swift type can not store the null value unless it is explicitly defined as an optional. So, what does the variable in the following line contains when it's declared.
var a:Int (declaring a variable without intializing it working fine in swift 3)
And also when we declare a variable as an optional with a "!",
var optionalSquare: Square! = Square(sideLength: 10, name: "Optional Square")
if we want to use the "optionalSquare" variable, we do not need to unwrap it cause we are sure(I think that is why we are using "!" instead of "?") it does not contain any null value. so why don't we declare it as a normal variable.
Please correct any false statements. Thank you.
what does [var a:Int] contains when it's declared
Nothing. Its value is undefined. Using it before assigning a value is a compilation error. You can declare it without initializing it, but you cannot use it.
This is part and parcel of Swift's philosophy of safety: in C, you could likewise leave a variable uninitialized, and its value would be undefined, but the compiler would not (by default) report error if you use it.
so why don't we declare it as a normal variable.
There's no reason that I can think of to make a local variable an implicitly unwrapped optional. The functionality is intended for properties ("ivars") on structs or classes. You should use them where it's impossible to set the property in the object's init, but it is certain that the value will be present before the object is used.
IBOutlets are probably the canonical use case. Another use that I find helpful is to allow setting a property by calling a method in init.
So, what does the variable in the following line contains when it's declared.
It does not matter, because you cannot access it anyway. A declaration like this tells Swift that you are going to decide on the value later. Reading the variable before assigning is an error that the compiler is going to catch.
why don't we declare [variables with forced unwrapping] it as a normal variables?
Because you may want to store nil in that variable at the times when it should not be used.
For example, you should make IB-assigned property implicitly unwrapped, because they need to be nil before NIB objects are "inflated", but after the init method has completed:
#IBOutlet private weak var myLabel: UILabel!
In order to make myLabel non-optional you would have to drop weak. On the other hand, you don't want to use exclamation point on each access of myLabel, because you know for sure that it must be initialized.
The same reasoning applies to other variables that you would like to make non-optional, but cannot assign in an initializer.
You can declare a non optional variable and not initialize it - the compiler doesn't complain as long as you do not use that variable. So this code
var num: Int
won't generate any error. However if you reference that variable before initializing, compilation fails
var num: Int
print(num)
In the former case there's no error because initialization can be deferred. You can declare a variable, and then initialize 100 lines after. As long as you don't reference it before initializing, you're ok.
To answer your second question, it's correct to say that in many cases it doesn't make much sense declaring and contextually initializing an implicitly unwrapped variable: a non optional variable is more appropriate.

What must be accomplished in the implementation of an initializer?

What must be accomplished in the implementation of an initializer?
a. All properties need to be initialized with a value
b. All properties need to be explicitly assigned a value.
c. All non-Optional properties need to be initialized.
Sorry, that's incorrect.
Optionals need to be initialized as well.
d. The object needs to be created
What answer is correct and why?
In my opinion that is very confusingly stated question. Because what you as the developer have to do is Option c.
Take a look at this simple code example and the minimum init to be compilable
class SomeClass {
var a : AnyObject
var b : AnyObject?
var c : AnyObject!
var d = ":)"
init() {
a = ""
print("initialized")
}
}
The swift docu states
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition. These actions are described in the following sections.
Option d. is imho non-sense since the object creation is handled by the underlying runtime environment and not via the initializer.
Now b. and a. remain with the tiny difference in wording explicitly assigned vs. initialized. I would therefore discard Option b because the b and c variable do not need any explicit value, the implicit nil is perfectly fine for the time (reading c will not work yet though)
Therefore my answer choice would be Option a. After the init method all properties need to have some specific value. Some of them explicitly in the init function, some of them implicitly.
tl;dr:
my final answer is Option a.

When to use ?, !, None, or Lazy?

I just started learning Swift and recently found out about
"Normal" variables (for lack of a better name):
ex: var test1: String
"Optional" variables
ex: var test2: String?
"Implicitly Unwrapped Optionals"
ex: var test3: String!
Lazy variables
ex: lazy var test4: String
My understanding is this:
Use "Optional" variables (?) when the variable may or may not be initialized at points in the future starting from initialization
Use "Implicitly Unwrapped Optionals" (!) when the variable is guaranteed to be initialized
Optionals can be converted to Implicitly Unwrapped Optionals via "Forced Unwrapping"
ex: let possibleString: String? = "Hello"
println(possibleString!)
Use "Lazy variables" when there is no need for something to be set until initialization (it seems these can be used with (?) or (!))
Therefore, my questions are:
When do I use option 1 - a variable without ? and without !
When do I use "lazy"
I read "lazy" is often used for singletons - why?
I have the most experience in Java and C++ terms, if that helps with my background for answering.
Edit: Here's everything I found (The main issue was "Normal" vs "Implicitly Unwrapped Optionals":
"Normal" variables must be initialized: (a) On the same line, (b) in the same scope before usage (Usage means some operation with the object), (c) by the end of the init iff the variable is a field. Note: The scope of init is everything in the scope of the class AND not in the scope of functions within the class.
Printing an Implicitly Unwrapped Optional will print "nil", but using the variable's functions will throw a runtime exception. Meanwhile, using (at all, including print) a Normal variable will not allow the program to compile at all
The purpose of using ! over "" (Nothing) is (a) More leniency since the program will compile (and run correctly given the variable is actually initialized) and (b) Lets you not initialize everything at the very beginning. Note: It is a compile time error to have any field undeclared if it is a Normal variable.
Not exactly that.
All variables must be initialised before the first use, and all class/struct stored properties must be assigned value in respective initialiser. Optionals are not about being allowed uninitalised at some point, but about being allowed to contain no value, which is represented by nil, which is still perfectly an initialised stated for such variable. Therefore, if something can not be known at the moment of initialisation then that's probably where you will use some sort of an optional (e.g. delegate for a view).
Implicitly unwrapped optionals is a sort of shorthand for cases when a variable might be empty, but we are absolutely sure that when we will be really using it it will hold an actual value (typical example is a property in a view controller that holds reference to a view).
Forced unwrapping does not convert optional into implicitly unwrapped optional, instead it gives you a value that is there if it's there (i.e. if optional is not nil), and throws an exception if it's not.
Lazy properties are used in cases when you want to defer their initialisation to a later stage, when the property is actually being used for first time. Usual case is if you need to access an expensive resource to do that (load huge file from disk, download it via network, etc), especially so if there might be cases when such property is not going to be used at all (why loading it from the disk if we will not use it probably?).
let's see Apple's example
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
Residence instances have a single Int property called numberOfRooms, with a default value of 1. Person instances have an optional residence property of type Residence?.
If you create a new Person instance, its residence property is default initialized to nil, by virtue of being optional.
1. If you need default value for property to be nil - use optional. Using variable without ? and ! - like 'numberOfRooms' -
You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property’s declaration. You specify a default property value by assigning an initial value to the property when it is defined.
NOTE
If a property always takes the same initial value, provide a default
value rather than setting a value within an initializer. The end
result is the same, but the default value ties the property’s
initialization more closely to its declaration. It makes for shorter,
clearer initializers and enables you to infer the type of the property
from its default value. The default value also makes it easier for you
to take advantage of default initializers and initializer inheritance.
2. ! is used to access the value wrapped inside variable when it is not nil, and throws exeption otherwise. So, you can use ! in order to make mark for users of you class - 'this value will not be nil at the time you unwrap it'
3. Lazy variable is used when you want to init it later, not at the time of whole object creation but exactly at the time you ask getter for data. this is useful when property stores an array, for example:
lazy var players: [String] = {
var temporaryPlayers = [String]()
temporaryPlayers.append("John Doe")
return temporaryPlayers
}()
When should I use lazy initialization?
One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized.
Short explanation:
A non optional variable has always a value and can never be nil.
The variable must be initialized in the init method or in the declaration line.
var a : String
var b = "bar"
init {
a = "foo"
}
An implicit unwrapped optional variable must not be initialized in the init method
or in the declaration line but is guaranteed to have always a value when it's used
var a : String!
func viewDidLoad() {
a = "Hello"
a += " world!"
}
An optional variable may have a value and is nil at declaration
var a : String? // = nil
A lazy variable is initialized later at the moment it's used the first time
class foo {
lazy var bar : String = {
return "Hello"
}()
}

Issues setting string to optional value

how can i pass the label inside the button to the next activity,
here is my code but it doesn't work
#IBOutlet weak var elecB: UIButton!
my prepareForSegue code
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var result:searchResultView = segue.destinationViewController as! searchResultView
if elecB.selected{
result.cat = elecB.titleLabel?.text!
}
}
it tells me there is an error in this line of code
result.cat = elecB.titleLabel?.text!
cat is a string
can any one help me, all i want to do is pass the label inside the button clicked to the next view controller
Change the declaration of titleLabel to titleLabel: UILabel! or titleLabel: UILabel, since you don't actually need it to be optional. It sounds like you'd reasonably expect for that label to exist all the time.
Making cat optional is also not the best solution, since you expect that string to always have a value. So leave cat as is, and make your title label non-optional, or implicitly unwrapped (!) if Xcode complains.
What do ? and ! mean?
A ? after a declaration means that that variable is optional, and can be reasonably excepted to be nil (this also allows you to set it to nil). You also have to follow the variable name with a ? every time you want to use it, or wrap it in an if let a = myOptionalVar {...}, so that code will only execute if the variable is not nil.
A ! after a declaration makes it an implicitly-unwrapped optional. This means that the variable can be nil, but is assumed to not be nil in most circumstances, so you don't have to follow it with an ! every time you want to use it. Note however, if the variable does happen to be nil when you try to use it, your program will crash.
! should only be used when you absolutely have to, because it is unsafe by nature. For example, if Interface Builder requires #IBOutlet variables to be optional, it is best to make them !, because they will be automatically initialised when your class is created from the storyboard, and will have a value for the rest of the time.
Using neither of these means that the variable is not optional, i.e. it must always have a value, and cannot be nil.
Check out the Swift documentation for the definition of optional variables (the ones with the ? at the end of the declaration.
If you define a variable like this var cat:String? then the variable is optional. That essentially means that the variable can have nil as a value.
From Apple's documentation:
You use optionals in situations where a value may be absent. An optional says:
- There is a value, and it equals x
or
- There isn’t a value at all
The example below uses the toInt() method to try to convert a String into an Int:
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int"
Because the toInt() method might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.)

Resources