将多个值附加到结构中的数组?

时间:2017-09-05 21:12:19

标签: arrays swift struct

我觉得我是在完全错误的角度尝试这个......

到目前为止,我的解析后的JSON存储在10个不同的数组中:

Alamofire.request(FULL_API).responseJSON { (response) in
        print("AddCoinModel: Full Api = \(FULL_API)")
        if response.result.error == nil {
            guard let data = response.data else { return }
            if let json = JSON(data: data).array {
                for item in json {

                    let id = item["id"].stringValue
                    self.coinImageIdStringArray.append("https://files.coinmarketcap.com/static/img/coins/64x64/\(id).png")

                    let name = item["name"].stringValue
                    self.coinFullNameArray.append(name)

                    let symbol = item["symbol"].stringValue
                    self.coinSymbolArray.append(symbol)

                    let price = item["price_\(self.API_FIAT.lowercased())"].numberValue
                    self.coinPriceArray.append(Double(price))

                    let priceBtc = item["price_btc"].numberValue
                    self.coinPriceInBitcoinArray.append(Double(priceBtc))

                    let volume = item["24h_volume_\(self.API_FIAT.lowercased())"].numberValue
                    self.coinVolume24hArray.append(Double(volume))

                    let marketCap = item["market_cap_\(self.API_FIAT.lowercased())"].numberValue
                    self.coinMarketCapArray.append(Double(marketCap))

                    let percent1h = item["percent_change_1h"].numberValue
                    self.coinPercentChange1hArray.append(Double(percent1h))

                    let percent24h = item["percent_change_24h"].numberValue
                    self.coinPercentChange24hArray.append(Double(percent24h))

                    let percent7d = item["percent_change_7d"].numberValue
                    self.coinPercentChange7dArray.append(Double(percent7d))


                    var coinApiStructArrays = CoinStructure.init(idForImageString: id, fullName: name, symbol: symbol, price: Double(price), priceInBitcoin: Double(priceBtc), volume24h: Double(volume), marketCap: Double(marketCap), pctChange1h: Double(percent1h), pctChange24h: Double(percent24h), pctChange7d: Double(percent7d))
                    print("aaaaa:\(coinApiStructArrays)")
                    self.coinapistruct.append(coinApiStructArrays)
                    print("bbbbb:\(self.coinapistruct)")

                }
                completion(true)
            }
        } else {
            completion(false)
            debugPrint("AddCoinModel: getCoinInfoFunc: \(response.result.error as Any)")
        }
    }  

到目前为止,每当我想将数据传递到tableview / collectionview时,我都必须引用每个数组。

我认为必须有一个更简单的方法,所以我试图为json创建一个结构,这样我就可以将所有数据输入到一行代码中并在将来调用它而无需键入10行代码10个阵列。

STRUCT:

struct CoinStructure {
    public private(set) var idForImageString: String!
    public private(set) var fullName: String!
    public private(set) var symbol: String!
    public private(set) var price: Double!
    public private(set) var priceInBitcoin: Double!
    public private(set) var volume24h: Double!
    public private(set) var marketCap: Double!
    public private(set) var pctChange1h: Double!
    public private(set) var pctChange24h: Double!
    public private(set) var pctChange7d: Double!
} 

我确实使用了'init'功能:

init(id: String){ idForImageString = id ...} 

然后尝试创建struct的变量并将json的每个值设置为等于它

 var array = CoinStructure.init(id: id ... etc)

最后,当我打印出api的前5个结果时:

CoinStructure(idForImageString: bitcoin, fullName: Bitcoin, symbol: BTC, price: 4385.61, priceInBitcoin: 1.0, volume24h: 2766630000.0, marketCap: 72565890651.0, pctChange1h: 0.38, pctChange24h: 3.15, pctChange7d: -4.16)  

(接下来的4个是相同但不同的值......)

好的,到目前为止这没关系,但我需要的是:

CoinStructure(idForImageString: [bitcoin, litecoin], fullName: [Bitcoin, Litecoin], symbol: [BTC, LTC]...)

那么当我填充tableview / collectionview时,我可以调用indexPath.row来说出数组中的第一个索引,并从数组中拉出'litecoin''Litecoin'和'LTC'。

我觉得我这样做完全错了,而且我必须有一个简单的方法来做到这一点,而不是像我一样弄得一团糟?

非常感谢, 杰里米

1 个答案:

答案 0 :(得分:0)

这种结构的意义在于单个CoinStructure实例可以模拟单个硬币类型。您正在尝试为多种类型的硬币建模,因此您应该创建CoinStructure的多个实例。

另一方面,没有必要在名称中添加Structure。我们可以看到它是一种结构。但是,名称的其余部分Coin部分是错误的。这种结构不模拟硬币,它模拟加密货币。

此外,所有成员的可变性,以及所有成员都是隐式解包的选项,都是一个非常大的红旗。

以下是我对此进行建模的方法:

import Foundation

import Foundation

struct CryptoCurrency {
    public let idForImageString: String // FIXME: <--- what is this thing? It's really unclear
    public let fullName: String
    public let symbol: String

    public let price: Decimal
    public let priceInBitcoin: Decimal
    public let volume24h: Decimal
    public let marketCap: Decimal

    public let pctChange1h: Decimal
    public let pctChange24h: Decimal
    public let pctChange7d: Decimal

    init(
        idForImageString: String,
        fullName: String,
        symbol: String,
        price: Decimal,
        priceInBitcoin: Decimal,
        volume24h: Decimal,
        marketCap: Decimal,
        pctChange1h: Decimal,
        pctChange24h: Decimal,
        pctChange7d: Decimal
    ) {
        self.idForImageString = idForImageString
        self.fullName = fullName
        self.symbol = symbol
        self.price = price
        self.priceInBitcoin = priceInBitcoin
        self.volume24h = volume24h
        self.marketCap = marketCap
        self.pctChange1h = pctChange1h
        self.pctChange24h = pctChange24h
        self.pctChange7d = pctChange7d
    }

    init?(fromJSON: JSON) {
        guard let idForImageString = json["id"].stringValue,
            let fullName = json["name"].stringValue,
            let symbol = json["symbol"].stringValue,
            let price = json["price_\(self.API_FIAT.lowercased())"].number?.decimalValue,
            let priceInBitcoin = json["price_btc"].number?.decimalValue,
            let volume24h = json["24h_volume_\(self.API_FIAT.lowercased())"].number?.decimalValue,
            let marketCap = json["market_cap_\(self.API_FIAT.lowercased())"].number?.decimalValue,
            let pctChange1h = json["percent_change_1h"].number?.decimalValue,
            let pctChange24h = json["percent_change_24h"].number?.decimalValue,
            let pctChange7d = json["percent_change_7h"].number?.decimalValue else {
            return nil
        }

        self.init(
            idForImageString: idForImageString,
            fullName: fullName,
            symbol: symbol,
            price: price,
            priceInBitcoin: priceInBitcoin,
            volume24h: volume24h,
            marketCap: marketCap,
            pctChange1h: pctChange1h,
            pctChange24h: pctChange24h,
            pctChange7d: pctChange7d
        )
    }
} 


Alamofire.request(FULL_API).responseJSON { (response) in
    print("AddCoinModel: Full Api = \(FULL_API)")
    guard response.result.error == nil,
        let data = response.data,
        let jsonArray = JSON(data: data).array else {
        completion(false)
        debugPrint("AddCoinModel: getCoinInfoFunc: \(response.result.error as Any)")
        return
    }

    self.cryptocurrencies = jsonArray.map { json in
        guard let cryptocurrency = CryptoCurrency(fromJSON: json) else {
            //FIXME: Handle the error case appropraitely
            fatalError("This JSON doesn't represent a valid CryptoCurrency, and my author didn't handle his errors properly!'")
        }
        return cryptocurrency
    }

    print(self.cryptocurrencies)
    completion(true)
}   

以下是self.cryptocurrencies的示例:

let cryptocurrencies = [
    CoinStructure(
        idForImageString: bitcoin,  // FIXME: <--- what is this thing? It's really unclear
        fullName: "Bitcoin",
        symbol: "BTC"
        ...
    ),
    CoinStructure(
        idForImageString: litecoin,  // FIXME: <--- what is this thing? It's really unclear
        fullName: "Litecoin",
        symbol: "LTC"
        ...
    ),
]