Public Swift 中的扩展:浮动与 Float.type

Public Extensions in Swift : Float vs Float.type

我正在尝试为 Swift 中的浮点数构建一个扩展,returns 一个枚举(大小写为正数为正数,负数为负数)。我先建立了一个枚举。

public enum Sign 
{
    case Positive,Negative
}

现在,对于扩展,

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

我正在

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

对于行

 if self < Float(0)

但这不应该发生,考虑到 'self' 在 Float 的扩展中,应该保持浮动。

因为您正在使用 static:

public static func sign()-> Sign { ... }
此函数中的

self 指的是类型( Float 结构)而不是实例(浮点数)。删除 static 就可以了。

首先,您将它与 static 一起使用,正如@codedifferent 已经解释的那样,其次,如果已经有一个 属性 isMinus 那么为什么要使用您自己的逻辑?

简单地使用它来减少代码行数:

public extension Float  {
 public  func sign()-> Sign {
  return  self.isSignMinus ? Sign.Negative : Sign.Positive

 }
}