使与分配不兼容的Int类型别名

时间:2019-04-18 13:21:35

标签: swift

我想使一些与分配不兼容的Integer类型,如下所示。

    typealias Fatty = Int
    typealias Skinny = Int

    var a : Fatty = 6
    var b: Skinny = 4

    a = b // This should throw a compile time error saying the types are incompatible

    a = Fatty(b) // this should work

有什么办法可以迅速地做到这一点(无需创建类/结构)?过去能够以Pascal做到这一点。

1 个答案:

答案 0 :(得分:5)

是的,您可以定义自己的整数类型,但这并不容易:

public struct Fatty: ExpressibleByIntegerLiteral, Hashable {
    public typealias IntegerLiteralType = Int
    let value: Int

    public init(_ value: Int) {
        self.value = value
    }

    public init(_ skinny: Skinny) {
        self.value = skinny.value
    }

    public init(integerLiteral value: Int) {
        self.value = value
    }
}

public struct Skinny: ExpressibleByIntegerLiteral, Hashable {
    public typealias IntegerLiteralType = Int
    let value: Int

    public init(_ value: Int) {
        self.value = value
    }

    public init(_ fatty: Fatty) {
        self.value = fatty.value
    }

    public init(integerLiteral value: Int) {
        self.value = value
    }
}

如果您希望类型表现得像实整数一样,则可以使它们符合BinaryInteger(或其他整数协议)。

可以使用某种协议进行概括:

public protocol CustomInt: ExpressibleByIntegerLiteral, Hashable, Comparable {
    associatedtype ValueType = _ExpressibleByBuiltinIntegerLiteral
    var value: ValueType { get set }

    init(value: ValueType)
}

extension CustomInt {
    public init(integerLiteral value: ValueType) {
        self.init(value: value)
    }

    public init<T: CustomInt>(_ customInt: T) where Self.ValueType == T.ValueType {
        self.init(value: customInt.value)
    }
}

extension CustomInt where ValueType: Comparable {
   public static func < (lhs: Self, rhs: Self) -> Bool {
      return lhs.value < rhs.value
   }
}

public struct Fatty: CustomInt {
    public var value: Int

    public init(value: Int) {
        self.value = value
    }
}

public struct Skinny: CustomInt {
    public var value: Int

    public init(value: Int) {
        self.value = value
    }
}
相关问题