Last active
November 13, 2024 09:09
-
-
Save SplittyDev/36a8beda8a42d39413c4b5ff16defc0d to your computer and use it in GitHub Desktop.
Currency Conversion Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2024 FiveSheep OÜ | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
import Foundation | |
import SwiftyJSON | |
private let apiBaseUrl = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies" | |
enum Currency: String, Identifiable, CaseIterable, Hashable { | |
case euro = "eur" | |
case usDollar = "usd" | |
case thaiBaht = "thb" | |
case philippinePeso = "php" | |
case vietnameseDong = "vnd" | |
case cambodianRiel = "khr" | |
var id: String { | |
self.rawValue | |
} | |
var symbol: String { | |
switch self { | |
case .euro: "€" | |
case .usDollar: "$" | |
case .thaiBaht: "฿" | |
case .philippinePeso: "₱" | |
case .vietnameseDong: "₫" | |
case .cambodianRiel: "៛" | |
} | |
} | |
/// The API URL to fetch the latest rates. | |
var url: URL { | |
return URL(string: "\(apiBaseUrl)/\(id).json")! | |
} | |
} | |
/// Cached conversion rates for a specific currency. | |
struct CachedConversionRates { | |
let createdAt: Date | |
let conversionRates: [Currency: Double] | |
/// Convert a value into the target currency. | |
func value(of value: Double, in currency: Currency) -> Double? { | |
if let conversionRate = conversionRates[currency], !conversionRate.isZero { | |
value * conversionRate | |
} else { | |
nil | |
} | |
} | |
} | |
/// Currency conversion actor. | |
final actor CurrencyConverter { | |
/// Shared instance to make use of efficient caching and refetching. | |
@MainActor static let shared = CurrencyConverter() | |
/// Conversion rate cache for various currencies. | |
private var cache: [Currency: CachedConversionRates] = [:] | |
private init() {} | |
/// Convert a value from a source currency into a target currency. | |
func convert(_ value: Double, from sourceCurrency: Currency, to targetCurrency: Currency) async throws -> Double? { | |
// Skip conversion if value is `0` | |
if value.isZero { | |
return value | |
} | |
// Skip conversion if source currency is the same as target currency | |
if sourceCurrency == targetCurrency.rawValue { | |
return value | |
} | |
// Fetch conversion rates and apply conversion | |
let rates = try await getOrFetchRates(for: sourceCurrency) | |
return rates.value(of: value, in: targetCurrency) | |
} | |
/// Get latest currency rates with caching applied. | |
/// | |
/// Refetches automatically on missing or stale cache. | |
func getOrFetchRates(for sourceCurrency: Currency) async throws -> CachedConversionRates { | |
// Try to find cached conversion rates | |
if let cachedConversionRates = cache[sourceCurrency] { | |
// Fetch new rates if the cache is stale | |
if cachedConversionRates.createdAt.timeIntervalUntilNow > CacheExpirationTime { | |
try await forceFetchRates(for: sourceCurrency) | |
} | |
// Otherwise, return the cached rates | |
else { | |
cachedConversionRates | |
} | |
} | |
// Otherwise, fetch new rates | |
else { | |
try await forceFetchRates(for: sourceCurrency) | |
} | |
} | |
/// Get the latest rates regardless of cache freshness. | |
private func forceFetchRates(for sourceCurrency: Currency) async throws -> CachedConversionRates { | |
// Fetch conversion rate JSON | |
let (data, _) = try await URLSession.shared.data(from: sourceCurrency.url) | |
let json = try JSON(data: data) | |
// Parse JSON into dictionary of [CurrencyId: ConversionRate] | |
let conversionRates = json[sourceCurrency.id] | |
.dictionaryValue | |
.compactMapValues(\.double) | |
let cachedRates = CachedConversionRates( | |
createdAt: Date.now, | |
conversionRates: conversionRates | |
) | |
/// Update rates in cache | |
self.cache[sourceCurrency] = cachedRates | |
return cachedRates | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment