Last active
May 28, 2021 08:15
-
-
Save yycking/168d8c19cc9aebfbe00751afdf177baf to your computer and use it in GitHub Desktop.
Let Version compare as easy as float
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
import Combine | |
import Foundation | |
struct Version: Codable { | |
var stringValue: String | |
init(rawValue: String) { | |
stringValue = rawValue | |
} | |
init(from decoder: Decoder) throws { | |
stringValue = try decoder.singleValueContainer().decode(String.self) | |
} | |
} | |
extension Version { | |
static var current: Version { | |
let version = Bundle.main.infoDictionary!["CFBundleVersion"] as! String | |
return Version(rawValue: version) | |
} | |
struct ItunesLookup: Codable { | |
let results: [Itunes] | |
struct Itunes: Codable { | |
let version: Version | |
let trackId: Int | |
var url: URL? { | |
return URL(string: "itms-apps://itunes.apple.com/app/id\(trackId)") | |
} | |
} | |
} | |
static var itunes: AnyPublisher<ItunesLookup.Itunes?, Error> { | |
let bundleIdentifier = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String | |
let link = "https://itunes.apple.com/lookup?bundleId=\(bundleIdentifier)" | |
.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! | |
let url = URL(string: link)! | |
return URLSession.shared | |
.dataTaskPublisher(for: url) | |
.map { $0.data } | |
.decode(type: ItunesLookup.self, decoder: JSONDecoder()) | |
.print() | |
.map { $0.results.first } | |
.eraseToAnyPublisher() | |
} | |
} | |
extension Version: Comparable { | |
static func < (lhs: Version, rhs: Version) -> Bool { | |
return lhs.stringValue.compare(rhs.stringValue, options: .numeric) == .orderedAscending | |
} | |
static func == (lhs: Version, rhs: Version) -> Bool { | |
return lhs.stringValue.compare(rhs.stringValue, options: .numeric) == .orderedSame | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment