将Swift 2转换为Swift 3 MKDirections和MKDirections时出错

时间:2016-09-21 07:46:11

标签: swift3

我很难将两段代码从Swift 2转换为Swift 3

工作的Swift 2代码块是

$JAVA_CLASSPATH

}

Swift 3已将此转换为

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)

这会在行

上产生错误
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)
}

无法将'[(startingAddress:String,endingAddress:String,route:MKRoute)]'的值转换为预期的参数类型'inout _'

如果有人可以提供帮助,我会非常感激

2 个答案:

答案 0 :(得分:1)

只需要

directionsArray += [(startingAddress : locationArray[i].textField!.text!,
                       endingAddress : locationArray[i+1].textField!.text!, 
                               route : routes[i])]

答案 1 :(得分: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)
    }
}