使不兼容赋值的 Int 类型别名



我想制作一些不兼容赋值的整数类型,如下所示。

    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

有没有办法在 swift 中做到这一点(无需创建类/结构(?曾经能够在帕斯卡中做到这一点。

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

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
    }
}

最新更新