Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
I'm not a bad person. Why must the universe punish me so with Swift generics?
struct ProtoOrder<T> {
var quantity: T
init(_ quantity: T) { self.quantity = quantity }
}
protocol ItemProtocol {
associatedtype HowCounted: Numeric
typealias Order = ProtoOrder<HowCounted>
var order: Order { get set }
mutating func deliver() -> Bool
}
extension ItemProtocol {
mutating func deliver() -> Bool {
return Utilities.deliver(order)
}
}
struct Shovels: ItemProtocol {
typealias HowCounted = Int
var order: Order
}
struct Gravel: ItemProtocol {
typealias HowCounted = Double
var order: Order
}
enum Utilities {
static func deliver<T>(_ order: ProtoOrder<T>) -> Bool where T == Int {
return true
}
}
@dyegos

This comment has been minimized.

Copy link

@dyegos dyegos commented Mar 13, 2019

Can you try something like this?

struct ProtoOrder<T> {
    var quantity: T
    init(_ quantity: T) { self.quantity = quantity }
}

protocol ItemProtocol {
    associatedtype HowCounted: Numeric
    typealias Order = ProtoOrder<HowCounted>

    var order: Order { get set }

    mutating func deliver() -> Bool
}

extension ItemProtocol {
    mutating func deliver() -> Bool {
        return Utilities<Int>.deliver(order)
    }
}

struct Shovels: ItemProtocol {
    typealias HowCounted = Int
    var order: Order
}

struct Gravel: ItemProtocol {
    typealias HowCounted = Double
    var order: Order
}

enum Utilities<T> {
    static func deliver<T>(_ order: ProtoOrder<T>) -> Bool {
        return true
    }
}
@dyegos

This comment has been minimized.

Copy link

@dyegos dyegos commented Mar 13, 2019

Or this

struct ProtoOrder<T> {
    var quantity: T
    init(_ quantity: T) { self.quantity = quantity }
}

protocol ItemProtocol {
    associatedtype HowCounted: Numeric
    typealias Order = ProtoOrder<HowCounted>

    var order: Order { get set }

    mutating func deliver() -> Bool
}

extension ItemProtocol {
    mutating func deliver() -> Bool {
        return Utilities.deliver(order)
    }
}

struct Shovels: ItemProtocol {
    typealias HowCounted = Int
    var order: Order
}

struct Gravel: ItemProtocol {
    typealias HowCounted = Double
    var order: Order
}

enum Utilities {
    static func deliver<T: Numeric>(_ order: ProtoOrder<T>) -> Bool {
        return true
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment