Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html> element to the output stream. You'd have to move the session_start() to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>. It is considered a standard practice to omit ?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
Best Solution
This answer is community wiki. If you feel it could be made better, feel free to edit it!
Background: What’s an Optional?
In Swift,
Optional<Wrapped>is an option type: it can contain any value from the original ("Wrapped") type, or no value at all (the special valuenil). An optional value must be unwrapped before it can be used.Optional is a generic type, which means that
Optional<Int>andOptional<String>are distinct types — the type inside<>is called the Wrapped type. Under the hood, an Optional is an enum with two cases:.some(Wrapped)and.none, where.noneis equivalent tonil.Optionals can be declared using the named type
Optional<T>, or (most commonly) as a shorthand with a?suffix.Optionals are a simple yet powerful tool to express your assumptions while writing code. The compiler can use this information to prevent you from making mistakes. From The Swift Programming Language:
Some other programming languages also have generic option types: for example, Maybe in Haskell, option in Rust, and optional in C++17.
In programming languages without option types, a particular "sentinel" value is often used to indicate the absence of a valid value. In Objective-C, for example,
nil(the null pointer) represents the lack of an object. For primitive types such asint, a null pointer can't be used, so you would need either a separate variable (such asvalue: IntandisValid: Bool) or a designated sentinel value (such as-1orINT_MIN). These approaches are error-prone because it's easy to forget to checkisValidor to check for the sentinel value. Also, if a particular value is chosen as the sentinel, that means it can no longer be treated as a valid value.Option types such as Swift's
Optionalsolve these problems by introducing a special, separatenilvalue (so you don't have to designate a sentinel value), and by leveraging the strong type system so the compiler can help you remember to check for nil when necessary.Why did I get “Fatal error: Unexpectedly found nil while unwrapping an Optional value”?
In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.
Xcode will show you the crash by highlighting a line of code. The problem occurs on this line.
This crash can occur with two different kinds of force-unwrap:
1. Explicit Force Unwrapping
This is done with the
!operator on an optional. For example:As
anOptionalStringisnilhere, you will get a crash on the line where you force unwrap it.2. Implicitly Unwrapped Optionals
These are defined with a
!, rather than a?after the type.These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.
In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type.
IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be
nilat runtime, and therefore crash when they are implicitly unwrapped. When fixing connections, try deleting the lines of code that define your outlets, then reconnect them.When should I ever force unwrap an Optional?
Explicit Force Unwrapping
As a general rule, you should never explicitly force unwrap an optional with the
!operator. There may be cases where using!is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value.While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead.
Implicitly Unwrapped Optionals
These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.
You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional.
However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution.
How can I safely deal with Optionals?
The simplest way to check whether an optional contains a value, is to compare it to
nil.However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding.
Optional Binding
Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax
if let x = anOptional {...}orif var x = anOptional {...}, depending if you need to modify the value of the new variable after binding it.For example:
What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (
number) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect.What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped.
Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it.
The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement.
A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax
guard condition else {...}.So, to use them with an optional binding, you can do this:
(Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code).
If
anOptionalIntcontains a value, it will be unwrapped and assigned to the newnumberconstant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed.The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements.
For example:
Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the
whereclause.Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value.
Nil Coalescing Operator
The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax
a ?? b, whereais an optional type andbis the same type asa(although usually non-optional).It essentially lets you say “If
acontains a value, unwrap it. If it doesn’t then returnbinstead”. For example, you could use it like this:This will define a
numberconstant ofInttype, that will either contain the value ofanOptionalInt, if it contains a value, or0otherwise.It’s just shorthand for:
Optional Chaining
You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a
?when using it.For example, say we have a variable
foo, of type an optionalFooinstance.If we wanted to call a method on
foothat doesn’t return anything, we can simply do:If
foocontains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing.(This is similar behaviour to sending messages to
nilin Objective-C)This can therefore also be used to set properties as well as call methods. For example:
Again, nothing bad will happen here if
fooisnil. Your code will simply continue executing.Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to
nil.(This is because an optional value will return
Void?rather thanVoidon a method that doesn’t return anything)For example:
However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because
foois optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrapfooitself before accessing methods or calling methods that return values.Also, as the name suggests, you can ‘chain’ these statements together. This means that if
foohas an optional propertybaz, which has a propertyqux– you could write the following:Again, because
fooandbazare optional, the value returned fromquxwill always be an optional regardless of whetherquxitself is optional.mapandflatMapAn often underused feature with optionals is the ability to use the
mapandflatMapfunctions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remainnil.For example, let’s say you have an optional string:
By applying the
mapfunction to it – we can use thestringByAppendingStringfunction in order to concatenate it to another string.Because
stringByAppendingStringtakes a non-optional string argument, we cannot input our optional string directly. However, by usingmap, we can use allowstringByAppendingStringto be used ifanOptionalStringhas a value.For example:
However, if
anOptionalStringdoesn’t have a value,mapwill returnnil. For example:flatMapworks similarly tomap, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself.try!Swift's error handling system can be safely used with Do-Try-Catch:
If
someThrowingFunc()throws an error, the error will be safely caught in thecatchblock.The
errorconstant you see in thecatchblock has not been declared by us - it's automatically generated bycatch.You can also declare
erroryourself, it has the advantage of being able to cast it to a useful format, for example:Using
trythis way is the proper way to try, catch and handle errors coming from throwing functions.There's also
try?which absorbs the error:But Swift's error handling system also provides a way to "force try" with
try!:The concepts explained in this post also apply here: if an error is thrown, the application will crash.
You should only ever use
try!if you can prove that its result will never fail in your context - and this is very rare.Most of the time you will use the complete Do-Try-Catch system - and the optional one,
try?, in the rare cases where handling the error is not important.Resources