1 Reply
      Latest reply on Jan 1, 2016 7:11 PM by OOPer
      Albinus Level 1 Level 1 (0 points)

        Suppose I want a property to tell me whether an arbitrary number is an integer. If the number is a Double, I can just use this:


        extension Double {
          var isInteger: Bool {
          return Double(self) == Double(Int(self))


        Of course I can make the same extension for CGFloat, or just cast a CGFloat to a Double. That's easy enough, but I'm curious: Is there a way of defining a function that will work for both Double and CGFloat without a cast? I've been working my way through the Protocols chapter of The Swift Programming Language and I'm wondering if there's a way of doing it with a protocol.

        • Re: Property for Double and CGFloat
          OOPer Level 8 Level 8 (5,675 points)

          It's not easy under the current Swift type system.

          My best proposal is something like this:

          protocol IntegerCheckableFloatType: FloatLiteralConvertible, Equatable {
              func % (lhs: Self, rhs: Self) -> Self
              var isInteger: Bool {get}
          extension IntegerCheckableFloatType {
              var isInteger: Bool {
                  return self % 1.0 == 0.0 as Self
          extension Double: IntegerCheckableFloatType {}
          extension CGFloat: IntegerCheckableFloatType {}
          extension Float: IntegerCheckableFloatType {}
          (123.4).isInteger //->false
          (123.0).isInteger //->true