2016-09-21 5 views
1

У меня возникают трудности, преобразовывая две секции кода из Swift 2 к Swift 3Ошибка при преобразовании Свифта 2 до Свифта 3 MKDirections и MKDirections

Рабочий Свифта 2 Код Блок был

func showRoute(routes: [MKRoute], time: NSTimeInterval) { 
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]() 
for i in 0..<routes.count { 
    plotPolyline(routes[i]) 
    directionsArray += [(locationArray[i].textField.text!, 
    locationArray[i+1].textField.text!, routes[i])] 
} 
displayDirections(directionsArray) 
printTimeToLabel(time) 

}

Swift 3 преобразовал это

func showRoute(routes: [MKRoute], time: TimeInterval) { 
    var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]() 
    for i in 0..<routes.count { 
     plotPolyline(route: routes[i]) 
     directionsArray += [(locationArray[i].textField?.text, 
          locationArray[i+1].textField?.text, routes[i])] 
    } 
    displayDirections(directionsArray: directionsArray) 
    printTimeToLabel(time: time) 
} 

Это приводит к ошибке уплотнительное п линия

directionsArray += [(locationArray[i].textField?.text, 
          locationArray[i+1].textField?.text, routes[i])] 

Невозможно преобразовать значение типа '[(startingAddress: String, endingAddress: String, маршрут: MKRoute)] ожидаемого типа аргумента 'INOUT _'

Если кто-то может помочь я был бы очень признателен

ответ

0

Я видел ваш вопрос, но ответов нет. И это не только одна проблема.

Вот полный корпус ViewController:

import UIKit 
import MapKit 
import CoreLocation 

class ViewController: UIViewController { 

    @IBOutlet weak var sourceField: UITextField! 
    @IBOutlet weak var destinationField1: UITextField! 
    @IBOutlet weak var destinationField2: UITextField! 
    @IBOutlet weak var topMarginConstraint: NSLayoutConstraint! 
    @IBOutlet var enterButtonArray: [UIButton]! 

    var originalTopMargin: CGFloat! 

    let locationManager = CLLocationManager() 
    var locationTuples: [(textField: UITextField?, mapItem: MKMapItem?)]! 

    var locationsArray: [(textField: UITextField?, mapItem: MKMapItem?)] { 
     var filtered = locationTuples.filter({ $0.mapItem != nil }) 
     filtered += [filtered.first!] 
     return filtered 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     originalTopMargin = topMarginConstraint.constant 

     locationTuples = [(sourceField, nil), (destinationField1, nil), (destinationField2, nil)] 

     locationManager.delegate = self 
     locationManager.requestWhenInUseAuthorization() 

     if CLLocationManager.locationServicesEnabled() { 
      locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters 
      locationManager.requestLocation() 
     } 
    } 

    override func viewWillAppear(_ animated: Bool) { 
     navigationController?.isNavigationBarHidden = true 
    } 

    @IBAction func getDirections(_ sender: AnyObject) { 
     view.endEditing(true) 
     performSegue(withIdentifier: "show_directions", sender: self) 
    } 

    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { 
     if locationTuples[0].mapItem == nil || 
      (locationTuples[1].mapItem == nil && locationTuples[2].mapItem == nil) { 
      showAlert("Please enter a valid starting point and at least one destination.") 
      return false 
     } else { 
      return true 
     } 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     let directionsViewController = segue.destination as! DirectionsViewController 
     directionsViewController.locationArray = locationsArray 
    } 

    @IBAction func addressEntered(_ sender: UIButton) { 
     view.endEditing(true) 
     let currentTextField = locationTuples[sender.tag-1].textField 
     CLGeocoder().geocodeAddressString(currentTextField!.text!, 
              completionHandler: {(placemarks, error) -> Void in 
              if let placemarks = placemarks { 
               var addresses = [String]() 
               for placemark in placemarks { 
                addresses.append(self.formatAddressFromPlacemark(placemark)) 
               } 
               self.showAddressTable(addresses, textField:currentTextField!, 
                     placemarks:placemarks, sender:sender) 
              } else { 
               self.showAlert("Address not found.") 
              } 
              }) 
    } 

    func showAddressTable(_ addresses: [String], textField: UITextField, 
          placemarks: [CLPlacemark], sender: UIButton) { 
     let addressTableView = AddressTableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain) 
     addressTableView.addresses = addresses 
     addressTableView.currentTextField = textField 
     addressTableView.placemarkArray = placemarks 
     addressTableView.mainViewController = self 
     addressTableView.sender = sender 
     addressTableView.delegate = addressTableView 
     addressTableView.dataSource = addressTableView 
     view.addSubview(addressTableView) 
    } 

    func formatAddressFromPlacemark(_ placemark: CLPlacemark) -> String { 
     return (placemark.addressDictionary!["FormattedAddressLines"] as! [String]).joined(separator: ", ") 
    } 

    @IBAction func swapFields(_ sender: AnyObject) { 
     swap(&destinationField1.text, &destinationField2.text) 
     swap(&locationTuples[1].mapItem, &locationTuples[2].mapItem) 
     swap(&self.enterButtonArray.filter{$0.tag == 2}.first!.isSelected, &self.enterButtonArray.filter{$0.tag == 3}.first!.isSelected) 
    } 

    func showAlert(_ alertString: String) { 
     let alert = UIAlertController(title: nil, message: alertString, preferredStyle: .alert) 
     let okButton = UIAlertAction(title: "OK", 
            style: .cancel) { (alert) -> Void in 
     } 
     alert.addAction(okButton) 
     present(alert, animated: true, completion: nil) 
    } 

    // The remaining methods handle the keyboard resignation/ 
    // move the view so that the first responders aren't hidden 

    func moveViewUp() { 
     if topMarginConstraint.constant != originalTopMargin { 
      return 
     } 

     topMarginConstraint.constant -= 165 
     UIView.animate(withDuration: 0.3, animations: {() -> Void in 
      self.view.layoutIfNeeded() 
     }) 
    } 

    func moveViewDown() { 
     if topMarginConstraint.constant == originalTopMargin { 
      return 
     } 

     topMarginConstraint.constant = originalTopMargin 
     UIView.animate(withDuration: 0.3, animations: {() -> Void in 
      self.view.layoutIfNeeded() 
     }) 
    } 
} 

extension ViewController: UITextFieldDelegate { 

    func textField(_ textField: UITextField, 
        shouldChangeCharactersIn range: NSRange, 
        replacementString string: String) -> Bool { 

     enterButtonArray.filter{$0.tag == textField.tag}.first!.isSelected = false 
     locationTuples[textField.tag-1].mapItem = nil 
     return true 
    } 

    func textFieldDidBeginEditing(_ textField: UITextField) { 
     moveViewUp() 
    } 

    func textFieldDidEndEditing(_ textField: UITextField) { 
     moveViewDown() 
    } 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     view.endEditing(true) 
     moveViewDown() 
     return true 
    } 
} 

extension ViewController: CLLocationManagerDelegate { 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     CLGeocoder().reverseGeocodeLocation(locations.last!, 
              completionHandler: {(placemarks, error) -> Void in 
               if let placemarks = placemarks { 
                let placemark = placemarks[0] 
                self.locationTuples[0].mapItem = MKMapItem(placemark: 
                 MKPlacemark(coordinate: placemark.location!.coordinate, 
                    addressDictionary: placemark.addressDictionary as! [String:AnyObject]?)) 
                self.sourceField.text = self.formatAddressFromPlacemark(placemark) 
                self.enterButtonArray.filter{$0.tag == 1}.first!.isSelected = true 
               } 
     }) 
    } 


    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 
     print(error) 
    } 
} 
1

Просто нужно

directionsArray += [(startingAddress : locationArray[i].textField!.text!, 
         endingAddress : locationArray[i+1].textField!.text!, 
           route : routes[i])] 
Смежные вопросы