簡體   English   中英

在Swift中難以附加到數組

[英]Difficulty appending to an array in 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個錯誤(“表達式解析為未使用的函數”,“無法將表達式的類型'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"]
                )
            )
        }

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
    )
)

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

您的代碼中有2個錯誤:

  1. 這段代碼:

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

    被視為單行語句。 請記住,語句會以換行符快速終止。 為了使其正常工作,您必須刪除換行符,以使打開括號位於同一行中,從而指示編譯器該語句尚未完成:

     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 ) ) 

如我所寫,最后一行可能是錯誤的:

price: theProduct["price"] as Float 

您需要檢查它是否包含字符串(在這種情況下,請查看@MartinR提出的代碼)或其他內容,例如float等。

重要說明:如果任何鍵都不在字典中,或者值不是期望的類型,則此代碼將生成運行時異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM