Andrei Stanca
Andrei Stanca

Reputation: 908

Difficulty appending to an array in Swift

I'm trying to format an Array with some data that I get from a Web Service. From what I tested in playground, something like this should work:

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

But inside the application I get 2 errors ("Expression resolves to an unused function", "Cannot convert the expression's type 'Product' to type 'StringLiteralConvertible'")

This is the code where errors are occuring:

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

Upvotes: 0

Views: 225

Answers (2)

Antonio
Antonio

Reputation: 72750

There are 2 errors in your code:

  1. This code:

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

    is treated as a single line statement. Remember that in swift a statement is terminated by a newline. In order to make it work properly you have to remove the newline so that the open parenthesis is in the same line, indicating the compiler that the statement is not completed yet:

    products.append(
    
  2. a dictionary always returns an optional, so you have to unwrap each value, and cast to String, because NSDictionary is [NSString:AnyObject]. Using the forced cast to String makes the unwrapping implicit, so you can write:

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

The last line, as I wrote it, is probably incorrect:

price: theProduct["price"] as Float 

you need to check whether it contains a string (in that case look at the code proposed by @MartinR) or something else, like a float etc.

Important If any of the keys is not in the dictionary, or if the value is not of the expected type, this code generates a runtime exception.

Upvotes: 1

Martin R
Martin R

Reputation: 539685

theProduct["price"] etc. return an AnyObject and you have to cast the values to String (or convert to Float). For example

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

if you are sure that the dictionary values are strings.

Upvotes: 1

Related Questions