Ios 对成员'的模糊引用;下标';使用谷歌地图路线时

Ios 对成员'的模糊引用;下标';使用谷歌地图路线时,ios,swift3,Ios,Swift3,下面的代码在Xcode 7.1中运行良好,但当我升级到Xcode 8和swift 3时,我发现了这个错误,我在互联网上搜索了stackoverflow中的相同问题,但没有一个能回答我的问题 func drawRoute() { clearRoute() // self.routePolyline = nil // self.routePolyline.map = nil let route = mapTk.overviewPolyline!["point

下面的代码在
Xcode 7.1
中运行良好,但当我升级到
Xcode 8
swift 3
时,我发现了这个错误,我在互联网上搜索了stackoverflow中的相同问题,但没有一个能回答我的问题

func drawRoute() {


    clearRoute()
    //  self.routePolyline = nil
    // self.routePolyline.map = nil


    let route = mapTk.overviewPolyline!["points"] as String //error here

    //var overViewPolyLine = routes![0]["overview_polyline"]["points"].string

    let path: GMSPath = GMSPath(fromEncodedPath: route)
    routePolyline = GMSPolyline(path: path)
    routePolyline.map = viewMap
}
以下是mapTK类以了解更多信息:

import Foundation


import UIKit
import CoreLocation
import MapKit

///This Class is designed for the detail methods that contact google maps server like GeoCode, GetDirection and Calculate distance and time
class MapTK: NSObject {
    let baseURLGeocode = "https://maps.googleapis.com/maps/api/geocode/json?"

    var lookupAddressResults: Dictionary<NSObject, AnyObject>!

    var fetchedFormattedAddress: String!

    var fetchedAddressLongitude: Double!

    var fetchedAddressLatitude: Double!


    let baseURLDirections = "https://maps.googleapis.com/maps/api/directions/json?"

    var selectedRoute: Dictionary<NSObject, AnyObject>!

    var overviewPolyline: Dictionary<NSObject, AnyObject>!

    var originCoordinate: CLLocationCoordinate2D!

    var destinationCoordinate: CLLocationCoordinate2D!

    var originAddress: String!

    var destinationAddress: String!

    var totalDistanceInMeters: UInt = 0

    var totalDistance: String!

    var totalDurationInSeconds: UInt = 0

    var totalDuration: String!



    /*  private let errorDictionary = ["NOT_FOUND" : "At least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded",
    "ZERO_RESULTS":"No route could be found between the origin and destination",
    "MAX_WAYPOINTS_EXCEEDED":"Too many waypointss were provided in the request The maximum allowed waypoints is 8, plus the origin, and destination",
    "INVALID_REQUEST":"The provided request was invalid. Common causes of this status include an invalid parameter or parameter value",
    "OVER_QUERY_LIMIT":"Service has received too many requests from your application within the allowed time period",
    "REQUEST_DENIED":"Service denied use of the directions service by your application",
    "UNKNOWN_ERROR":"Directions request could not be processed due to a server error. Please try again"]

    */

    override init() {
        super.init()
    }

        ///the geocodeAddress is getting information from googlemaps with JSON it receive the geocode information
    func geocodeAddress(address: String!, withCompletionHandler completionHandler: @escaping ((_: String, _: Bool) -> Void)) {
        if let lookupAddress = address {
            var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
            //geocodeURLString = geocodeURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!






            let geocodeURL = NSURL(string: geocodeURLString)

           // dispatch_Dispatch.Queue.mainasync(dispatch_get_main_queue(), { () -> Void in
            DispatchQueue.main.async {

            let geocodingResultsData = NSData(contentsOf: geocodeURL! as URL)

               // let error: NSError?

               do
               {
                let dictionary = try JSONSerialization.jsonObject(with: geocodingResultsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary


                // try NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
              /*
                if (error != nil) {
                    print(error)
                    completionHandler(status: "", success: false)
                }

*/
 //               else {
                    // Get the response status.
                    let status = dictionary?["status"]as! String
              //   let status = dictionary["status"] as! [AnyObject]



                    if status == "OK" {
                        let allResults = dictionary?["results"] as! Array<Dictionary<NSObject, AnyObject>>
                        self.lookupAddressResults = allResults[0]

                        // Keep the most important values.
                        self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"]? as? String
                        let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
                        self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
                        self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue

                        completionHandler(status, true)
                    }
                    else {
                        completionHandler(status, false)
                    }
               } catch let error as NSError {

                print(error)
                }
            }  
        }
        else {
            completionHandler("No valid address.", false)
        }
    }


    ///getDirection method is using JSON to receive waypoints for making route for drawing polyline, as its name suggests it get the direciton inforamtion, first it send lat and lng the receive a dictionary and that dictionary give all the infrmation need to draw route like waypoints

    func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, travelMode: TravelModes!, completionHandler: @escaping ((_ status: String, _ success: Bool) -> Void)) {
        if let originLocation = origin {
            if let destinationLocation = destination {
                var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation //+ "&key=AIzaSyDsDqj0EMYZ-C4lGF3tmbntZtzurLl6_J4"



                if let routeWaypoints = waypoints {
                    directionsURLString += "&waypoints=optimize:true"

                    for waypoint in routeWaypoints {
                        directionsURLString += "|" + waypoint
                    }
                }
                if let _ = travelMode {
                    var travelModeString = ""

                    switch travelMode.rawValue {
                    case TravelModes.walking.rawValue:
                        travelModeString = "walking"

                    case TravelModes.bicycling.rawValue:
                        travelModeString = "bicycling"

                    default:
                        travelModeString = "driving"
                    }




                directionsURLString += "&mode=" + travelModeString
            }


              //  directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(NSUTF8StringEncoding)!

              //  directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

             //  directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!



                /// directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

                directionsURLString = directionsURLString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!


//let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

                //var url = NSURL(urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()))
                //let savePath = (documentDirectory as NSString).stringByAppendingPathComponent("mergeVideo-\(date).mov")

                let directionsURL = NSURL(string: directionsURLString)

              //  DispatchQueue.main.asynchronously(execute: { () -> Void in

                     DispatchQueue.main.async {
                    let directionsData = NSData(contentsOf: directionsURL! as URL)

                   // var error: NSError?

                    do {
 let dictionary = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary


                        /*
                        if (error != nil) {
                        print(error)
                        completionHandler(status: "", success: false)
                    }
*/
                   // else {
                        let status = dictionary?["status"] as! String

                        if status == "OK" {
                            self.selectedRoute = (dictionary?["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0]
                            self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>

                            let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>>

                            let startLocationDictionary = legs[0]["start_location"] as! Dictionary<NSObject, AnyObject>
                            self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double)

                            let endLocationDictionary = legs[legs.count - 1]["end_location"]as! Dictionary<NSObject, AnyObject>
                            self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double)

                            self.originAddress = legs[0]["start_address"] as! String
                            self.destinationAddress = legs[legs.count - 1]["end_address"] as! String

                            self.calculateTotalDistanceAndDuration()

                            completionHandler(status, true)

                        }
                        else {
                            completionHandler(status, false)
                        }



                    } catch let error as NSError {

                        print(error)
                    }

                  }
                    }



            else {
                completionHandler("Destination is nil.", false)
            }
        }

        else {
            completionHandler("Origin is nil", false)
        }

    }


/// this method below is for the calculation of Distance adn Duration of each location for travel

    func calculateTotalDistanceAndDuration() {
        let legs = self.selectedRoute["legs"] as! Array<NSDictionary>

        totalDistanceInMeters = 0
        totalDurationInSeconds = 0

        for leg in legs {
            totalDistanceInMeters += (leg["distance"] as! Dictionary<NSObject, AnyObject>)["value"] as! UInt
            totalDurationInSeconds += (leg["duration"]as! Dictionary<NSObject, AnyObject>)["value"] as! UInt
        }


        let distanceInKilometers: Double = Double(totalDistanceInMeters / 1000)
        totalDistance = "Total Distance: \(distanceInKilometers) Km"


        let mins = totalDurationInSeconds / 60
        let hours = mins / 60
        let days = hours / 24
        let remainingHours = hours % 24
        let remainingMins = mins % 60
        let remainingSecs = totalDurationInSeconds % 60

        totalDuration = "Duration: \(days) d, \(remainingHours) h, \(remainingMins) mins, \(remainingSecs) secs"
    }






}
<代码>导入基础 导入UIKit 导入核心定位 导入地图套件 ///这个类是为联系GoogleMaps服务器的详细方法设计的,比如GeoCode、GetDirection和计算距离和时间 类MapTK:NSObject{ 让baseURLGeocode=”https://maps.googleapis.com/maps/api/geocode/json?" var lookupAddressResults:字典! var fetchedFormattedAddress:字符串! var fetchedaddress经度:双精度! var fetchedAddressLatitude:Double! 让baseURLDirections=”https://maps.googleapis.com/maps/api/directions/json?" var selectedRoute:字典! var概览多段线:字典! 变量原始坐标:CLLocationCoordinate2D! var DestinationCoordination:CLLocationCoordinate2D! var originAddress:字符串! var destinationAddress:String! var totalDistanceInMeters:UInt=0 var totalDistance:字符串! var totalDurationInSeconds:UInt=0 var totalDuration:String! /*private let errorDictionary=[“未找到”:“请求的起点、目的地或航路点中指定的至少一个位置无法进行地理编码”, “零结果”:“在始发站和目的地之间找不到路由”, “超过最大航路点”:“请求中提供的航路点太多,允许的最大航路点为8,加上起点和目的地”, “无效的_请求”:“提供的请求无效。此状态的常见原因包括无效的参数或参数值”, “超过查询限制”:“服务在允许的时间内收到来自您的应用程序的太多请求”, “拒绝请求”:“服务拒绝您的应用程序使用方向服务”, “未知错误”:“由于服务器错误,无法处理方向请求。请重试”] */ 重写init(){ super.init() } ///geocodeAddress通过JSON从googlemaps获取信息,它接收到了geocode信息 func geocodeAddress(地址:String!,withCompletionHandler completionHandler:@escaping(((字符串,:Bool)->Void)){ 如果让lookupAddress=address{ var geocodeURLString=baseURLGeocode+“address=“+lookupAddress //geocodeURLString=geocodeURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! 让geocodeURL=NSURL(字符串:geocodeURLString) //dispatch\u dispatch.Queue.mainasync(dispatch\u get\u main\u Queue(),{()->Void in DispatchQueue.main.async{ 让geocodingResultsData=NSData(contentsOf:geocodeURL!as URL) //让错误:n错误? 做 { 让dictionary=try JSONSerialization.jsonObject(使用:geocodingResultsData!作为数据,选项:JSONSerialization.ReadingOptions.mutableContainers)作为?NSDictionary //尝试将NSJSONSerialization.JSONObjectWithData(directionsData!,选项:NSJSONReadingOptions.MutableContainers)作为NSDictionary /* 如果(错误!=nil){ 打印(错误) completionHandler(状态:“”,成功:false) } */ //否则{ //获取响应状态。 让status=字典?[“status”]作为!字符串 //让status=dictionary[“status”]作为![AnyObject] 如果状态==“正常”{ 让allResults=字典?[“结果”]作为!数组 self.lookupAddressResults=所有结果[0] //保持最重要的价值观。 self.fetchedFormattedAddress=self.lookupAddressResults[“格式化的_地址”]?作为?字符串 让geometry=self.lookupAddressResults[“geometry”]as!Dictionary self.fetchedaddress经度=((几何体[“位置”]as!字典)[“lng”]as!NSNumber)。doubleValue self.fetchedAddressLatitude=((几何体[“位置”]as!字典)[“纬度”]as!NSNumber)。doubleValue completionHandler(状态,true) } 否则{ completionHandler(状态,false) } }将let错误捕获为NSError{ 打印(错误) } } } 否则{ completionHandler(“无有效地址”,false) } } ///getDirection方法使用JSON接收用于绘制多段线的路线的航路点,顾名思义,它获取方向信息,首先发送lat和lng并接收字典,该字典提供绘制类似路线的航路点所需的所有信息 func getDirections(起点:String!、终点:String!、航路点:Array!、travelMode:TravelModes!、completionHandler:@escaping((u状态:String,uu成功:Bool)->Void)){ 如果让originLocation=原点{ 如果让destinationLocation=目的地{ var directionsURLString=baseURLDirections+“origin=“+originLocation+”和destination=“+destinationLocation/+”&key=AIzaSyDsDqj0EMYZ-c4lgf3tmbntzurlll6_J4” 如果让航路点=航路点{ directionsURLString+=“&waypoints=optimize:true” 对于航路点中的航路点{ 方向URLSTRING+=“|”+航路点 } } 如果let=travelMode{ var traveling=“” 切换travelMod
Dictionary<String, Any>
typealias JSONObject = [String:Any] // synonym of Dictionary<String, Any>
var lookupAddressResults: JSONObject!
... 
var selectedRoute: JSONObject!
var overviewPolyline: JSONObject!
...
    if status == "OK" {
        let allResults = dictionary?["results"] as! Array<JSONObject>
        self.lookupAddressResults = allResults[0]

        // Keep the most important values.
        self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as? String
        let geometry = self.lookupAddressResults["geometry"] as! JSONObject
        self.fetchedAddressLongitude = ((geometry["location"] as! JSONObject)["lng"] as! NSNumber).doubleValue
        self.fetchedAddressLatitude = ((geometry["location"] as! JSONObject)["lat"] as! NSNumber).doubleValue

        completionHandler(status, true)
      }

...
( ... as! NSNumber).doubleValue
... as! Double