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

dav*_*n11 0 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
Run Code Online (Sandbox Code Playgroud)

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

Sul*_*han 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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望类型表现得像实整数一样,则可以使它们符合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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,您不必定义所有内容。一旦实现了遵守协议的基本方法,Swift协议扩展将为您定义很多。 (2认同)