//在文件中:Struct.swift是我定义结构布局的地方。
struct coin
{
var coinYear = String("")
var userID = String("")
var coinSellCoinID = String("")
var coinImageURL = String("")
var mintYear = String("")
var about = String("")
var allowBarter = String("")
}
/ *
在文件FirstViewController.swift中,我从输入框中获取硬币ID值,然后单击按钮并构建URL字符串。
然后我将该URL发送到fetchCoinJSON函数以获取JSON文本
* /
@IBAction func btnSubmitCoinID(sender: AnyObject)
{
let temp = coinID.text
let theCoinURL = NSURL(string: MyVariables.url + "getCoinInfo.php?coinID=" + temp)
fetchCoinJSON(theCoinURL!)
}
// file:fetchJson.swift使用获取JSON字符串的URL,然后获取JSON字符串并将该字符串传递给parseCoinJson函数。
func fetchCoinJSON(theurl: NSURL)
{
var error: NSError?
var notWorking = coin()
MyVariables.rawCoinJSON =
NSString(contentsOfURL: theurl, encoding: NSUTF8StringEncoding, error: &error)!
var data: NSData =
MyVariables.rawCoinJSON.dataUsingEncoding(NSUTF8StringEncoding)!
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error)
println("Error: \(error)")
notWorking = parseCoinJson(anyObj!) <--- var notWorking = nil
NSLog("OoOoOoOoOoOoOoO")
println(notWorking.coinWeight) <--- logs null
}
//文件ParseJSON.swift这里我解析JSON并设置相应的struct值。使用NSLog我知道c.CoinYear确实包含正确的值以及所有其他值。然而
返回c
给出错误:ParseJSON.swift:95:16:'coin'不能转换为'()'
func parseCoinJson(anyObj:AnyObject)
{
if anyObj is Array<AnyObject>
{
var c = coin()
for json in anyObj as! Array<AnyObject>
{
c.userID = (json["userid"] as AnyObject? as? String) ?? String("") ?? String ("")
c.mintYear = (json["mintyear"] as AnyObject? as? String) ?? String("") ?? String ("")
c.coinActiveStatus = (json["isActive"] as AnyObject? as? String) ?? String("") ?? String ("")
c.coinSellCoinID = (json["sellcoinid"] as AnyObject? as? String) ?? String("") ?? String ("")
c.coinImageURL = (json["coinImageURL"] as AnyObject? as? String) ?? String("") ?? String ("")
c.about = (json["about"] as AnyObject? as? String) ?? String("") ?? String ("")
c.allowBarter = (json["allowBarter"] as AnyObject? as? String) ?? String("") ?? String ("")
....
}
return c
}
}
答案 0 :(得分:1)
func parseCoinJson(anyObj:AnyObject)
此函数返回Void
,即()
。然后返回coin
。你的意思是:
func parseCoinJson(anyObj:AnyObject) -> Coin
请注意,类型应始终为前导上限。所以这应该是struct Coin
。