Error to use a shorter spelling to unwrap a value - ios

in Swift documentation at https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html, there are examples about usage of optionals and unwrapping them. When I try the examples on my Macbook, I got an error as; "Variable binding in a condition requires an initializer".
Defining the variables part in document:
let nickname: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickname ?? fullName)"
Explanation and example parts which throws the error written above:
You can use a shorter spelling to unwrap a value, using the same name for that unwrapped value.
if let nickname {
print("Hey, \(nickname)")
}
Why I cannot use if let nickname and if it throws error, why it is written in the documentation?

The shorthand syntax for optional unwrapping with if let, guard let and while let was introduced in swift 5.7. I believe u are using an older version of swift.
Check this to find out which version of swift u are using.
For more details read the section Language updates -> Quality of life improvements.

Related

Firebase stored key is wrapped inside Optional(\" \") when doing a nested write

No longer a question now. I re-edit this to explain what happened:
I did a nested write like this
let key: String!
key = "foo"
let dict = ["Zoes": "7th Street"]
ref.child("/\(key)/shops").setValue(dict)
This results in key of "foo" becoming: "Optional(\"foo\")" as a String stored in firebase.
So I thought since key is declared as implicitly unwrap, it would just unwrap in the string interpolation. But turned out the string was not forced unwrapped during string interpolation, that's why it's got "Optional" written. It's not a firebase issue now, it's just how String interpolation works in Swift.

Nil is not compatible with expected argument type 'String'

I am currently converting my swift 2.3 code to swift 3 and I am getting the above error on the following line:
setSharedPassword(nil, account: account, completion: completion)
Would the appropriate solution be just to replace nil with ""? The error goes away when I do it. I am looking for an explanation. Please help.
If your setSharedPassword func's first parameter is of type String then you will not be able to set this as nil because it is not optional. If you want to be able to set it as nil, then you could do something like this for your func:
func setSharedPassword(string: String?, account: ...)
The reason why "" works is because it is still a value for a String, just a value that has no characters.
Of course this answer is assuming this is your own func. If setSharedPassword is not yours, then you either need to come up with a String that represents no password, or just supply "" as before.

NSUTF8StringEncoding result encoded string with 'Optional' string

I'm using NSUTF8StringEncoding to encode some text inputs, the inputs get encoded and the resulting string contain a 'Optional'. An example worked out is available here.
What does that encoded string with 'optional' really mean?
Does that have any significant role?
The thing you have to understand is that an optional is a different data type than the required object it contains. An optional "wraps" or contains some other object. The optional can either be empty, represented by nil, or it can contain another object.
Internally an optional is an enum that has 2 values, Some and None. The Some case has an associated value. Optionals are generics. The associated value stored in the Some case (non empty) can be any type, and that determines the type of the optional.
If you print an optional, you see the container AND the value stored inside, or you see nil (since a nil optional does not contain anything.)
let aString:String? = "Foo"
println("aString = \(aString)")
Displays something like
optional("Foo")
That's because aString is not a String optional, it is an optional that contains a string.
optional variables are variables that can may or may not have a value.
Looking at your example here
we can see data has type NSData?
unlike objective-c where we can happily send messages to nil values we need to make sure the 'data' definitely has a value before we can use it
if you are sure it will have a value you can unwrap it explicitly like this
let myString = "encode me"
let data : NSData? = myString.dataUsingEncoding(NSUTF8StringEncoding)
data!.someNSDataFunction()
This will crash if data is nil.To safely unwrap it you can can do this
if let actualData = data
{
actualData.someNSDataFunction()
}
else
{
println("data has not been set")
}

Nil-coalescing to provide default values in Swift 1.2

Previously (i.e. prior to Swift 1.2) I've used code like this:
self.name = jsonDictionary["name"] as? String ?? "default name string here"
I've found this to be a readable but concise way of:
getting a value from a dictionary
checking it's of the type I'm expecting
assigning a default value
However in Swift 1.2, I get this compiler error:
Consecutive statements on a line must be separated by ';'
I can't see anything in the Xcode 6.3 release notes or the Apple Swift Blog about this.
Seems you now have to use brackets:
self.name = (jsonDictionary["name"] as? String) ?? "default name string here"

Swift NSString function syntax usage

I have a basic question about swift function calling syntax. I have read documentation but not able to figure it out. So decided to put a query over here.
A piece of code i wrote
var string1 = NSString().stringByAppendingString("First string")
var string2 = NSString.stringByAppendingString("Second string")
println(string1)
println(string2)
Both string have same function calling but return type is different. And only difference here is (). I got out put like
First string
(Function)
Question is why its not giving a warning/error. Is it that var string2 holds method body of stringByAppendingString? Whats going on, New swift developer like me can easily make a this type of typo mistake and not able to figure out.
Can you please explain why its not return value?
This happens because swift methods are curried functions (you can find detailed explanation in Ole Begemann's post).
So what you actually got in the following line:
var string2 = NSString.stringByAppendingString("Second string")
is a function that takes a string as parameter and returns the result of
"Second string".stringByAppendingString(parameter)
You can check that by calling string2 as an ordinary function:
string2("123")
// Prints: "Second string123"

Resources