What the difference between using or not using "!" in Swift? - swift

The ! mark is used for the optional value in Swift to extract the wrapped value of it, but the value can be extracted without the !:
var optionalString: String? = "optionalString"
println(optionalString)
another example using the !:
var optionalString: String? = "optionalString"
println(optionalString!)
both the codes above get the right value, so I wonder what's the difference between using and not using !, is it just for detect an error at runtime if the optional value is nil or something else? Thanks in advance.

As others have already stated, a really good place to start would be with the official documentation. This topic is extraordinarily well covered by the documentation.
From the official documentation:
Trying to use ! to access a non-existent optional value triggers a
runtime error. Always make sure that an optional contains a non-nil
value before using ! to force-unwrap its value.
println() is probably not the best way to test how the ! operator works. Without it, println() will either print the value or nil, with it it will either print the value or crash.
The main difference is when we're trying to assign our optional to another value or use it in an argument to a function.
Assume optionalValue is an optional integer.
let actualValue = optionalValue
Using this assignment, actualValue is now simply another optional integer. We haven't unwrapped the value at all. We have an optional rather than an integer.
Meanwhile,
let actualValue = optionalValue!
Now we're forcing the unwrap. Actual value will be an integer rather than an optional integer. However, this code will cause a runtime exception is optionalValue is nil.

Your question is answered in the book "The Swift Programming Language: iBooks
Download it and search it for "!".
You could've easily found the answer without having to ask here. For future reference, please always remember to look in the manual first.
From "The Swift Programming Language":
You can use an "if" statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to "true"; if it has no value at all, it evaluates to "false".
Once you're sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional's name. The exclamation mark effectively says, "I know that this optional definitely has a value; please use it." This is known as forced unwrapping of the optional's value.

I've never heard of Swift before now, but reading the documentation seems clear
"Using the ! operator to unwrap an optional that has a value of nil results in a runtime error."
If in your application nil is a valid and expected value in any normal circumstance and/or you want to trap and handle it in your code then I suggest that you don't use it. If you never expect it to be nil then use it as a debug aid. Runtime error suggest to me that your program will be terminated with a message reported by the OS.

Related

How can you get the default error string used when an optional-nil error is thrown?

We're implementing our own version of the .required() method on optionals where instead of simply force-unwrapping throwing an error, you get the file, function and line number of where the offense took place as well as a dev-supplied message of what went wrong.
The message itself is optional, so if the user doesn't specify it, we want ours to share the same message as Swift's default exception for force-unwrapping a nil optional. Their default text is this...
Unexpectedly found nil while unwrapping an Optional value
When not showing our custom message, we of course want ours to show the same text for log analysis. While we can simply hard-code the above string, I was wondering if there's a way to extract it from the built-in error. Something like this...
let ourMsg = UnexpectedNilError.localizedDescription
However, not sure what goes in place of UnexpectedNilError above, or if this is even possible. Not that big a deal. Just wondering if there are standard errors we can tap into here.
After a quick search on Swift's repo, the error message is found in the file Optional.swift line 314:
_preconditionFailure(
"Unexpectedly found nil while unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
It seems to be quite hardcoded as well, being passed directly as a parameter to _preconditionFailure, so it doesn't seem like you can get it as a string value in your code.

Why are null checks bad / why would I want an optional to succeed if it's null?

I've read more than a few answers to similar questions as well as a few tutorials, but none address my main confusion. I'm a native Java coder, but I've programmed in Swift as well.
Why would I ever want to use optionals instead of nulls?
I've read that it's so there are less null checks and errors, but these are necessary or easily avoided with clean programming.
I've also read it's so all references succeed (https://softwareengineering.stackexchange.com/a/309137/227611 and val length = text?.length). But I'd argue this is a bad thing or a misnomer. If I call the length function, I expect it to contain a length. If it doesn't, the code should deal with it right there, not continue on.
What am I missing?
Optionals provide clarity of type. An Int stores an actual value - always, whereas an Optional Int (i.e. Int?) stores either the value of an Int or a nil. This explicit "dual" type, so to speak, allows you to craft a simple function that can clearly declare what it will accept and return. If your function is to simply accept an actual Int and return an actual Int, then great.
func foo(x: Int) -> Int
But if your function wants to allow the return value to be nil, and the parameter to be nil, it must do so by explicitly making them optional:
func foo(x: Int?) -> Int?
In other languages such as Objective-C, objects can always be nil instead. Pointers in C++ can be nil, too. And so any object you receive in Obj-C or any pointer you receive in C++ ought to be checked for nil, just in case it's not what your code was expecting (a real object or pointer).
In Swift, the point is that you can declare object types that are non-optional, and thus whatever code you hand those objects to don't need to do any checks. They can just safely just use those objects and know they are non-null. That's part of the power of Swift optionals. And if you receive an optional, you must explicitly unpack it to its value when you need to access its value. Those who code in Swift try to always make their functions and properties non-optional whenever they can, unless they truly have a reason for making them optional.
The other beautiful thing about Swift optionals is all the built-in language constructs for dealing with optionals to make the code faster to write, cleaner to read, more compact... taking a lot of the hassle out of having to check and unpack an optional and the equivalent of that you'd have to do in other languages.
The nil-coalescing operator (??) is a great example, as are if-let and guard and many others.
In summary, optionals encourage and enforce more explicit type-checking in your code - type-checking that's done by by the compiler rather than at runtime. Sure you can write "clean" code in any language, but it's just a lot simpler and more automatic to do so in Swift, thanks in big part to its optionals (and its non-optionals too!).
Avoids error at compile time. So that you don't pass unintentionally nulls.
In Java, any variable can be null. So it becomes a ritual to check for null before using it. While in swift, only optional can be null. So you have to check only optional for a possible null value.
You don't always have to check an optional. You can work equally well on optionals without unwrapping them. Sending a method to optional with null value does not break the code.
There can be more but those are the ones that help a lot.
TL/DR: The null checks that you say can be avoided with clean programming can also be avoided in a much more rigorous way by the compiler. And the null checks that you say are necessary can be enforced in a much more rigorous way by the compiler. Optionals are the type construct that make that possible.
var length = text?.length
This is actually a good example of one way that optionals are useful. If text doesn't have a value, then it can't have a length either. In Objective-C, if text is nil, then any message you send it does nothing and returns 0. That fact was sometimes useful and it made it possible to skip a lot of nil checking, but it could also lead to subtle errors.
On the other hand, many other languages point out the fact that you've sent a message to a nil pointer by helpfully crashing immediately when that code executes. That makes it a little easier to pinpoint the problem during development, but run time errors aren't so great when they happen to users.
Swift takes a different approach: if text doesn't point to something that has a length, then there is no length. An optional isn't a pointer, it's a kind of type that either has a value or doesn't have a value. You might assume that the variable length is an Int, but it's actually an Int?, which is a completely different type.
If I call the length function, I expect it to contain a length. If it doesn't, the code should deal with it right there, not continue on.
If text is nil then there is no object to send the length message to, so length never even gets called and the result is nil. Sometimes that's fine — it makes sense that if there's no text, there can't be a length either. You may not care about that — if you were preparing to draw the characters in text, then the fact that there's no length won't bother you because there's nothing to draw anyway. The optional status of both text and length forces you to deal with the fact that those variables don't have values at the point where you need the values.
Let's look at a slightly more concrete version:
var text : String? = "foo"
var length : Int? = text?.count
Here, text has a value, so length also gets a value, but length is still an optional, so at some point in the future you'll have to check that a value exists before you use it.
var text : String? = nil
var length : Int? = text?.count
In the example above, text is nil, so length also gets nil. Again, you have to deal with the fact that both text and length might not have values before you try to use those values.
var text : String? = "foo"
var length : Int = text.count
Guess what happens here? The compiler says Oh no you don't! because text is an optional, which means that any value you get from it must also be optional. But the code specifies length as a non-optional Int. Having the compiler point out this mistake at compile time is so much nicer than having a user point it out much later.
var text : String? = "foo"
var length : Int = text!.count
Here, the ! tells the compiler that you think you know what you're doing. After all, you just assigned an actual value to text, so it's pretty safe to assume that text is not nil. You might write code like this because you want to allow for the fact that text might later become nil. Don't force-unwrap optionals if you don't know for certain, because...
var text : String? = nil
var length : Int = text!.count
...if text is nil, then you've betrayed the compiler's trust, and you deserve the run time error that you (and your users) get:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Now, if text is not optional, then life is pretty simple:
var text : String = "foo"
var length : Int = text.count
In this case, you know that text and length are both safe to use without any checking because they cannot possibly be nil. You don't have to be careful to be "clean" -- you literally can't assign anything that's not a valid String to text, and every String has a count, so length will get a value.
Why would I ever want to use optionals instead of nulls?
Back in the old days of Objective-C, we used to manage memory manually. There was a small number of simple rules, and if you followed the rules rigorously, then Objective-C's retain counting system worked very well. But even the best of us would occasionally slip up, and sometimes complex situations arose in which it was hard to know exactly what to do. A huge portion of Objective-C questions on StackOverflow and other forums related to the memory management rules. Then Apple introduced ARC (automatic retain counting), in which the compiler took over responsibility for retaining and releasing objects, and memory management became much simpler. I'll bet fewer than 1% of Objective-C and Swift questions here on SO relate to memory management now.
Optionals are like that: they shift responsibility for keeping track of whether a variable has, doesn't have, or can't possibly not have a value from the programmer to the compiler.

FIRAuth.auth() compiling error: "Cannot use optional chaining on non optional value 'FIRAuth'"

Cannot use optional chaining on non optional value 'FIRAuth'
I have tested every solutions, but always got the same error.
Even if i create a new project, when i'm using FIRAuth, i always got a compiling error.
Can someone help me please. I use Swift 2, Xcode 7, IOS9
If you are trying to add FIRAuth.auth()? try to remove (?).
FIRAuth.auth() is non optional so treating them as one might result to the error “Cannot use optional chaining on non optional value 'FIRAuth'”
Optional chaining is a process for querying and calling properties,
methods, and subscripts on an optional that might currently be nil
Check Optional Chaining

Terminology of Optionals in Swift or other languages

In Swift the elements we manipulates all have types.
When we use theses types, we can add a '!', '?' or nothing to express their nullability.
What shall I call the '?' or '!' used to express this trait ?
A type decorator ? A decorator ? Operator ? Something else ?
What shall I call the type created when using this character ?
Is it a new type ? Is it a decorated type ? A type variation ?
The swift compiler, seems to consider them as new types, However my question is not implementation or language dependent and therefor I tagged it as language agnostic.
Edit: I'm looking for a language agnostic name. I understand with pranjalsatija's comment optionals are defined as compound type.
However, this is a language implementation detail.
I could rephrase my questions as:
What do you call a character with a special meaning when used it a type definition, and how to call the derived type.
This term should probably apply to capital casing constants in ruby as the concept is similar.
? on the end of the type isn’t a decorator or operator. It’s hardcoded syntactic sugar in Swift that allows you to shorten Optional<Thing> to Thing?.
The ? doesn’t really have a name (at least I’ve never heard anyone on the Swift team use one), in the language reference it’s just described as “the postfix ?”. The language grammar doesn’t put it in a syntactic category.
Similarly, [Thing] is shorthand for Array<Thing>, but there isn’t a name for the square brackets in this context.
Describing Option<Int> as “derived from” Int would be to misuse the term “derived”. You can if you want describe it as “Optional specialized for Int”.
In fact you may be looking for the language-agnostic term for how Swift allows you to build types (like Optional<T> or Array<T>) that apply to any kind of type T without having to care what T actually is. In which case the term would probably be generics.
! is a little different. When applied to a type name as in Thing!, it’s shorthand for ImplicitlyUnwrappedOptional<Thing>, in the same manner as ?.
! when applied to a variable of type Thing? is equivalent to a postfix operator that tests the optional and if it is nil, terminates your program, something like this:
postfix operator !<T>(value: T?) -> T {
if let unwrapped = value {
return unwrapped
}
else {
fatalError("unexpectedly found nil while unwrapping an Optional value")
}
}
so in this context, ! can be described as an operator. But not in the first context.
For the terminology a given language uses to describe optionals, see the Option type wikipedia page.
Optionals in Swift technically are completely different types, not variations of the same type. However, to a developer, they seem to be variations, so we'll treat them as such. The ? and the ! don't really have a set, specified name just yet, at least not that I know of. In a sense, you shouldn't be calling them type decorators, because optionals are really new types on their own. So to answer your question, the ? and the ! are parts of a type's name, more than anything else. And the new type created when using a ? or an ! is just that. A brand new type.
The type created using '?' is an Optional and '!' is an Implicitly Unwrapped Optional
I think the answer here may help you out, they refer to both as decorations
Here's a larger explanation about exclamation marks
And here's one for question marks

What use does the new as! operator have?

I don't quite understand what new functionality the as! operator is supposed to add.
Apple's documentation says:
The as! operator performs a forced cast of the expression to the specified type. The as! operator returns a value of the specified type, not an optional type. If the cast fails, a runtime error is raised. The behavior of x as! T is the same as the behavior of (x as? T)!.
It seems that using as! only makes sense, when you know that the downcast will be successful, because otherwise a runtime error will be triggered. But when I know that the downcast will be successful I just use the as operator. And since neither as! nor as return an optional they even return the exact same type.
Maybe I'm missing something, but what's the point?
The as (no bang) operator is for casts that are guaranteed by the language to succeed — primarily, that means casts from a subtype to one of its ancestor types.
The as! and as? operators are for casts that the language can't guarantee will succeed. This comes into play when you have a general type and want to treat it as a more specific subtype. The compiler doesn't know which subtype might really be hiding behind the general type — that information can be decided at run time — so as far as the language knows, there's a possibility of the cast failing.
The difference between as? and as! is how that failure is handled. With the former, the result of the cast gets wrapped in an optional, forcing you to yeast for the failure and allowing you to handle it in a way that makes sense to your app. The latter assumes the cast will succeed, so you aren't forced to check for failure—you'll just crash if your assumption turns out to be wrong.
So why use as!? It fills the same role as the Implicitly Unwrapped Optional: you can use it (at your own risk) for situations where some behavior is "guaranteed" by some factor external to the language (even if the language itself can't guarantee it), allowing you to skip having to write code to test for failures you don't expect to happen. One of the most common cases of such is when you're depending on the runtime behavior of another class — the language doesn't say that the subviews array of a UIView must contain other UIViews, but its documentation assures you that it will.
Before Swift 1.2, there was no as! — as included both cases that could crash and cases that couldn't. The new operator requires you to be clear about whether you're doing something that will always succeed, something you expect to always succeed, and something you plan to test for failure.
There are cases where you as a programmer can know that as would succeed, but the compiler can't be sure of it. In such cases, as is a compile-time error, but as! will compile.