'Swift: How to call a method located in ViewController from @main located in AppDelegate?
I´m new to Swift and struggling with the entry point.
Used versions: Swift 5.5.2 + IOS 15.3.1
I´ve created a method in ViewController which simply should show a word in a label. This method have to be called from a main function. According to my understanding the main function has to be implemented in AppDelegate after @main.
Following my code.
AppDelegate:
@main struct myApp {
static func main(){
let newClass = ViewController()
newClass.viewText()
}
}
ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func viewText() {
let word = "hello"
labelText.text = String(word)
}
}
By running the App I get the following error message which occurs in the line labelText.text = String(word):
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Your help is really appreciated.
Solution 1:[1]
As already pointed out in the comments of your question, the @main is not meant for UI development, it is for CLI development (Command Line Interface).
I am not 100% sure what you mean with that you have a label which has a method that needs to be run on main, so I'm making some assumptions here on what you mean. If you mean that the label should be tappable and run an action, then I would recommend you use an UIButton for that.
Maybe you've heard somewhere that all UI needs to be run on Main and this is what you've meant, than I would say that at this stage you don't need to worry about that. By default the app is run on main, unless you actively do something to change this. Please forgive me in assuming this, but my assumption is that you are rather new to iOS development and so I would like to suggest that you get familiar with the basics first; e.g. setting up a basic UI and pressing a button with an action.
I would suggest you start off with building a simple Hello, World! iOS application and take it from there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
