自分の位置から近い順にお店を表示する機能を作成しています。
現在はAPIを叩くとカテゴリー毎に別れているお店のデータをJSONで取得することができます。
なので順序がDBへ登録した順になっています。
調べたところ、Swiftには配列をソートできる関数が用意されているそうなので
それを使用しあらかじめ入力しておいた緯度経度を元に近い順にソートしようとしたのですが、
値がnil
になります。
参考サイトは通常の配列のため、ネストされている配列の時はどうすればよろしいでしょうか。
またなぜ、参考先の引数はspot1
、spot2
が引数なのでしょうか
ご教授いただけると嬉しいです。
StoreListSwift
1import UIKit 2import CoreLocation 3 4class StoreListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { 5 6 @IBOutlet weak var TableView: UITableView! 7 8 var category_id = "" 9 let cellReuseIdentifier = "cell" 10 //Json用変数 11 var stores : [categories.stores]? 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 TableView.delegate = self 16 TableView.dataSource = self 17 18 let url = URL(string: "http://127.0.0.1:8000/search/api/category?category_id=" + category_id) 19 let request = URLRequest(url: url!) 20 let session = URLSession.shared 21 22 let encoder: JSONEncoder = JSONEncoder() 23 encoder.dateEncodingStrategy = .iso8601 24 encoder.outputFormatting = .prettyPrinted 25 26 session.dataTask(with: request){(data, response, error)in if error == nil, 27 let data = data, 28 let response = response as? HTTPURLResponse{ 29 30 let decoder: JSONDecoder = JSONDecoder() 31 decoder.dateDecodingStrategy = .iso8601 32 do { 33 34 let json = try decoder.decode(categories.self, from: data) 35 36 37 //print(json.stores[0].lat) 38 39 //Jsonを変数に代入 40 self.stores = json.stores 41 DispatchQueue.main.async { 42 self.TableView.reloadData() 43 } 44 45 } catch { 46 print("error:", error.localizedDescription) 47 48 } 49 50 } 51 52 }.resume() 53 54 55 //ソート機能 56 let currentLocation = CLLocation(latitude: 35.658034, longitude: 139.701636) 57 58 stores?.sort(by: { (store1, store2) -> Bool in 59 let a = CLLocation(latitude: store1.lat, longitude: store1.lng) 60 let b = CLLocation(latitude: store2.lat, longitude: store2.lng) 61 return currentLocation.distance(from: a) < currentLocation.distance(from: b) 62 }) 63 64 print(stores) 65 } 66}
JSON
1struct categories : Codable { 2 let id : Int 3 let name : String 4 let stores : [stores] 5 6 struct stores : Codable { 7 let id : Int 8 let name : String 9 let location : String 10 let price : String 11 let open_time : String 12 let closed_day : String 13 let tellNumber : String 14 var lat : CLLocationDegrees 15 var lng : CLLocationDegrees 16 let photos : [photos] 17 let tags : [tags] 18 19 20 struct photos:Codable { 21 let id : Int 22 let path : String 23 } 24 25 struct tags:Codable { 26 let id : Int 27 let name : String 28 } 29 } 30} 31

回答1件
あなたの回答
tips
プレビュー