Search code examples
swiftswift2swift-extensions

Public Extensions in Swift : Float vs Float.type


I'm trying to build an extension for floats in Swift that returns an enum (case .Positive for positive, .Negative for negative). I built an enum first.

public enum Sign 
{
    case Positive,Negative
}

Now, for the extension,

public extension Float
{
    public static func sign()-> Sign
    {
        if self < Float(0)
        {
            return Sign.Negative
        }
        else
        {
            return Sign.Positive
        }
    }
}

I'm getting

Cannot convert value of type 'Float.Type' to expected argument type

For the line

 if self < Float(0)

But that shouldn't be happening, considering that 'self' inside an extension for Float, should remain a float.


Solution

  • Because you are using static:

    public static func sign()-> Sign { ... }
    

    self in this function refers to the type (the Float struct) rather than the instance (a floating point number). Remove the static and you'll be fine.