swift 在列表中限制API请求

pkln4tw6  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(99)

我有一个应用程序,我在那里做一个API调用,允许我从网站上获取货币。它代表了所有的货币,但是我需要将它们限制在3个“USD”,“KZT”,“AED”,“RUB”。
我的fetching代码如下:

import SwiftUI

class FetchData: ObservableObject {

@Published var coversionData: [Currency] = []
@Published var baseCode = "USD"

 init() {
        fetch()
    }
    
func fetch() {
    
    let url = "https://open.exchangerate-api.com/v6/latest?base=\(baseCode)"
    
    let session = URLSession(configuration: .default)
    session.dataTask(with: URL(string: url)!) { data, _, _ in
        
        guard let JSONData = data else {return}
        
        do {
            let conversion = try JSONDecoder().decode(Conversion.self, from: JSONData)
            
            DispatchQueue.main.async {
                self.coversionData = conversion.rates.compactMap({ (key,value) -> Currency? in
                    return Currency(currencyName: key, currencyValue: value)
                })
            }
        }
        catch {
            print(error)
        }
    }
    .resume()
}

func updateData(baseCode: String) {
    
    self.baseCode = baseCode
    
    self.coversionData.removeAll()
    fetch()
    
}
}

字符串
有人可以与我的文档,教程,GitHub链接分享任何我只需要了解如何只显示三个类别的东西吗?
例如,请!

lo8azlld

lo8azlld1#

//Properties
     @Published var filteredCurrency = "KZT"

 //.Filter call
.filter({ Currency in
                        Currency.currencyName == self.filteredCurrency
                    })

字符串
这是一个答案,因为我相信我调用了一个.filter,并解决了Currency.currency名称将等于我给它的一个属性
现在我的代码看起来像这样

import SwiftUI

class FetchData: ObservableObject {
    
    @Published var coversionData: [Currency] = []
    @Published var baseCode = "USD"
    @Published var filteredCurrency = "KZT"
    
init() {
    fetch()
}

func fetch() {
    
    let url = "https://open.exchangerate-api.com/v6/latest?base=\(baseCode)"
    
    let session = URLSession(configuration: .default)
    session.dataTask(with: URL(string: url)!) { data, _, _ in
        
        guard let JSONData = data else {return}
        
        do {
            let conversion = try JSONDecoder().decode(Conversion.self, from: JSONData)
            
            DispatchQueue.main.async {
                self.coversionData = conversion.rates.compactMap({ (key,value) -> Currency? in
                    return Currency(currencyName: key, currencyValue: value)
                })
                .filter({ Currency in
                    Currency.currencyName == self.filteredCurrency
                })
            }
        }
        catch {
            print(error)
        }
    }
    .resume()
}

func updateData(baseCode: String) {
    
    self.baseCode = baseCode
    

       self.coversionData.removeAll()
        fetch()
        
    }
    
}

相关问题