Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroki Nagasawa committed May 24, 2021
0 parents commit 6bd664e
Show file tree
Hide file tree
Showing 12 changed files with 500 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
91 changes: 91 additions & 0 deletions .swiftpm/xcode/xcshareddata/xcschemes/currency-converter.xcscheme
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1250"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "currency-converter"
BuildableName = "currency-converter"
BlueprintName = "currency-converter"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "currency-converterTests"
BuildableName = "currency-converterTests"
BlueprintName = "currency-converterTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "currency-converterTests"
BuildableName = "currency-converterTests"
BlueprintName = "currency-converterTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "currency-converter"
BuildableName = "currency-converter"
BlueprintName = "currency-converter"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2021 Hiroki Nagasawa

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.
21 changes: 21 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// swift-tools-version:5.3

import PackageDescription

let package = Package(
name: "CurrencyConverter",
platforms: [.iOS(.v13), .macOS(.v10_15)],
products: [
.library(
name: "CurrencyConverter",
targets: ["CurrencyConverter"]),
],
targets: [
.target(
name: "CurrencyConverter",
dependencies: []),
.testTarget(
name: "CurrencyConverterTests",
dependencies: ["CurrencyConverter"]),
]
)
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# currency-converter

A simple currency converter library using the XML data from [European Central Bank](https://www.ecb.europa.eu/home/html/index.en.html).
26 changes: 26 additions & 0 deletions Sources/CurrencyConverter/CurrencyConverter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation

/// The converter to fetch foreign exchange reference rates from European Central Bank (ECB).
/// Source: https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html
public class CurrencyConverter {
private let parser: ReferenceRatesXMLParser

public init() {
parser = ReferenceRatesXMLParser()
}

public init(data: Data) {
parser = ReferenceRatesXMLParser(data: data)
}

/// Fetch the latest reference rates from the source.
public func fetch(completion: @escaping (Result<ReferenceRates, XMLParserError>) -> Void) {
parser.callbacks.parseSucceeded = { referenceRates in
completion(.success(referenceRates))
}
parser.callbacks.parseErrorOccurred = { error in
completion(.failure(error))
}
parser.parse()
}
}
14 changes: 14 additions & 0 deletions Sources/CurrencyConverter/CurrencyRate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Foundation

/// Represents the currency rate that has the currency code and rate.
public struct CurrencyRate: Codable, Hashable {
/// The currency code, such as "USD", "EUR", and "JPY".
public let currencyCode: String
/// The currency rate in the currency code.
public let rate: Double

public init(currencyCode: String, rate: Double) {
self.currencyCode = currencyCode
self.rate = rate
}
}
79 changes: 79 additions & 0 deletions Sources/CurrencyConverter/ReferenceRates.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import Foundation

/// Represents the reference rates that has the date code and rates.
public struct ReferenceRates: Codable, Hashable {
private static let defaultCurrencyCode = "EUR"

/// The date string, e.g. 2021-05-13.
public let date: String
var rates: [CurrencyRate]

public init(date: String, rates: [CurrencyRate]) {
self.date = date
self.rates = rates
}

/// Returns array of currency rates from the given parameters.
///
/// - Parameters:
/// - amount: The amount of the currency. The default is 1.
/// - baseCurrencyCode: The base currency code for the currency rates. The default is "EUR".
public func rates(amount: Double = 1, baseCurrencyCode: String = "EUR") -> [CurrencyRate] {
guard Locale.isoCurrencyCodes.contains(baseCurrencyCode) else {
return []
}

if baseCurrencyCode == Self.defaultCurrencyCode {
return rates
} else {
var newRates = rates.filter { $0.currencyCode != baseCurrencyCode }

if let rate = rate(fromCurrencyCode: baseCurrencyCode, toCurrencyCode: Self.defaultCurrencyCode) {
newRates.append(.init(currencyCode: Self.defaultCurrencyCode, rate: rate))
}

newRates = newRates.compactMap {
if let rate = rate(fromCurrencyCode: baseCurrencyCode, toCurrencyCode: $0.currencyCode) {
return .init(currencyCode: $0.currencyCode, rate: amount * rate)
}
return nil
}

return newRates
}
}

/// Returns the rate from the given parameters.
///
/// - Parameters:
/// - amount: The amount of the currency. The default is 1.
/// - fromCurrencyCode: The currency code that you'd like to converted from.
/// - toCurrencyCode: The currency code that you'd like to converted to.
public func rate(amount: Double = 1, fromCurrencyCode: String, toCurrencyCode: String) -> Double? {
guard fromCurrencyCode != toCurrencyCode else {
return amount
}

let isoCurrencyCodes = Locale.isoCurrencyCodes

guard isoCurrencyCodes.contains(fromCurrencyCode) && isoCurrencyCodes.contains(toCurrencyCode) else {
return nil
}

if let rate = rates.first(where: { $0.currencyCode == toCurrencyCode })?.rate, fromCurrencyCode == Self.defaultCurrencyCode {
return amount * rate
}

if let rate = rates.first(where: { $0.currencyCode == fromCurrencyCode })?.rate, toCurrencyCode == Self.defaultCurrencyCode {
return amount * 1 / rate
}

if let fromRate = rates.first(where: { $0.currencyCode == fromCurrencyCode })?.rate,
let toRate = rates.first(where: { $0.currencyCode == toCurrencyCode })?.rate {
let actualRate = toRate / fromRate
return amount * actualRate
}

return nil
}
}
95 changes: 95 additions & 0 deletions Sources/CurrencyConverter/ReferenceRatesXMLParser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Foundation

class ReferenceRatesXMLParser: NSObject, XMLParserDelegate {
private static let defaultXMLURL = URL(string: "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")!

private let parser: XMLParser?

private var resultDate: String?
private var resultRates: [CurrencyRate] = []
var callbacks = Callbacks()

struct Callbacks {
var parseSucceeded: ((ReferenceRates) -> Void)?
var parseErrorOccurred: ((XMLParserError) -> Void)?
}

enum XMLParserKeys: String {
case time
case currency
case rate
}

init(contentsOf url: URL = defaultXMLURL) {
parser = XMLParser(contentsOf: url)
super.init()
parser?.delegate = self
}

init(data: Data) {
parser = XMLParser(data: data)
super.init()
parser?.delegate = self
}

func parse() {
parser?.parse()
}

// MARK: - XMLParserDelegate

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
guard elementName == "Cube", !attributeDict.isEmpty else {
// Skip throwing an error as there will be element names to ignore,
// such as 'gesmes:Envelope', 'gesmes:subject', and so on.
return
}

var currencyRate: (currencyCode: String?, rate: Double?)

for attribute in attributeDict {
switch attribute.key {
case XMLParserKeys.time.rawValue:
let datePattern = #"^\d{4}[-]\d{2}[-]\d{2}$"# // 2021-05-07
if attribute.value.range(of: datePattern, options: .regularExpression) != nil {
resultDate = attribute.value
} else {
callbacks.parseErrorOccurred?(.custom("Unexpected time value: \(attribute.value)"))
return
}
case XMLParserKeys.rate.rawValue:
if let rate = Double(attribute.value) {
currencyRate.rate = rate
} else {
callbacks.parseErrorOccurred?(.custom("Unexpected rate value: \(attribute.value)"))
return
}
case XMLParserKeys.currency.rawValue:
if Locale.isoCurrencyCodes.contains(attribute.value) {
currencyRate.currencyCode = attribute.value
} else {
callbacks.parseErrorOccurred?(.custom("Unexpected currency value: \(attribute.value)"))
return
}
default:
break
}
}

if let currencyCode = currencyRate.currencyCode, let rate = currencyRate.rate {
resultRates.append(.init(currencyCode: currencyCode, rate: rate))
}
}

func parserDidEndDocument(_ parser: XMLParser) {
if let resultDate = resultDate {
callbacks.parseSucceeded?(.init(date: resultDate, rates: resultRates))
} else {
callbacks.parseErrorOccurred?(.custom("Parse failed"))
}
}

func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
callbacks.parseErrorOccurred?(.general(parseError))
}
}
6 changes: 6 additions & 0 deletions Sources/CurrencyConverter/XMLParserError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foundation

public enum XMLParserError: Error {
case general(Error)
case custom(String)
}

0 comments on commit 6bd664e

Please sign in to comment.