Error handling optimization - swift

I am just playing with the new error handling in version 2.0. And I now have the following functions with a throw:
func decodeHTML(HTML: String) throws {
guard let remove : String? = HTML.componentsSeparatedByString("<div id=\"loading\" style=\"display: none;\">")[0] else { throw DecodeError.MatchError }
guard var splitter : [String]? = remove!.componentsSeparatedByString("<div class=\"info\">") else { throw DecodeError.MatchError }
if splitter!.count > 0 { splitter!.removeFirst() }
if splitter!.count > 0 { splitter!.removeLast() }
if splitter!.count > 0 {
for HTMLmessage in splitter! {
guard var splitter2 : [String]? = HTMLmessage.componentsSeparatedByString("</td><td>Besked fra ") else { throw DecodeError.MatchError }
guard let author : String? = (splitter2![1].componentsSeparatedByString("</tr>"))[0] else { throw DecodeError.MatchError }
guard let date : String? = (splitter2![0].componentsSeparatedByString("<td width=\"25%\">"))[1] else { throw DecodeError.MatchError }
guard let title : String? = HTMLmessage.componentsSeparatedByString("\"><b>")[1].componentsSeparatedByString("</b></a></td></tr>")[0] else { throw DecodeError.MatchError }
guard var string : String? = HTMLmessage.componentsSeparatedByString("</a></td></tr><tr><td colspan=2>")[1].componentsSeparatedByString("</td></tr></table></div>")[0] else { throw DecodeError.MatchError }
string = string!.stringByReplacingOccurrencesOfString("</p><p>", withString: "\n")
string = string!.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
self.messages.append(message(author, date, title, string))
}
} else {
throw DecodeError.MatchError
}
}
But I wonder, do I really have to guard everytime something can go wrong? Is there an easier way to throw an error if one of the lines fails?

I cleaned up your function a bit:
extension String {
func split(string: String) -> [String] { return componentsSeparatedByString(string) }
}
extension Array {
var second : Element? { return dropFirst().first }
}
func decodeHTML(HTML: String) throws {
guard let
splitter = HTML
.split("<div id=\"loading\" style=\"display: none;\">").first?
.split("<div class=\"info\">").dropFirst().dropLast()
where !splitter.isEmpty else {
throw DecodeError.MatchError
}
for HTMLmessage in splitter {
let splitter2 = HTMLmessage.split("</td><td>Besked fra ")
guard let
author = splitter2.second?
.split("</tr>").first,
date = splitter2.first?
.split("<td width=\"25%\">").second,
title = HTMLmessage
.split("\"><b>").second?
.split("</b></a></td></tr>").first,
string = HTMLmessage
.split("</a></td></tr><tr><td colspan=2>").second?
.split("</td></tr></table></div>").first?
.stringByReplacingOccurrencesOfString("</p><p>", withString: "\n")
.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
else {
throw DecodeError.MatchError
}
let message = (author, date, title, string)
}
}
You can use dropFirst, dropLast and first to get access to elements safely. You should probably really use a HTML parsing library though.

I'd recommend you to create a wrapper function:
func componentsSeparatedByString(string: String) throws -> String {
let texts = HTMLmessage.componentsSeparatedByString(string)
if texts.count > 0
return texts[0]
} else {
throw DecodeError.MatchError
}
}
And now you can call this function multiple times and use single catch block:
do {
let text1 = try componentsSeparatedByString("text1")
let text2 = try componentsSeparatedByString("text2")
let text3 = try componentsSeparatedByString("text3")
} catch {
print("Something went wrong!")
}

Related

Realm accessed from incorrect thread occasional

I have this function
class func addCVals(_ criteres: [[AnyHashable: Any]], _ type: String) {
DispatchQueue.global(qos: .background).async {
autoreleasepool {
if criteres.count > 0 {
if let realm = DBTools.getRealm() {
do {
try realm.transaction {
let oldValues = CriteresVal.objects(in: realm, where: "type = '\(type)'")
if oldValues.count > 0 {
realm.deleteObjects(oldValues)
}
for critere in criteres {
let cval = CriteresVal(critere, type)
if let c = cval {
realm.addOrUpdate(c)
}
}
}
} catch {
DebugTools.record(error: error)
}
realm.invalidate()
}
}
}
}
}
The request that get oldValues occasionally cause an error
Realm accessed from incorrect thread
I don't understand why as I get a new Realm before with this lines:
if let realm = DBTools.getRealm()
My function getRealm:
class func getRealm() -> RLMRealm? {
if !AppPreference.lastAccount.elementsEqual("") {
let config = RLMRealmConfiguration.default()
do {
return try RLMRealm(configuration: config)
} catch {
DebugTools.record(error: error)
DispatchQueue.main.async {
Notifier.showNotification("", NSLocalizedString("UNKNOWN_ERROR_DB", comment: ""), .warning)
}
}
}
return nil
}
CriteresVal is an RLMObject that is composed of this:
#objcMembers
public class CriteresVal: RLMObject {
dynamic var cvalId: String?
dynamic var type: String?
dynamic var text: String?
dynamic var compositeKey: String?
override public class func primaryKey() -> String {
return "compositeKey"
}
private func updatePrimaryKey() {
self.compositeKey = "\(self.cvalId ?? "")/\(self.type ?? "")"
}
required init(_ cvalue: [AnyHashable: Any]?, _ type: String) {
super.init()
if let values = cvalue {
if let cvalId = values["id"] as? String {
self.cvalId = cvalId
} else if let cvalId = values["id"] as? Int {
self.cvalId = "\(cvalId)"
}
self.type = type
if let text = values["text"] as? String {
self.text = text
}
}
updatePrimaryKey()
}
func generateDico() -> [String: Any] {
var dicoSortie = [String: Any]()
if let realm = self.realm {
realm.refresh()
}
if let value = cvalId {
dicoSortie["id"] = value
}
if let value = type {
dicoSortie["type"] = value
}
if let value = text {
dicoSortie["text"] = value
}
return dicoSortie
}
}
compositeKey is the primary key which included cvalId and type
Thanks for help.

How do I parse a CSV file, to make it easily accessable for tableView?

I wrote a CSV file that contains a set of items by row. I used a class like so to form the CSV file, here is the code for creating the file:
class SymptomData: NSObject {
var symptom: String = ""
var severity: String = ""
var comment: String = ""
var timestamp: String = ""
}
var symptom_data = [SymptomData]()
var symptomData: SymptomData!
func writeTrackedSymptomValues(symptom: String, comment: String, time: String, timestamp: String) {
symptomData = SymptomData()
for _ in 0..<5 {
symptomData.symptom = symptom
symptomData.severity = self.severity
symptomData.comment = comment
symptomData.timestamp = timestamp
symptom_data.append(symptomData!)
}
createCSV()
}
var logFile: URL? {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
let fileName = "symptom_data.csv"
return documentsDirectory.appendingPathComponent(fileName)
}
func createCSV() {
guard let logFile = logFile else {
return
}
guard let data = ("\(symptomData.symptom),\(symptomData.severity),\(symptomData.comment),\(symptomData.timestamp)\n").data(using: String.Encoding.utf8) else { return }
if FileManager.default.fileExists(atPath: logFile.path) {
if let fileHandle = try? FileHandle(forWritingTo: logFile) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
}
} else {
var csvText = "Symptom,Severity,Comment,Time\n"
let newLine = "\(symptomData.symptom),\(symptomData.severity),\(symptomData.comment),\(symptomData.timestamp)\n"
csvText.append(newLine)
do {
try csvText.write(to: logFile, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(logFile ?? "not found")
}
}
The CSV file looks like this:
Now I would like to read the file, and add each row to my table view. Ideally, I would like to be able to access each row easily like so:
row0.symptom = symptomData[0].symptom
row0.comment = symptomData[0].comment
etc. But I am not sure how to parse the data back into my class, I would also like it like this so that I can reorder them by timestamp.
Here is how I am parsing the data so far:
func readCSV() {
guard let logFile = logFile else {
return
}
if FileManager.default.fileExists(atPath: logFile.path) {
if let fileHandle = try? FileHandle(forWritingTo: logFile) {
fileHandle.seekToEndOfFile()
fileHandle.readDataToEndOfFile()
fileHandle.closeFile()
print("symptom_data exists")
do {
let file = try String(contentsOf: logFile)
let rows = file.components(separatedBy: .newlines)
for row in rows {
let fields = row.replacingOccurrences(of: "\"", with: "").components(separatedBy: ",")
print(fields)
}
} catch {
print(error)
}
}
} else {
print("No symptom_data File.")
}
}
This prints this:
["Symptom", "Severity", "Comment", "Time"]
["Anxiety", "Severe", "test", "1592333677"]
["Anxiety", "Mild", "test2", "1592333686"]
["Fatigue", "Mild", "test3", "1592160840"]
["Electric shock sensations (Brain Zaps)", "Mild", "", "1592333820"]
["Anxiety", "Severe", "", "1592336985"]
How can I get each row into a class or struct so I can easily add it to the table view, or is there a better way to do it?

How to get context of a sentence

So i'm working a an app that can patch words that are broken.
Lets take:
mny people say there is a error in this sentence
With swift here we can us UITextChecker and get a wonderful result of what the word mny could actually be... However, i actually get a couple of choices, one of which is many and among the other you have money so obviously money wouldn't fit in very well in this sentence. Are there any way to check if the sentence itself is logical?
Consider that this still needs to be improved. I updated this swift 3 solution to Swift 5. Worth to mention that it was originally inspired by this python tutorial
Create a new iOS project, add there a text file named bigtext.txt which will contain this text. This will be our "learning" dictionary.
Then in ViewController:
import UIKit
import NaturalLanguage
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let inputString = "mny people say there is a error in this sentence"
var newString = inputString
// Read a text file and "study" the model
guard let path = Bundle.main.path(forResource: "bigtext", ofType: "txt") else {
print("Path not available")
return
}
let checker = SpellChecker(contentsOfFile: path)
// better to use this to iterate between words in a sentence
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = inputString
tokenizer.enumerateTokens(in: inputString.startIndex..<inputString.endIndex) { tokenRange, _ in
let word = String(inputString[tokenRange])
let checked = checker?.correct(word: word)
let candidates = checker?.candidates(word: word)
if word == checked {
print("\(word) unchanged")
} else {
if let checked = checked {
newString.replaceSubrange(tokenRange, with: checked)
}
print("Correct:\t\(word) -> \(String(describing: checked))")
print("Candidates:\t\(word) -> \(String(describing: candidates))")
}
return true
}
print("Result: \(newString)")
}
}
func edits(word: String) -> Set<String> {
if word.isEmpty { return [] }
let splits = word.indices.map {
(word[word.startIndex..<$0], word[$0..<word.endIndex])
}
let deletes = splits.map { $0.0 + String($0.1.dropFirst()) }
let transposes: [String] = splits.map { left, right in
if let fst = right.first {
let drop1 = String(right.dropFirst())
if let snd = drop1.first {
let drop2 = String(drop1.dropFirst())
return "\(left)\(snd)\(fst)\(drop2)"
}
}
return ""
}.filter { !$0.isEmpty }
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let replaces = splits.flatMap { left, right in
alphabet.map { "\(left)\($0)\(String(right.dropFirst()))" }
}
let inserts = splits.flatMap { left, right in
alphabet.map { "\(left)\($0)\(right)" }
}
let setString = [String(deletes.first!)] + transposes + replaces + inserts
return Set(setString)
}
struct SpellChecker {
var knownWords: [String:Int] = [:]
mutating func train(word: String) {
if let idx = knownWords[word] {
knownWords[word] = idx + 1
}
else {
knownWords[word] = 1
}
}
init?(contentsOfFile file: String) {
do {
let text = try String(contentsOfFile: file, encoding: .utf8).lowercased()
let words = text.unicodeScalars.split(whereSeparator: { !("a"..."z").contains($0) }).map { String($0) }
for word in words { self.train(word: word) }
}
catch {
return nil
}
}
func knownEdits2(word: String) -> Set<String>? {
var known_edits: Set<String> = []
for edit in edits(word: word) {
if let k = known(words: edits(word: edit)) {
known_edits.formUnion(k)
}
}
return known_edits.isEmpty ? nil : known_edits
}
func known<S: Sequence>(words: S) -> Set<String>? where S.Iterator.Element == String {
let s = Set(words.filter { self.knownWords.index(forKey: $0) != nil })
return s.isEmpty ? nil : s
}
func candidates(word: String) -> Set<String> {
guard let result = known(words: [word]) ?? known(words: edits(word: word)) ?? knownEdits2(word: word) else {
return Set<String>()
}
return result
}
func correct(word: String) -> String {
return candidates(word: word).reduce(word) {
(knownWords[$0] ?? 1) < (knownWords[$1] ?? 1) ? $1 : $0
}
}
}
Will output you:
Correct: mny -> Optional("may")
Candidates: mny -> Optional(Set(["any", "ny", "may", "many"]))
people unchanged
say unchanged
there unchanged
is unchanged
a unchanged
error unchanged
in unchanged
this unchanged
sentence unchanged
Result: may people say there is a error in this sentence
Please, consider that we took first correction candidate.
Need first to clarify ourselves the word order and understand the sentence context.

How do I store values ​by referring to classes in FireStore

I'm creating a chat app using the MessageKit library in Swift 4.2 and FireStore.
My problem is that I can't store data acquired by real time communication using addSnapshotListener in the Message class and confirmed the contents of the class, but I do not think it is wrong.
messageListener is working properly. When handleDocumentChange is executed, it returns nil.
I checked the return value with document.data (), but the value returned.
How do I store values ​​by referring to classes?
guard var message = Message (document: change.document) else {
print ("return Message")
return
}
The data entered for FireStore is as follows
{
"channels": [{
"MOuL1sdbrnh0x1zGuXn7": { // channel id
"name": "Puppies",
"thread": [{
"3a6Fo5rrUcBqhUJcLsP0": { // message id
"content": "Wow, that's so cute!",
"created": "May 12, 2018 at 10:44:11 PM UTC-5",
"senderID": "YCrPJF3shzWSHagmr0Zl2WZFBgT2",
"senderUsername": "naturaln0va",
"recipientProfilePictureURL":"URL",
"recipientID":"ezample",
"recipientUsername" :"A"
"recipientProfilePictureURL":"aaaaa"
},
}]
},
}]
}
That's my message class:
class Message: MessageType {
var id: String?
var sentDate: Date
var kind: MessageKind
lazy var sender: Sender = Sender(id: atcSender.uid ?? "No Id", displayName: atcSender.uid ?? "No Name")
var atcSender: User
var recipient: User
var messageId: String {
return id ?? UUID().uuidString
}
var image: UIImage? = nil
var downloadURL: URL? = nil
let content: String
init(messageId: String, messageKind: MessageKind, createdAt: Date, atcSender: User, recipient: User) {
self.id = messageId
self.kind = messageKind
self.sentDate = createdAt
self.atcSender = atcSender
self.recipient = recipient
switch messageKind {
case .text(let text):
self.content = text
default:
self.content = ""
}
}
init(user: User, image: UIImage) {
self.image = image
content = ""
sentDate = Date()
id = nil
self.kind = MessageKind.text("xxx")
self.atcSender = user
self.recipient = user
}
init?(document: QueryDocumentSnapshot) {
let data = document.data()
guard let sentDate = data["created"] as? Date else {
return nil
}
guard let senderID = data["senderID"] as? String else {
return nil
}
guard let senderUsername = data["senderUsername"] as? String else {
return nil
}
guard let senderProfilePictureURL = data["senderProfilePictureURL"] as? String else {
return nil
}
guard let recipientID = data["recipientID"] as? String else {
return nil
}
guard let recipientUsername = data["recipientUsername"] as? String else {
return nil
}
guard let recipientProfilePictureURL = data["recipientProfilePictureURL"] as? String else {
return nil
}
id = document.documentID
self.sentDate = sentDate
self.atcSender = User(uid: senderID, username: senderUsername, firstname: "", lastname: "", email: "", profileUrl: senderProfilePictureURL)
self.recipient = User(uid: recipientID, username: recipientUsername, firstname: "", lastname: "", email: "", profileUrl: recipientProfilePictureURL)
if let content = data["content"] as? String {
self.content = content
downloadURL = nil
} else if let urlString = data["url"] as? String, let url = URL(string: urlString) {
downloadURL = url
self.content = ""
} else {
return nil
}
self.kind = MessageKind.text(content)
}
required init(jsonDict: [String: Any]) {
fatalError()
}
var description: String {
return self.messageText
}
var messageText: String {
switch kind {
case .text(let text):
return text
default:
return ""
}
}
var channelId: String {
let id1 = (recipient.username ?? "")
let id2 = (atcSender.username ?? "")
return id1 < id2 ? id1 + id2 : id2 + id1
}
}
extension Message: DatabaseRepresentation {
var representation: [String : Any] {
var rep: [String : Any] = [
"created": sentDate,
"senderID": atcSender.uid ?? "",
"senderUsername": atcSender.username ?? "",
"senderProfilePictureURL": atcSender.profileUrl ?? "",
"recipientID": recipient.uid ?? "",
"recipientUsername": recipient.username ?? "",
"recipientProfilePictureURL": recipient.profileUrl ?? "",
]
if let url = downloadURL {
rep["url"] = url.absoluteString
} else {
rep["content"] = content
}
return rep
}}extension Message: Comparable {
static func == (lhs: Message, rhs: Message) -> Bool {
return lhs.id == rhs.id
}
static func < (lhs: Message, rhs: Message) -> Bool {
return lhs.sentDate < rhs.sentDate
}
}
ChatViewController:
import UIKit
import MessageKit
import MessageInputBar
import Firebase
import FirebaseFirestore
import FirebaseAuth
class ChatViewController: MessagesViewController {
private let db = Firestore.firestore()
private var reference: CollectionReference?
private var messages: [Message] = []
private var messageListener: ListenerRegistration?
private let user: User
private let channel: Channel
let uid = Auth.auth().currentUser?.uid
init(user: User, channel: Channel) {
self.user = user
self.channel = channel
super.init(nibName: nil, bundle: nil)
title = channel.name
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
messageListener?.remove()
}
override func viewDidLoad() {
super.viewDidLoad()
guard let id = channel.id else {
navigationController?.popViewController(animated: true)
return
}
reference = db.collection(["channels", id, "thread"].joined(separator: "/"))
// reference?.addSnapshotListener { querySnapshot, error in
// guard let snapshot = querySnapshot else {
// print("Error fetching snapshots: \(error!)")
// return
// }
// snapshot.documentChanges.forEach { diff in
// if (diff.type == .added) {
// print("New city: \(diff.document.data())")
// }
// if (diff.type == .modified) {
// print("Modified city: \(diff.document.data())")
// }
// if (diff.type == .removed) {
// print("Removed city: \(diff.document.data())")
// }
// }
// }
messageListener = reference?.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error listening for channel updates: \(error?.localizedDescription ?? "No error")")
return
}
snapshot.documentChanges.forEach { change in
self.handleDocumentChange(change)
print("handleDocumentChange")
}
}
self.navigationItem.title = title
messageInputBar.delegate = self
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
messageInputBar.sendButton.tintColor = UIColor.lightGray
//scrollsToBottomOnKeyboardBeginsEditing = true // default false
//maintainPositionOnKeyboardFrameChanged = true // default false
}
private func save(_ message: Message) {
reference?.addDocument(data: message.representation) { error in
if let e = error {
print("Error sending message: \(e.localizedDescription)")
return
}
self.messagesCollectionView.scrollToBottom()
}
}
private func insertNewMessage(_ message: Message) {
guard !messages.contains(message) else {
return
}
messages.append(message)
messages.sort()
let isLatestMessage = messages.index(of: message) == (messages.count - 1)
let shouldScrollToBottom = messagesCollectionView.isAtBottom && isLatestMessage
messagesCollectionView.reloadData()
if shouldScrollToBottom {
DispatchQueue.main.async {
self.messagesCollectionView.scrollToBottom(animated: true)
}
}
}
private func handleDocumentChange(_ change: DocumentChange) {
guard var message = Message(document: change.document) else {
print("return Message")
return
}
switch change.type {
case .added:
print("add Message")
insertNewMessage(message)
default:
break
}
}
}
Console prints
New city: ["senderUsername": panyayan,
"senderID": RAMIqHAVeoU4TKkm3FDw7XUwgym2,
"created": FIRTimestamp:seconds=1544623185 nanoseconds=412169933>,
"recipientUsername": panyayan,
"content": AAA,
"recipientID": RAMIqHAVeoU4TKkm3FDw7XUwgym2,
"recipientProfilePictureURL": https:,
"senderProfilePictureURL": https:]
return Message
handleDocumentChange
Dont know if you still need it but:
The document.data() field created is a FIRTimestamp.
When you try to init the Message object you use
guard let sentDate = data["created"] as? Date else {
return nil
}
Thats might be a reason, why your object is nil.
Try something like
guard let sentTimestamp = data["created"] as? Timestamp else {
return nil
}
...
self.sentDate = sentTimestamp.dateValue()

iOS - Converting String to Double

So i am fetching from fire base config data and trying to manipulate it as so.
This is my struct :
struct FireBaseConfiguration: Codable {
var updateTime: String = ""
var iOSMinVersionForceUpdate: String = ""
var iOSMinVersionMessageUpdate: String = ""
var iOSMinFirmwareVersion: String = ""
var privacyPolicyUrlFireBase: String = ""
var termOfUseUrlFireBase: String = ""
}
This is my parser method:
func fireBaseConfigVersionMapParser(dataString: String, version: String) -> FireBaseConfiguration? {
var fireBaseConfiguration: FireBaseConfiguration?
let data = dataString.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? NSDictionary {
let model = jsonArray.object(forKey: version)
let data = try JSONSerialization.data(withJSONObject: model!, options: .prettyPrinted)
do {
let parsedModel = try JSONDecoder().decode(FireBaseConfiguration.self, from: data)
print("parsedModel is: \(parsedModel)")
fireBaseConfiguration = parsedModel
} catch let error{
print(error)
}
} else {
print("bad json")
}
} catch let error{
print(error)
}
return fireBaseConfiguration
}
And this is the implementation in the vc:
self.remoteConfig?.fetch(withExpirationDuration: 0, completionHandler: { [unowned self] (status, error) in
if status == .success {
self.remoteConfig?.activateFetched()
guard let configVersionMap = self.remoteConfig?.configValue(forKey: "iOSConfigVersionMap").stringValue else { return }
if let configModel = self.parser.fireBaseConfigVersionMapParser(dataString: configVersionMap, version: self.getCurrentAppVersion()!) {
print(configModel)
print(configModel.iOSMinVersionForceUpdate)
print(configModel.iOSMinVersionMessageUpdate)
var doubleForceUpdate = Double(configModel.iOSMinVersionForceUpdate)
var doubleMessageUpdate = Double(configModel.iOSMinVersionMessageUpdate)
print(doubleForceUpdate)
print(doubleMessageUpdate)
}
} else {
print("Config not fetched")
print("Error: \(error?.localizedDescription ?? "No error available.")")
}
})
so the prints are so:
FireBaseConfiguration(updateTime: "13/7/2018", iOSMinVersionForceUpdate: "1.0.2", iOSMinVersionMessageUpdate: "1.0.2", iOSMinFirmwareVersion: "1.0.1", privacyPolicyUrlFireBase: "https://www.name.com/corporate/privacy-policy", termOfUseUrlFireBase: "https://www.name.com/corporate/terms-of-use")
1.0.2
1.0.2
nil
nil
any ideas?
It is a simple String, but it's not actually a valid Double (Double values do not have two decimal places). So this is why it is failing.
What I think you actually need is the ability to compare version numbers, there are a number of other answers on the site that can show you how to do this:
Compare two version strings in Swift
Compare version numbers in Objective-C
So you can just keep your version numbers as a String