[英]How to model data from JSON array with no property name into swift so It can be parsed? SWIFT
[英]swift, parsed Json data append into an Array but can't access the Array from default viewController
我的項目中有兩個swift文件。 一個叫做loadApi.swift,另一個是默認的ViewController.swift
我打算在loadApi.swift中包含獲取和解析Json數據的所有功能。 貝婁是代碼
import Foundation
var arr: Array = [String]()
func loadApi(){
var url = "http://api.wordnik.com:80/v4/word.json/love/definitions?limit=200&includeRelated=true&sourceDictionaries=ahd&useCanonical=true&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"
let session = NSURLSession.sharedSession()
let wordnik = NSURL(string: url)
//println(wordnik)
var task = session.dataTaskWithURL(wordnik!){
(data, response, error)-> Void in
if error != nil {
println("Internet error! Check your Internet Connection")
} else{
var error : NSError?
var vocabData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as NSArray
if error != nil{
println("Parse Json error!")
}else{
for items in vocabData{
let def = items["text"] as String
arr.append(def)
}
}
}
}
task.resume()
}
好吧,一切正常,我可以從url獲取並解析Json數據,然后將它們附加到“arr”數組中。 但是,當我嘗試在默認的ViewController.swift中調用“arr”數組時,我收到此錯誤,說“在調用中缺少參數#2”。 Bellow是我在ViewController.swift中的代碼
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
loadApi()
println(arr)
//error saying "missing parameter #2 in call"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如何訪問包含從Json數據中獲取的所有字符串的“arr”數組?
將數組的聲明更改為var arr = [String]()
應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.