我只能打印1个数据,不能再打印。这是我的错误:
线程1:致命错误:索引超出范围
这是我的JSON:
"Enter burst time for process: {i} ->".format(i=i)
这是我运行良好的结构:
[
{
"Guides": [
{
"_id": "5cbc780edfdb6307006aec37",
"Text": "He is one of Soroush Friend",
"Tavernier": 2
},
{
"_id": "5cbc781bdfdb6307006aec38",
"Text": "He is one of Soroush Friend",
"Tavernier": 2
}
]
}
]
这是我的数组和我的课:
struct GuideStruct: Codable {
let guides: [Guide]
enum CodingKeys: String, CodingKey {
case guides = "Guides"
}
}
struct Guide: Codable {
let id, text: String
let tavernier: Int
enum CodingKeys: String, CodingKey {
case id = "_id"
case text = "Text"
case tavernier = "Tavernier"
}
}
还有我在viewcontroller中的代码:
internal static var guides = [guidesarr]()
class guidesarr {
var _id : String
var Text : String
var Tavernier : Int
init(_id : String,Text : String,Tavernier : Int) {
self._id = _id
self.Text = Text
self.Tavernier = Tavernier
}
}
我可以打印:
class GameViewController: UIViewController,UITextFieldDelegate {
typealias guide1 = [GuideStruct]
var i1 = 0
override func viewDidLoad() {
super.viewDidLoad()
let headers : HTTPHeaders = ["Content-Type":"application/json","OAtcp":"0!QSJ5SDG8Q39PPM$DXP5HD1E10"]
Alamofire.request("http://192.168.1.100:3535/DarkDiamonds/Api/GetActiveGames",method :.post,headers: headers).responseJSON { (newresponse) in
do {
let decoder = JSONDecoder()
let responseguide = try decoder.decode(guide1.self, from: newresponse.data!)
for each1 in responseguide {
let newstruct = guidesarr(_id:each1.guides[self.i1].id , Text: each1.guides[self.i1].text, Tavernier: each1.guides[self.i1].tavernier)
self.i1 = self.i1 + 1
AppDelegate.guides.append(newstruct)
}
print(AppDelegate.guides[0])
print(AppDelegate.guides[1])
print(AppDelegate.Games.count)
print(AppDelegate.guides[0].Text)
print(AppDelegate.guides[1].Text)
}catch {
}
}
}
}
并打印此:
print(AppDelegate.guides[0])
但是当我要打印此内容时:
print(AppDelegate.guides[0].Text)
有错误:
线程1:致命错误:索引超出范围
答案 0 :(得分:1)
您的代码中有几个问题。
guidesarr
类。只需使用您的Guide
结构即可。data
。安全地检查它并进行正确的错误检查。Guide
实例中的两个GuideStruct
实例。我会像这样重做您的代码:
class GameViewController: UIViewController,UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let headers : HTTPHeaders = ["Content-Type":"application/json","OAtcp":"0!QSJ5SDG8Q39PPM$DXP5HD1E10"]
Alamofire.request("http://192.168.1.100:3535/DarkDiamonds/Api/GetActiveGames", method: .post, headers: headers).responseJSON { (newresponse) in
if let data = newresponse.data {
do {
let decoder = JSONDecoder()
let guides = try decoder.decode([GuideStruct].self, from: data)
for guideStruct in guides {
AppDelegate.guides.append(contentsOf: guideStruct.guides)
}
print(AppDelegate.guides[0])
print(AppDelegate.guides[1])
print(AppDelegate.Games.count)
print(AppDelegate.guides[0].Text)
print(AppDelegate.guides[1].Text)
}catch {
// Bad JSON
}
} else {
// No data
}
}
}
}
然后更改:
internal static var guides = [guidesarr]()
收件人:
internal static var guides = [Guide]()
并删除guidearr
类。