Issues setting string to optional value - ios

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.)

Related

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.

Stored property initialisation for non optional

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.

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"
}()
}

What the difference when declaring these variables in swift using ! or ()

What is the difference of declaring variables this way?
var contacts: [Person]!
var contacts = [Person]()
By using var contacts: [Person]! you don't actually initialize a Person array.
var contacts: [Person]! // contacts still nil
var contacts = [Person]() // Person array with 0 objects
If you use () instead you initialize an empty Person array.
Variable declarations in Swift take the following form:
var name: Type = initialValue
That is, you declare a variable called name of some Type, and set it to an initialValue.
There are many shorthand forms though, so you will see various alternatives. The one you see the most often is leaving off the Type part. If you do, then the type of name is “inferred” from the initialValue.
This is what is happening with var contacts = [Person](). The type is an Array of Person. The () is calling the initializer (i.e. creating the array).
Alternatively, you can declare a variable, with a type, but not give it an initial value. But the compiler won’t let you use it until you are guaranteed to have set it with an initial value. So for example, you could write var contacts: [Person], then later contacts = [Person]().
When you write var contacts: [Person]!, with a !, you are declaring a variable of type Optional<[Person]> – that is, a type that can either be nil, or contain an array. Unlike regular arrays, optionals of arrays have a default value if you don’t initialize them. The default value is nil – that is, that the optional does not contain an array.
But the ! (instead of the more common ?) means it is declared to be a special kind of optional, called an “implicitly-unwrapped optional” – that is, an optional that, when you use it in certain ways, will act as if it isn’t optional. The big downside of this is that it will let you use it as if it isn’t an optional. But if you do and it is nil then your program will crash. So before anyone uses contacts, it will need to be initialized (such as with contacts = [Person]() or assigning some existing array to it)
For this reason, it’s best to not use these implicitly-unwrapped optionals except in very specific circumstances. They sometimes seem like they’re convenient but they’re usually not the best option as they’re dangerous.
The operator : is not declaring, its just saying which type a variable is
Operator = is as in every other language a declaring operator which in this case followed by the () which in this case declared a new array of Person.
Other people provided the differences, I'll give you the scenarios of when either should be used.
var contacts: [Person]! //implicitly unwrapped optional. #1
var contacts = [Person]() //array initialization. #2
I use #1 when I create a variable that won't be initialized by it's own class. This situation occurs when I implement a detail view that takes in information that is passed by another controller.
For #2, use when you want to initialized a new empty array.

if let acting weird when explicitly specifying type

Let's say we have:
let a:Int? = nil
// block not executed - unwapping done, type is inferred
if let unwrapped_a = a {
println(unwrapped_a)
}
// block not executed - unwrapping done, type is specified
if let unwrapped_a:Int = a {
println(unwrapped_a)
}
// block gets executed - unwrapping not done, new local constant + assignment is done instead?
if let not_unwrapped_a:Int? = a {
println(not_unwrapped_a)
}
So should I assume that Swift does an unwrapping in the first case, but an assignment in the second case?
Isn't this syntax a bit too close to create confusion? I mean, yes, the compiler warns you that you're using an optional type when working with not_unwrapped_a, but still.
Update:
So after Airspeed Velocity's answer I found another (but actually the same) weird case:
if let not_unwrapped_a:Int???? = a {
println(not_unwrapped_a)
}
a will be silently wrapped in an Int????. So it will be a type of Int????? (five) - because a was already an optional. And then it will get unwrapped once.
Case 1 and case 2 are identical – they are both assignments of the contents of a to a new variable. The only difference is you are leaving Swift to infer the type of unwrapped_a in option 1, whereas you’re manually giving the type in option 2. The main reason you’d ever need to do option 2 is if the source value were ambiguous – for example if it were an overloaded function that could return multiple types.
Case 3 is quite interesting.
Whenever you have a value, Swift will always be willing to silently upgrade it to an optional wrapping the value, if it helps make the types match and the code compile. Swift auto-upgrading of types is fairly rare (it won’t implicitly upgrade an Int16 to an Int32 for example) but values to optionals is an exception.
This means you can pass values wherever an optional is needed without having to bother to wrap it:
func f(maybe: Int?) { ... }
let i = 1
// you can just pass a straight value:
f(i)
// Swift will turn this into this:
f(Optional(i))
So in your final example, you’ve told Swift you want not_unwrapped_a to be an Int?. But it’s part of a let that requires a to be unwrapped before it’s assigned to it.
Presented with this, the only way Swift can make it work is to implicitly wrap a in another optional, so that’s what it does. Now it is an optional containing an optional containing nil. That is not a nil-valued optional - that is an optional containing a value (of an optional containing nil). Unwrapping that gives you an optional containing nil. It seems like nothing happened. But it did - it got wrapped a second time, then unwrapped once.
You can see this in action if you compile your sample code with swiftc -dump-ast source.swift. You’ll see the phrase inject_into_optional implicit type='Int??’. The Int?? is an optional containing an optional.
Optionals containing optionals aren’t obscure edge cases - they can happen easily. For example if you ever for…in over an array containing optionals, or used a subscript to get a value out of a dictionary that contained optionals, then optionals of optionals have been involved in that process.
Another way of thinking about this is if you think of if let x = y { } as kind of* like a function, if_let, defined as follows:
func if_let<T>(optVal: T?, block: T->()) {
if optVal != nil {
block(optVal!)
}
}
Now imagine if you supplied a block that took an Int? – that is, T would be an Int?. So T? would be a Int??. When you passed a regular Int? into if_let along with that block, Swift would then implicitly upgrade it to an Int?? to make it compile. That’s essentially what’s happening with the if let not_unwrapped_a:Int?.
I agree, the implicit optional upgrade can sometimes be surprising (even more surprising is that Swift will upgrade functions that return optionals, i.e. if a function takes an (Int)->Int?, it will upgrade an (Int)->Int to return an optional instead). But presumably the feeling is the potential confusion is worth it for the convenience in this case.
* only kind of
The purpose of the optional binding is to check an optional for not nil, unwrap and assign to a non optional of the type enclosed in the optional. So in my opinion the 1st case is the correct way of using it - the only variation I would use is adding an optional cast (useful for example when the optional contains AnyObject).
I wouldn't use the 2nd case, preferring an optional cast:
if let unwrapped_a = a as? Int { ... }
unless, as noted by #drewag in comments, the type is explicitly specified to avoid ambiguities when it's not clear.
In my opinion the 3rd case should generate a compilation error. I don't see any use of optional binding to assign an optional to another optional. Optional binding is not a generic inline assignment (such as if let x = 5 {...}), so conceptually it should not work if the left side is an optional - it should be handled the same way as if the right side is not an optional (for which compilation fails instead).

Resources