Facing Errors & Warnings in Swift 5 !!? Checkout the fixes, if that got listed here.
It is but natural for a developer to come across the errors and warnings during the development of an application regardless of number of years they have been working with any technologies. Finding and fixing errors and warnings may take a minute or may take days based on the complexity of the code and various other factors.
So, to help you out a little with fixes to some of the known errors and warnings, I am making here a list of the possible compile time errors and warnings that any swift developer might come across while working for an iOS Application. List includes an example with error or warning and a possible solution to fix it.
Check it out from the list of errors or warnings that you commonly see while working with the iOS development in Swift 5.0 and might finding it difficult to figure out the reason behind the error. Add in comment other errors or warnings that you might have seen and have a solution for it.
1. Error: Cannot use mutating member on immutable value: ‘shoppingList’ is a ‘let’ constant
Sample Code:
let shoppingList = ["Biscuits", "Mangoes", "Chocolates"]
shoppingList.append("Milk")
shoppingList.append("Bread")
Solution:
In swift defining variable can be done like this
var myVariable: Type = Value
Defining the constant can be done by use of let keyword
let myConstant: Type = Value
so, to fix the error, we should change the shoppingList array to variable
var shoppingList = ["Biscuits", "Mangoes", "Chocolates"]
shoppingList.append("Milk")
shoppingList.append("Bread")
2. Error: Empty collection literal requires an explicit type
Sample Code:
let emptyArray = []
Solution:
There are two ways to define the empty array
let emptyArray = [String]()
OR, by using the shorthand, that will need to pass the explicit type of the array, it is difficult for the compiler at the time of defining array to infer the type of the array, because type can be of anything like String, Int, Double etc..
So, this is the proper way to define the array and fix the error “Empty collection literal requires an explicit type”
let emptyArray: [String] = []
3. Error: Use of unresolved operator ‘++’; did you mean ‘+= 1’?
Sample Code:
var incrementer = 0
incrementer++
Solution:
++ & — operators are removed in advanced version of swift, You can use += 1 and -= 1 etc.. to perform the addition, subtraction or multiple the actual variable with some value.
var incrementer = 0
incrementer += 1
4. Error: ‘nil’ cannot initialize specified type ‘String’
Sample Code:
let nickName: String = nil
nil values can be assigned only to optional type of variable or constant.
let nickName: String? = nil
5. Warning: Left side of nil coalescing operator ‘??’ has non-optional type ‘String’, so the right side is never used
Sample Code:
let nickName: String = "Brave"
let fullName: String = "John Appleseed"
let informalGreeting = "Hello \(nickName ?? fullName)"
Solution:
This warning, when you passing the left part of the nil coalescing operator as non optional value. The use of nil coalescing operator is to pass some default value when the left part of the operator is nil.
You can use it only with the optional variables, so changing the type of nickname to String? will fix this warning.
let nickName: String? = "Brave"
let fullName: String = "John Appleseed"
let informalGreeting = "Hello \(nickName ?? fullName)"
6. Error: Switch must be exhaustive
Sample Code:
let iAmLetter = "A"
switch iAmLetter {
case "A":
print("This is letter A")
case "B":
print("This is letter B")
}
Solution:
Switch must have some default case which can be executed if non of the other cases gets match.
let iAmLetter = "A"
switch iAmLetter {
case "A":
print("This is letter A")
case "B":
print("This is letter B")
default:
print("This is some other letter")
}
7. Error: Anonymous closure argument not contained in a closure
Sample Code:
let numbers = [3, 2, 4, 1]
numbers.map($0 * 2)
Solution:
Closure without the name can be written by ({}).
So, there is missing {} in above code, which a compiler trying to explain.
let numbers = [3, 2, 4, 1]
numbers.map({$0 * 2})
8. Warning: String interpolation produces a debug description for an optional value; did you mean to make this explicit?
Sample Code:
func simpleDescription() {
let name: String? = "John"
print("This is \(name)")
}
Solution:
Use ‘String(describing:)’ to silence this warning
func simpleDescription() {
let name: String? = "John"
print("This is \(String(describing: name))")
}
OR
Provide a default value to avoid this warning
func simpleDescription() {
let name: String? = "John"
print("This is \(name ?? “Unknown”)")
}
9. Error: Cannot force unwrap value of non-optional type ‘String’
Sample Code:
var nonOptionalString: String = ""
print(nonOptionalString!)
Solution:
You cannot force unwrap a variable of non-optional type. Force unwrapping means, adding ‘!’ at the end of the optional variable, when you are sure that there exists the value in it. If you are not sure about the presence of the value in an optional variable you can use, if let or guard else
var nonOptionalString: String = ""
print(nonOptionalString)
10. Error: Variable ‘nameOfVariable’ used before being initialized
Sample Code:
let newVariable: String = "Hello"
var nameOfVariable: String
var combinedVariable = newVariable + nameOfVariable
print(combinedVariable)
Solution:
You cannot use a variable or constant, before initializing it. Initializing a variable or a constant means providing some initial value to it. As you can see in variable named newVariable, we have assigned “Hello” to it. So, to fix the error, we can set some blank value to nameOfVariable
let newVariable: String = "Hello"
var nameOfVariable: String = ""
var combinedVariable = newVariable + nameOfVariable
print(combinedVariable)
11. Error: Left side of mutating operator isn’t mutable: ‘self’ is immutable
Sample Code:
struct SimpleStruct {
var simpleDecription: String = "This is struct"
func adjust() {
simpleDecription += " added new text"
}
}
Solution:
Mark method ‘mutating’ to make ‘self’ mutable for the structure. The declaration of class doesn’t need any of its methods marked as mutating because methods on a class can always modify the class.
struct SimpleStruct {
var simpleDecription: String = "This is struct"
mutating func adjust() {
simpleDecription += " added new text"
}
}
12. Error: Type ‘Int’ does not conform to protocol ‘ExampleProtocol’
Sample Code:
protocol ExampleProtocol {
var simpleDecription: String { get }
mutating func adjust()
}
extension Int: ExampleProtocol {}
Solution:
Conforming to protocol means implement all the required methods available in a protocol to the class, struct or type you a.
struct SimpleStruct {
var simpleDecription: String = "This is struct"
mutating func adjust() {
simpleDecription += " added new text"
}
}
13. Error: Extensions must not contain stored properties
Sample Code:
extension Int {
var simpleDecription: String = "This is \(self)"
}
Solution:
Use extension to add functionality to an existing type, in above example, I added simpleDescription variable to extend the functionality of Int, If you call simpleDescription from instance of type Int, it will print the string “This is VALUE OF INT”, But stored property is not allowed in the extension, so we will use computed property and can get the desired results.
extension Int {
var simpleDecription: String {
return "This is \(self)"
}
}
14. Error: Missing return in a function expected to return ‘String’
Sample Code:
func getName() -> String {
let myName: String = "Bhavin”
print(myName)
}
Solution:
If function is returning something, it must return the value of expected type. In getName function, it is expecting to return a value of type String, but we are returning nothing there, so was the error. It can be fixed by returning a String as per follows
func getName() -> String {
let myName: String = "Bhavin”
print(myName)
return myName
}
15. Error: Computed property must have an explicit type
Sample Code:
extension Double {
var ceilDescription{
return “Ceil Value of \(self) is \(ceil(self))”
}
}
Solution:
We can keep the variable explicitly typed when we are sure about the type of the variable, e.g. var year = 2019, here compiler can identify the type and behind the scene, sets type of year to Int. Compiler can inferred the type of variables but when it comes to extension, we have to specify it explicitly.
extension Double {
var ceilDescription: String {
return "Ceil Value of \(self) is \(ceil(self))"
}
}
And list goes on… This is not the end, it’s just a beginning!. There are many more errors and warnings that you might have came across during your development phase. So, keep adding in comment to expand this list to help iOS Developers with quick fixes.