Skip to content

Instantly share code, notes, and snippets.

@alexj70
Last active April 27, 2017 21:22
Show Gist options
  • Save alexj70/ed181093202a994ccabb77b275de4f55 to your computer and use it in GitHub Desktop.
Save alexj70/ed181093202a994ccabb77b275de4f55 to your computer and use it in GitHub Desktop.
Resource

Resource

import Foundation
struct Resource {
    enum HTML: String, ResourceConvertible, Iteratable {
        case rightOfWithdrawal = "RightOfWithdrawal"
        case privatePolicy = "PrivatePolicy"
        case termsAndConditions = "TermsAndConditions"
    }
}

protocol ResourceConvertible {}

extension ResourceConvertible where Self: RawRepresentable, Self.RawValue == String {
    var url: URL {
        return Bundle.main.url(for: self)
    }
}

extension Bundle {
    func url<T: ResourceConvertible>(for resource: T) -> URL where T: RawRepresentable, T.RawValue == String {
        let ext = String(describing: T.self).lowercased()
        guard let url = self.url(forResource: resource.rawValue, withExtension: ext) else {
            fatalError("Could not find resource \(resource.rawValue).\(ext)")
        }
        return url
    }
}

Enum iteration

Using

let html1 = Resource.HTML.privatePolicy.url
let html2 = Bundle.main.url(for: Resource.HTML.privatePolicy)

Unit testing

import XCTest
@testable import LIQR
class ResourcesTests: XCTestCase {
    func test_HTMLResources() {
        checkResources(Resource.HTML.self)
    }
    
    func checkResources<T: RawRepresentable>(_: T.Type) where T: Iteratable, T: ResourceConvertible, T: Hashable, T.RawValue == String {
        for resource in T.hashValues() {
            XCTAssertNotNil(resource.url, "\(resource.rawValue)")
            XCTAssertNotNil(Bundle.main.url(for: resource), "\(resource.rawValue)")
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment