Decoding generics with phantom types - swift

I am trying to define a Currency type that would prevent numeric and alphabetic currency codes from getting mixed up:
public protocol ISO4217Type {}
public enum ISO4217Alpha: ISO4217Type {}
public enum ISO4217Num: ISO4217Type {}
public struct Currency<T: ISO4217Type> {
public let value: String
}
extension Currency where T == ISO4217Alpha {
public init?(value: String) {
let isLetter = CharacterSet.letters.contains
guard value.unicodeScalars.all(isLetter) else { return nil }
self.value = value
}
}
extension Currency where T == ISO4217Num {
public init?(value: String) {
let isDigit = CharacterSet.decimalDigits.contains
guard value.unicodeScalars.all(isDigit) else { return nil }
self.value = value
}
}
This works great. Now, is it possible to add a Codable conformance that would throw a decoding error when trying to decode a currency code with the wrong payload? (For example, decoding USD as a numeric currency code.)

The key revelation was that it’s possible to customize the behaviour using static functions on the phantom type:
public protocol ISO4217Type {
static func isValidCode(_ code: String) -> Bool
}
public enum ISO4217Alpha: ISO4217Type {
public static func isValidCode(_ code: String) -> Bool {
let isLetter = CharacterSet.letters.contains
return code.unicodeScalars.all(isLetter)
}
}
public enum ISO4217Num: ISO4217Type {
public static func isValidCode(_ code: String) -> Bool {
let isDigit = CharacterSet.decimalDigits.contains
return code.unicodeScalars.all(isDigit)
}
}
public struct Currency<T: ISO4217Type> {
public let value: String
private init(uncheckedValue value: String) {
self.value = value
}
public init?(value: String) {
guard T.isValidCode(value) else { return nil }
self.value = value
}
}
extension Currency: Codable {
public func encode(to encoder: Encoder) throws {
var c = encoder.singleValueContainer()
try c.encode(value)
}
public init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
let value = try c.decode(String.self)
guard T.isValidCode(value) else {
throw DecodingError.dataCorruptedError(in: c,
debugDescription: "Invalid \(type(of: T.self)) code")
}
self.init(uncheckedValue: value)
}
}

Related

How swift implement the default Decodable for struct?

struct Person: Decodable {
let firstName: String
}
var data = """
{"firstName": "Fai"}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let parsed = try decoder.decode(Person.self, from: data)
JSONDecoder will decode the data, which is comfirmed to Decodable protocol.
So I want to know how swift implement this. But I can not get any idea in the source code: https://github.com/apple/swift/blob/main/stdlib/public/core/Codable.swift
The Decodable protocol only need to implement an init(from decoder: Decoder) function.
If I am going to do it, I will make an extension for struct:
extension struct: Decodable {
init(from decoder: Decoder) {...}
}
But when I delete the Decodable on my example, the compiler give errors:
Instance method 'decode(_:from:)' requires that 'Person' conform to 'Decodable'
So this is not the swift way to implement this. How's swift way? And where's the source code?
You can see what the compiler writes for you using -print-ast:
echo 'struct Person: Decodable {
let firstName: String
}' | swiftc -print-ast -
This will output most of the auto-generated code (it should include all of the Codable conformances, but there are a few other kinds of auto-generated code that won't include their implementation):
internal struct Person : Decodable {
internal let firstName: String
private enum CodingKeys : CodingKey {
case firstName
#_implements(Equatable, ==(_:_:)) fileprivate static func __derived_enum_equals(_ a: Person.CodingKeys, _ b: Person.CodingKeys) -> Bool {
private var index_a: Int
switch a {
case .firstName:
index_a = 0
}
private var index_b: Int
switch b {
case .firstName:
index_b = 0
}
return index_a == index_b
}
fileprivate func hash(into hasher: inout Hasher) {
private var discriminator: Int
switch self {
case .firstName:
discriminator = 0
}
hasher.combine(discriminator)
}
private init?(stringValue: String) {
switch stringValue {
case "firstName":
self = Person.CodingKeys.firstName
default:
return nil
}
}
private init?(intValue: Int) {
return nil
}
fileprivate var hashValue: Int {
get {
return _hashValue(for: self)
}
}
fileprivate var intValue: Int? {
get {
return nil
}
}
fileprivate var stringValue: String {
get {
switch self {
case .firstName:
return "firstName"
}
}
}
}
internal init(firstName: String)
internal init(from decoder: Decoder) throws {
#_hasInitialValue private let container: KeyedDecodingContainer<Person.CodingKeys> = try decoder.container(keyedBy: Person.CodingKeys.self)
self.firstName = try container.decode(String.self, forKey: Person.CodingKeys.firstName)
}
}
For the full implementation details, see DerivedConformanceCodable.cpp. Probably of most interest to your question is deriveBodyDecodable_init.

Type 'Cache' does not conform to protocol 'Encodable'

I have been following the guide found here for Caching in Swift.
I am currently getting the error Type 'Cache' does not conform to protocol 'Encodable'
This makes no sense to me as I have followed the guide to the letter, I have found a couple of people using the same cache on GitHub and I believe my output matches theirs.
Why does 'Cache' not conform?
I have added the complete class as created in the tutorial below -
final class Cache<Key: Hashable, Value> {
private let wrapped = NSCache<WrappedKey, Entry>()
private let entryLifetime: TimeInterval
private let dateProvider: () -> Date
private let keyTracker = KeyTracker()
init(dateProvider: #escaping () -> Date = Date.init,entryLifetime: TimeInterval = 12 * 60 * 60, maximumEntryCount: Int = 50) {
self.dateProvider = dateProvider
self.entryLifetime = entryLifetime
wrapped.countLimit = maximumEntryCount
wrapped.delegate = keyTracker
}
func insert(_ value: Value, forKey key: Key) {
let date = dateProvider().addingTimeInterval(entryLifetime)
let entry = Entry(key: key, value: value, expirationDate: date)
let wrappedKey = WrappedKey(key: key)
wrapped.setObject(entry, forKey: wrappedKey)
keyTracker.keys.insert(key)
}
func value(forKey key: Key) -> Value? {
guard let entry = wrapped.object(forKey: WrappedKey(key: key)) else { return nil }
guard dateProvider() < entry.expirationDate else {
//Discard expired values
removeValue(forKey: key)
return nil
}
return entry.value
}
func removeValue(forKey key: Key) {
let key = WrappedKey(key: key)
wrapped.removeObject(forKey: key)
}
}
private extension Cache {
final class WrappedKey: NSObject {
let key: Key
init(key: Key) {
self.key = key
}
override var hash: Int { return key.hashValue }
override func isEqual(_ object: Any?) -> Bool {
guard let value = object as? WrappedKey else { return false }
return value.key == key
}
}
}
private extension Cache {
final class Entry {
let key: Key
let value: Value
let expirationDate: Date
init(key: Key, value: Value, expirationDate: Date) {
self.key = key
self.value = value
self.expirationDate = expirationDate
}
}
}
extension Cache {
subscript(key: Key) -> Value? {
get { return value(forKey: key) }
set {
guard let value = newValue else {
//If nil is assigned using subscript then remove any value for that key
removeValue(forKey: key)
return
}
insert(value, forKey: key)
}
}
}
private extension Cache {
final class KeyTracker: NSObject, NSCacheDelegate {
var keys = Set<Key>()
func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject object: Any) {
guard let entry = object as? Entry else { return }
keys.remove(entry.key)
}
}
}
extension Cache.Entry: Codable where Key: Codable, Value: Codable {}
private extension Cache {
func entry(forKey key: Key) -> Entry? {
guard let entry = wrapped.object(forKey: WrappedKey(key: key)) else { return nil }
guard dateProvider() < entry.expirationDate else {
removeValue(forKey: key)
return nil
}
return entry
}
func insert(_ entry: Entry) {
wrapped.setObject(entry, forKey: WrappedKey(key: entry.key))
keyTracker.keys.insert(entry.key)
}
}
extension Cache: Codable where Key: Codable, Value: Codable {
convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.singleValueContainer()
let entries = try container.decode([Entry].self)
entries.forEach(insert)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(keyTracker.keys.compactMap(entry))
}
}
extension Cache where Key: Codable, Value: Codable {
func saveToDisk(withName name: String, using fileManager: FileManager = .default) throws {
let folderURLs = fileManager.urls(
for: .cachesDirectory,
in: .userDomainMask
)
let fileURL = folderURLs[0].appendingPathComponent(name + ".cache")
let data = try JSONEncoder().encode(self)
try data.write(to: fileURL)
}
}

Unable to infer closure type in the current context in APIClient

I'm trying to migrate code from Swift 3.2 to Swift 4.2. When put in Xcode 10.1 I get this error.'Unable to infer closure type in the current context '. This is using YALAPIClient. Please help.
Unable to infer closure type in the current context
This I found on stack overflow. But I'm not using any try method here.Please help.
private func presentIndustrySearch() {
let dataProvider = RequestDataProvider { return IndustriesRequest() } /*error comes here*/
}
public class RequestDataProvider<Representation, Request>: DataProvider, NetworkClientInjectable
where
Request: SerializeableAPIRequest,
Request.Parser.Representation == [Representation]
{
public typealias Item = Representation
public typealias RequestConstructor = () -> Request
public private(set) var data = [Item]()
private let requestConstructor: RequestConstructor
public init(_ requestConstructor: #escaping RequestConstructor) {
self.requestConstructor = requestConstructor
}
public func loadData(before: () -> Void, after: #escaping (Error?) -> Void) {
let request: Request = self.requestConstructor()
before()
networkClient.execute(request: request, parser: request.parser, completion: { [weak self] task in
guard let `self` = self else { return }
if let data = task.value, data.count != 0 {
self.data.append(contentsOf: data)
after(nil)
} else if let error = task.error {
after(error as NSError)
} else {
let error = NSError.reachedEndOfPage()
after(error)
}
})
}
}
public protocol SerializeableAPIRequest: APIRequest {
associatedtype Parser: ResponseParser
var parser: Parser { get }
}
public struct IndustriesRequest: SerializeableAPIRequest, TokenizedAPIRequest, StubAPIRequest {
public private(set) var method = APIRequestMethod.get
public private(set) var path = "industries"
public private(set) var parser = KeyPathMappableArrayParser<[Industry]>(keyPath: "data")
public private(set) var parameters: [String: String]? = [:]
public private(set) var authenticationTokenRequired = true
public init(value: String = "") {
parameters!["term"] = value
}
}

swift - UserDefaults wrapper

I want to make userDefaults easier to use. I write this code.
But I don't want to create a allKeys enum(cases voipToken, userId, userName, displayName,...) as the key path for my property.
If I want add a var accessToken to struct LoginInfo, I must add a case accessToken to enum AllKeys. I use CoreStore.key(.accessToken) get a keyPath for CoreStore.LoginInfo.accessToken.
import Foundation
struct CoreStore {
// static let sharedInstance = CoreStore()
// private init(){}
private static let keyPrefix = "_shared_store_"
enum allKeys: String {
case accessToken
}
static func key(_ key: allKeys) -> String {
return keyPrefix + key.rawValue
}
struct LoginInfo: CoreStoreSettable,CoreStoreGettable { }
}
extension CoreStore.LoginInfo {
static var accessToken: String? {
set {
set(value: newValue, forKey: CoreStore.key(.accessToken))
}
get {
return getString(forKey: CoreStore.key(.accessToken))
}
}
// ...
}
protocol CoreStoreSettable {}
extension CoreStoreSettable {
static func set(value: String?, forKey key: String) {
UserDefaults.standard.set(value, forKey: key)
}
}
protocol CoreStoreGettable {}
extension CoreStoreGettable {
static func getString(forKey key: String) -> String? {
return UserDefaults.standard.string(forKey: key)
}
}
Questions:
Is there a way to remove "enum allKeys"?
Should I use sharedInstance? Why?
I tried :
static var accessToken: String? {
set {
let keyPath = \CoreStore.Loginfo.accessToken
let keyPathString = keyPath.string
set(value: newValue, forKey: keyPathString)
}
get {
return getString(forKey: CoreStore.key(.accessToken))
}
}
I get error "Type of expression is ambiguous without more context"

Can Swift enums be inferred and restricted generically?

I can't find the syntax, but I want to do something like this:
class MyClass {
let stringValue: String // filled in later
let integerValue: Int // filled in later
init(stringValue: String) {
self.stringValue = stringValue
self.integerValue = stringValue.hashValue
}
init(integerValue: Int) {
self.integerValue = integerValue
self.stringValue = String(integerValue)
}
}
extension MyClass {
// This is invalid syntax, but I think you can understand
// vvvvvvvvv I'm trying to give back an enum whose type is inferred
var enumValue<T: enum>: T? {
get {
// This is also invalid; I want to check the type of the enum's raw value
if T is String {
return T(rawValue: self.stringValue)
} else if T is Int {
return T(rawValue: self.integerValue)
} else {
return nil
}
}
}
}
The usage would be like:
enum MyEnum: String {
case foo
case bar
}
func baz(_ some: MyClass) {
if let myEnum: MyEnum = some.enumValue {
print(myEnum)
}
}
let some = MyClass(stringValue: "foo")
baz(some) // prints "foo"
Is this possible in Swift? That is, to have a generically-typed field or function whose type is constricted to enums and inferred based on usage, then use that to instantiate an enum value?
A possible solution would be a generic overloaded function:
extension MyClass {
func enumValue<T: RawRepresentable>() -> T? where T.RawValue == String {
return T(rawValue: stringValue)
}
func enumValue<T: RawRepresentable>() -> T? where T.RawValue == Int {
return T(rawValue: integerValue)
}
}
which is then called as
func baz(_ some: MyClass) {
if let myEnum: MyEnum = some.enumValue() {
print(myEnum)
}
}
Alternatively, pass the enum type as an argument:
extension MyClass {
func enumValue<T: RawRepresentable>(_ type: T.Type) -> T? where T.RawValue == String {
return T(rawValue: stringValue)
}
func enumValue<T: RawRepresentable>(_ type: T.Type) -> T? where T.RawValue == Int {
return T(rawValue: integerValue)
}
}
and call it like
func baz(_ some: MyClass) {
if let myEnum = some.enumValue(MyEnum.self) {
print(myEnum)
}
}