【问题标题】:Value of tuple type '(key: String, value: AnyObject)' has no member 'subscript'元组类型“(键:字符串,值:AnyObject)”的值没有成员“下标”
【发布时间】:2017-11-14 10:03:50
【问题描述】:

我收到这样的错误:元组类型“(键:字符串,值:AnyObject)”的值没有成员“下标”

我尝试在线搜索但我不明白,它总是说要更改为字典数组,但是当我将数据解析为 [[String:AnyObject]] 时,它给了我一个错误。

Error Screenshot

这是我的上下文代码

`//
//  MapViewViewController.swift
//  On the Map!
//
//  Created by Belal Elsiesy on 11/13/17.
//  Copyright © 2017 Elsiesy Industries. All rights reserved.
//

import UIKit

import MapKit

class MapViewViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var MapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        getLocations()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let locations  = appDelegate.locationData
        var annotations = [MKPointAnnotation]()

        // When the array is complete, we add the annotations to the map.

        for location  in locations! {

            // Notice that the float values are being used to create CLLocationDegree values.
            // This is a version of the Double type.
            let lat = CLLocationDegrees(location["latitude"] as! Double)
            let long = CLLocationDegrees(location["longitude"] as! Double)

            // The lat and long are used to create a CLLocationCoordinates2D instance.
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

            let first = location["firstName"] as! String
            let last = location["lastName"] as! String
            let mediaURL = location["mediaURL"] as! String

            // Here we create the annotation and set its coordiate, title, and subtitle properties
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotation.title = "\(first) \(last)"
            annotation.subtitle = mediaURL

            // Finally we place the annotation in an array of annotations.
            annotations.append(annotation)
        }
        // When the array is complete, we add the annotations to the map.
        self.MapView.addAnnotations(annotations)
    }
}




    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
func getLocations() {

        var request = URLRequest(url: URL(string: "https://parse.udacity.com/parse/classes/StudentLocation")!)
        request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
        request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            if error != nil { // Handle error...
                ////////////////////////DO THIS LATER
            }
            print(String(data: data!, encoding: .utf8)!)
        let parsedResult: [String:AnyObject]!
            do {
                parsedResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as!  [String : AnyObject]


                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.locationData = parsedResult
            } catch {
                print("Could not parse the data as JSON: '\(data)'")

            }


        }
        task.resume()
    }


`

【问题讨论】:

  • 因为您的位置变量没有下标,所以您不能使用 [] 来查询信息。我认为对变量位置的类型存在误解。它是一个元组 (String, Anyobject) 而不是字典 [String : AnyObject]。

标签: json swift xcode


【解决方案1】:

来自 Apple 文档:您可以使用 for-in 循环遍历字典中的键值对。字典中的每一项都作为(键,值)元组返回,您可以将元组的成员分解为临时常量或变量作为迭代的一部分:

for (key, value) in dictionary {
    print(key)
    print(value)
}

并注意您的代码的另一个问题: 1)函数getLocation()中有异步代码,当您在viewDidLoad()中分配时

let locations  = appDelegate.locationData

位置等于 nil。

2) Swift 4 具有解析 JSON 的有用功能,研究一下。现在你得到的字典只有一个键值对,键等于“结果”

【讨论】:

  • 那么我该如何解决这个问题。
  • 没有快速的解决方案来修复它。对于异步工作,您可以使用 getLocation(with handler: @escaping: () -> ()) 或找到另一种方式。对于 JSON,我建议使用单独的 struct Location 来保存数据并将 JSON 映射到此结构的数组。首先阅读有关使用异步函数的工作以及有关在 Swift 4 中解析 JSON 的内容。
【解决方案2】:

我在尝试对元组数组进行排序时遇到了这个错误。原因是元组成员不像数组那样被引用。

对于元组,您使用 location.latitude

(对于数组,您可以使用 location["latitude"]

元组是用常规大括号声明的,而不是数组的方括号:

let location = (latitude: 2.3, longitude: 1.2)

let c = location.latitude   // c is now 2.3

我知道这个问题很老了,但我希望这可以帮助其他搜索没有成员“下标”的人

【讨论】:

    猜你喜欢
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多