Swift中的"sign"函数

Mau*_*itz 13 swift

是否有一个函数在Swift中为正数返回+1,为负数返回-1?

我查看了一个巨大的文件,如果你右键单击 - >典型函数的定义,但如果它在那里,我不知道它的名字.

我这样做了:

(num < 0 ? -1 : 1)
Run Code Online (Sandbox Code Playgroud)

但我宁愿使用内置函数,如果有的话 - 至少是出于自我记录的原因.

dfr*_*fri 12

斯威夫特4

正如@Wil Shipley的Swift 4回答中已经指出的那样,协议中现在有一个sign属性FloatingPoint:

FloatingPointSign

浮点值的符号.

查点案例

  • case minus负值的符号.
  • case plus 正值的符号.

然而,在意见sign的源代码蓝图FloatingPoint包含了非常重要的信息在生成的文档不存在(没有?):

/// The sign of the floating-point value.
///
/// The `sign` property is `.minus` if the value's signbit is set, and
/// `.plus` otherwise. For example:
///
///     let x = -33.375
///     // x.sign == .minus
///
/// Do not use this property to check whether a floating point value is
/// negative. For a value `x`, the comparison `x.sign == .minus` is not
/// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if
/// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign`
/// could be either `.plus` or `.minus`.
Run Code Online (Sandbox Code Playgroud)

强调,"...... .minus如果设置了值的符号""不要使用此属性来检查浮点值是否为负值".

Summa summarum:使用协议的新sign属性FloatingPoint来实际检查值的signbit是否设置,但如果尝试使用此属性来判断数字是否为负数,请务必小心.

var f: Float = 0.0

if case .minus = (-f).sign { print("A. f is negative!") }

f = -Float.nan

if f < 0 { print("B. f is negative!") }
if case .minus = f.sign { print("C. f is negative!") }

// A. f is negative!
// C. f is negative!
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

Wrt内置函数,我认为最接近的是Foundation方法copysign(_: Double, _: Double) -> Double

let foo = -15.2
let sign = copysign(1.0, foo) // -1.0 (Double)
Run Code Online (Sandbox Code Playgroud)

当你没有在多种类型上操作时,自然需要一些类型转换Double.

但是,我认为没有理由不创建适合您需求的扩展,特别是对于这样一个简单的功能,sign因为它们不需要膨胀,例如

extension IntegerType {
    func sign() -> Int {
        return (self < 0 ? -1 : 1)
    }
    /* or, use signature: func sign() -> Self */
}

extension FloatingPointType {
    func sign() -> Int {
        return (self < Self(0) ? -1 : 1)
    }
}
Run Code Online (Sandbox Code Playgroud)

(这里1也屈服于0,如你问题中的例子).


(关于以下评论的编辑)

上面的替代解决方案是使用默认实现来定义您自己的协议sign(),以便符合此协议的所有类型都可以访问该sign()方法.

protocol Signable {
    init()
    func <(lhs:Self, rhs:Self) -> Bool
}

extension Signable {
    func sign() -> Int {
        return (self < Self() ? -1 : 1)
    }
}

/* extend signed integer types to Signable */
extension Int: Signable { }    // already have < and init() functions, OK
extension Int8 : Signable { }  // ...
extension Int16 : Signable { }
extension Int32 : Signable { }
extension Int64 : Signable { }

/* extend floating point types to Signable */
extension Double : Signable { }
extension Float : Signable { }
extension CGFloat : Signable { }

/* example usage */
let foo = -4.2
let bar = 42

foo.sign() // -1 (Int)
bar.sign() // 1  (Int)
Run Code Online (Sandbox Code Playgroud)


小智 8

如果您的值是整数,则可以使用signum()。

https://developer.apple.com/documentation/swift/int/2886673-signum

这是一个代码片段,可以清楚地说明这一点;

let negative: Int = -10
let zero: Int = 0
let positive: Int = 10

print(negative.signum()) // prints "-1"
print(zero.signum()) // prints "0"
print(positive.signum()) // prints "1"
Run Code Online (Sandbox Code Playgroud)


Wil*_*ley 7

在Swift-4花车中有一个新属性:

public var sign: FloatingPointSign { get }
Run Code Online (Sandbox Code Playgroud)

(但是这只会检查符号位,因此在某些情况下它会失败-0- 请参阅上面接受的答案.)


nea*_*ave 6

simd库有一个符号方法:

import simd

sign(-100.0) // returns -1
sign(100.0) // returns 1
sign(0.0) // returns 0
Run Code Online (Sandbox Code Playgroud)

simd如果你,你可以免费获得import SpriteKit.


Mas*_*sih 5

使用:

let result = signbit(number)
Run Code Online (Sandbox Code Playgroud)

这将为负数返回1,为正数返回0.

let number = -1.0
print("\(signbit(number))")

1

let number = 1.0
print("\(signbit(number))")

0
Run Code Online (Sandbox Code Playgroud)