Ios 在Swift中附加到数组的困难
我试图用从Web服务获得的一些数据格式化数组。根据我在操场上的测试,类似这样的东西应该会起作用:Ios 在Swift中附加到数组的困难,ios,xcode,swift,Ios,Xcode,Swift,我试图用从Web服务获得的一些数据格式化数组。根据我在操场上的测试,类似这样的东西应该会起作用: import UIKit struct Product { let id: Int let name: String } var products:[Product] = [] products.append(Product(id: 0, name: "some name")) products.append(Product(id: 1, name: "some name"))
import UIKit
struct Product
{
let id: Int
let name: String
}
var products:[Product] = []
products.append(Product(id: 0, name: "some name"))
products.append(Product(id: 1, name: "some name"))
for aproduct in products
{
println(aproduct.id)
}
但在应用程序内部,我得到了2个错误(“表达式解析为未使用的函数”,“无法将表达式的类型“Product”转换为类型“StringLiteralConvertible”)
这是发生错误的代码:
struct Product
{
let name :String;
let duration :String;
let description :String;
let image :String;
let price :Float;
}
[...]
var theData : NSData! = results.dataUsingEncoding(NSUTF8StringEncoding)
let leJSON: NSDictionary! = NSJSONSerialization.JSONObjectWithData(theData, options:NSJSONReadingOptions.MutableContainers, error: MMerror) as? NSDictionary
let theJSONData :NSArray = leJSON["data"] as NSArray
var products:[Product] = []
for aProduct in theJSONData
{
let theProduct = aProduct as NSDictionary
products.append //ERROR: Expression resolves to an unused function
(
Product( //ERROR: Cannot convert the expression's type 'Product' to type 'StringLiteralConvertible'
name: theProduct["name"],
duration: theProduct["duration"],
description: theProduct["description"],
image: "[no Image]",
price: theProduct["price"]
)
)
}
产品[“价格”]
等。返回任何对象
,您必须将值强制转换为
String
(或转换为Float
)。比如说
products.append(
Product(
name: theProduct["name"] as String,
duration: theProduct["duration"] as String,
description: theProduct["description"] as String,
image: "[no Image]" as String,
price: (theProduct["price"] as NSString).floatValue
)
)
如果您确定字典值是字符串。代码中有两个错误:
products.append //ERROR: Expression resolves to an unused function
被视为单行语句。请记住,在swift中,语句以换行符结尾。为了使其正常工作,必须删除换行符,使开括号位于同一行中,以指示编译器语句尚未完成:
products.append(
NSDictionary
是[NSString:AnyObject]。使用强制转换为字符串使展开隐式,因此您可以编写:
products.append (
Product(
name: theProduct["name"] as String,
duration: theProduct["duration"] as String,
description: theProduct["description"] as String,
image: "[no Image]",
price: theProduct["price"] as Float
)
)
price: theProduct["price"] as Float
您需要检查它是否包含字符串(在这种情况下,请查看@MartinR提出的代码)或其他内容,如浮点等
重要信息如果字典中没有任何键,或者该值不是预期的类型,则此代码将生成运行时异常