如何使用函数中的数据填充数组?

时间:2016-08-20 08:43:29

标签: arrays json swift

您好我有以下功能:

 func parceDosi()
{

    struct City{

        let name : String
      //  let location : CLLocation

    }

    var cities = [City]()


    var person = "Person"
    let path: String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
    let jsonData = NSData(contentsOfFile: path) as NSData!
    let ReadableJSON = JSON ( data:jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil )

    NumberRows = ReadableJSON ["People"].count

    for (var i = 0 ; i <= NumberRows; i++ )
    {
        Person += "\(i)"

        let NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!

        let NameShirina = ReadableJSON ["People"] [Person] ["C1"].string as String!

        let NameDuljina = ReadableJSON ["People"] [Person] ["D1"].string as String!

        let latitude    =   (NameShirina as NSString).doubleValue
        let longitude   =   (NameDuljina as NSString).doubleValue
   //     let loc         =  CLLocation( latitude: latitude, longitude: longitude)
    //    let ci          =  City(name: NameImeNaObekt, location: loc)

        let ci    =  City( name: NameImeNaObekt)

        cities.append(ci)

从json文件中读取信息。读取的信息我想将其返回到

var data = [??]

这个变量数据如果按以下方式工作正常:

var data = [纽约,波士顿,加利福尼亚],

但我不想写纽约,波士顿,加利福尼亚州,而是希望返回这个功能        func parceDosi(),        因为所有的城市都是从json文件中解析出来的,所以我不需要写每一个。你知道怎么做,我是新的,我的语法中的东西是错的。 这是JSON文件:

  {
      "People": {
        "Person0": {
            "A1": "Безплатен Сок",
            "B1": "Царево 11",
            "C1": "43.0757",
            "D1": "23.6172",
            "E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
                   },

        "Person1": {
            "A1": "Безплатна Бира",
            "B1": "Царево 22",
            "C1": "44.0757",
            "D1": "24.6172",
            "E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
                    },
"Person2": {
    "A1": "Безплатен Десерт",
    "B1": "Царево 33",
    "C1": "45.0757",
    "D1": "25.6172",
    "E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person3": {
    "A1": "Безплатно Кафе",
    "B1": "Царево 55",
    "C1": "41.0757",
    "D1": "21.6172",
    "E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"
},
"Person4": {
    "A1": "Безплатна Кола",
    "B1": "Царево 66",
    "C1": "46.0757",
    "D1": "26.6172",
    "E1": "http://weknowyourdreams.com/image.php?pic=/images/beer/beer-07.jpg"


    }
  }
  }

1 个答案:

答案 0 :(得分:0)

JSON中的每个Person包含5个键值对,因此我扩展了结构City,将从纬度和经度创建属性location

struct City {
  let name : String
  let city : String
  let location : CLLocation
  let imageURL : NSURL
}

由于您使用的是SwiftJSON,因此解析非常清晰

var cities = [City]()

func parceDosi() {
  guard let url = NSBundle.mainBundle().URLForResource("jsonFile", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else {
    print("Error finding JSON File")
    return
  }

  let readableJSON = JSON(data: jsonData) // the mutable option is not needed.

  let people = readableJSON["People"].dictionaryValue
  for (_, person) in people {
    let personName = person["A1"].stringValue
    let cityName = person["B1"].stringValue
    let latitude = person["C1"].doubleValue
    let longitude = person["D1"].doubleValue
    let imageURL = person["E1"].stringValue

    let city = City(name: personName, city: cityName, location: CLLocation(latitude: latitude, longitude: longitude), imageURL: NSURL(string:imageURL)!)
    cities.append(city)
  }

  // This is an example to get the nearest city from a given location

  let myLocation = CLLocation(latitude: 50.0, longitude: 8.0)
  let nearestlocations = cities.sort { (city1, city2) -> Bool in
    return city1.location.distanceFromLocation(myLocation) < city2.location.distanceFromLocation(myLocation)
  }
  print(nearestlocations.first!)
}

PS:由于你负责捆绑中的JSON文件,我建议为人们使用一个数组(而不是字典),并给“棋盘”-key提供更具描述性的名称。