Swift- Variable Not Initialized Before Use (But It's Not Used)

Why latest Swift version always says variable is not initialized before use

viewDidLoad is not the equivalent of init

I suggest you either use optionals:

var a:Int?

or you can initialize your variable directly in its declaration

var a:Int = 0

Last but not least, if you want to initialize any other way, do it in the init

override init() {
super.init()

a = 0
}

How can I check if a variable is not initialized in Swift?

You're right—you may not compare a non-optional variable to nil. When you declare, but do not provide a value for, a non-optional variable, it is not set to nil like an optional variable is. There is no way to test for the use of an uninitialized non-optional variable at runtime, because any possibility of such use is a terrible, compiler-checked programmer error. The only code that will compile is code that guarantees every variable will be initialized before its use. If you want to be able to assign nil to a variable and check its value at runtime, then you must use an optional.

Example 1: Correct Usage

func pickThing(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here...

if choice {
variable = "Thing 1"
} else {
variable = "Thing 2"
}

print(variable) //...but this is okay because the variable is definitely set by now.
}

Example 2: Compilation Error

func pickThing2(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here, but...

if choice {
variable = "Thing 1"
} else {
//Uh oh, if choice is false, variable will be uninitialized...
}

print(variable) //...that's why there's a compilation error. Variables ALWAYS must have a value. You may assume that they always do! The compiler will catch problems like these.
}

Example 3: Allowing nil

func pickThing3(choice: Bool) {
let variable: String? //Optional this time!

if choice {
variable = "Thing 1"
} else {
variable = nil //Yup, this is allowed.
}

print(variable) //This works fine, although if choice is false, it'll print nil.
}

False error? `Variable used before being initialized` DURING initialization in init()

This code:

@State var greeting: String

Creates a backing variable behind the scenes:

let _greeting: State<String>

If you want to initialize it yourself in init(), you can do:

init() {
_greeting = new State<String>(initialValue: "Hello, World!")
}

but since you have a constant, it is simpler to set it like this:

@State var greeting: String = "Hello, World!"

The 3rd variant works, because without @State there's no magic.

The 1st option doesn't work, because the code gets translated to:

init() {
self._greeting.wrappedValue = "Hello, World!"
}

and _greeting is not initialized at this point (no initialValue is specified). Yes, the error is misleading.

I don't know why the 2nd version works. No initialValue is specified, and the String has no implicit default value. Maybe this is a new feature of iOS 15 SwiftUI that should work, but doesn't work in all cases due to some limitations?

P.S. There is something like "preinit": all properties that are assigned with some expressions like length = Measurement<UnitLength>(...) are run there before init, but there's no access to it, it is internal.

Variable is used before initialized when @Environment(\.dismiss) is used

A @State var has to be initialised differently:

self._myInt = State(initialValue: foo)

How to declare but not initialize a property in a Swift class

Create an implicitly unwrapped optional - this will act like a normal variable but it does not need to be initialised - its initial value is nil. Just ensure the value is set before it is used otherwise you will get a fatal error for unwrapping nil.

class car {
var oneWheel: Wheel!

func run(inputWheel: Wheel) {
wheel = inputWheel
}
}

variable used before being initialized

This is because of the way of initialising variables in Swift, In Swift Class each property need some default value before being used.

Class initialisation in Swift is a two-phase process. In the first
phase, each stored property is assigned an initial value by the class
that introduced it. Once the initial state for every stored property
has been determined, the second phase begins, and each class is given
the opportunity to customize its stored properties further before the
new instance is considered ready for use.

Try changing your code as below:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController = segue.destinationViewController as! SecondTableViewController
var secondArrays : SecondTableData?

if let indexPath = self.tableView.indexPathForSelectedRow {
secondArrays = secondArrayData[indexPath.row]

//Here you're making sure that the secondArrays would must have a value
destViewController.secondArray = secondArrays.secondTitle
}

}


Related Topics



Leave a reply



Submit