Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
dropPrefix()
// this particular API/implementation for demonstration only,
// not necessarily quite what will be proposed
extension Collection where SubSequence == Self {
/// Drop n elements from the front of `self` in-place,
/// returning the dropped prefix.
mutating func dropPrefix(_ n: IndexDistance) -> SubSequence {
// nature of error handling/swallowing/trapping/optional
// returning here TBD...
let newStart = index(startIndex, offsetBy: n)
defer { self = self[newStart..<endIndex] }
return self[startIndex..<newStart]
}
}
// soon...
extension String: Collection { }
Given this, here’s your example code written using it (compacted a little for brevity):
struct Product {
var id, group, name, description, currency: String
var inStock, ordered, price: Int
var priceFormatted: String {
let whole = (price/100)
let cents = price - (whole * 100)
return currency + " \(whole).\(cents)"
}
init(inputrecord: String) {
// note, no copying will occur here, as String is
// copy-on-write and there’s no writing happening
var record = inputrecord
id = record.dropPrefix(10)
group = record.dropPrefix(4)
name = record.dropPrefix(16)
description = record.dropPrefix(30)
inStock = Int(record.dropPrefix(10))!
ordered = Int(record.dropPrefix(10))!
price = Int(record.dropPrefix(10))!
currency = record.dropPrefix(1)
}
}
let record = "123A.534.CMCU3Arduino Due Arm 32-bit Micro controller. 000000034100000005680000002250$"
let product = Product(inputrecord: record)
print("=== Product data for the item with ID: \(product.id) ====")
print("group : \(product.group)")
print("name : \(product.name)")
print("description : \(product.description)")
print("items in stock : \(product.inStock)")
print("items ordered : \(product.ordered)")
print("price per item : \(product.priceFormatted)")
print("=========================================================“)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.