无法在 View Controller 和 Model 之间传递数据

Can't pass data between View Controller and Model

我的视图控制器中有带有文本字段的 UIAlertController。当用户输入城市名称时,当我获得该城市的坐标时,此数据必须传输到模型。但我无法将城市名称从 View Controller 传递到 Model

我的 UIAlertController:

class MainScrenenViewController: UIViewController {
    
    var delegate: ILocationGroup?

    @objc func locationButtonTap() {
        let alert = UIAlertController(title: "Add city", message: nil, preferredStyle: .alert)
        let addButton = UIAlertAction(title: "Add", style: .default) { action in
           
            self.delegate?.addLocation(alert.textFields?.first?.text ?? "No City")
            
        }
        
        alert.addAction(addButton)
        let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alert.addAction(cancelButton)
        
        alert.addTextField { textField in
            textField.placeholder = "Your City"
        }
        
        present(alert, animated: true, completion: nil)
    }

我的模特:

protocol ILocationGroup {
    
    func addLocation(_ name: String)
    
}

class LocationGroup: ILocationGroup {
    
    var mainScreenViewController: MainScrenenViewController?
        
    func addLocation(_ name: String) {
        
        mainScreenViewController?.delegate = self
        
                let url = "https://geocode-maps.yandex.ru/1.x/?apikey=fd93783b-fe25-4428-8c3b-38b155941c8c&format=json&geocode=\(name)"
                
                guard let url = URL(string: url) else { return }
                
                let task = URLSession.shared.dataTask(with: url) { data, response, error in
                    guard let data = data, error == nil else { return }
            
                    do {
                        let result = try JSONDecoder().decode(LocationData.self, from: data)
            
                        
                        print(result.response.geoObjectCollection.metaDataProperty.geocoderResponseMetaData.boundedBy.envelope.lowerCorner)
                    }
                    catch {
                        print("failed to convert \(error)")
                    }
            
                }
                task.resume()
    }
}

我认为应该是 var delegate: LocationGroup()

此外,我不会将其称为委托,因为注册委托是 swift

中的关键字

https://manasaprema04.medium.com/different-ways-to-pass-data-between-viewcontrollers-views-8b7095e9b1bf