在Swift中追加数组的难度

时间:2014-10-07 18:31:00

标签: 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"))



for aproduct in products
{
    println(aproduct.id)
}

但是在应用程序中我得到2个错误("表达式解析为未使用的函数","无法转换表达式'产品'键入& #39; StringLiteralConvertible'&#34)

这是发生错误的代码:

    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"]
                )
            )
        }

2 个答案:

答案 0 :(得分:1)

theProduct["price"]等返回AnyObject,您必须将值转换为 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
    )
)

如果您确定字典值是字符串。

答案 1 :(得分:1)

您的代码中有2个错误:

  1. 此代码:

    products.append //ERROR:  Expression resolves to an unused function
    

    被视为单行语句。请记住,在swift中,语句会被换行符终止。为了使其正常工作,您必须删除换行符,以使开括号位于同一行,表明编译器尚未完成该语句:

    products.append(
    
  2. 字典总是返回一个可选项,因此您必须打开每个值,并转换为String,因为NSDictionary是[NSString:AnyObject]。使用强制转换为String会使展开隐式,因此您可以编写:

    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
        )
    )
    
  3. 我写的最后一行可能不正确:

    price: theProduct["price"] as Float 
    

    你需要检查它是否包含一个字符串(在这种情况下查看@MartinR提出的代码)或其他内容,如浮点数等。

    重要如果任何键不在字典中,或者该值不是预期类型,则此代码会生成运行时异常。