【发布时间】:2014-06-12 14:13:34
【问题描述】:
在 C / Objective-C 中,可以使用 MIN 和 MAX 宏找到两个数字之间的最小值和最大值。 Swift 不支持宏,而且在语言/基础库中似乎没有等价物。是否应该使用自定义解决方案,可能基于像这样的泛型one?
【问题讨论】:
在 C / Objective-C 中,可以使用 MIN 和 MAX 宏找到两个数字之间的最小值和最大值。 Swift 不支持宏,而且在语言/基础库中似乎没有等价物。是否应该使用自定义解决方案,可能基于像这样的泛型one?
【问题讨论】:
min 和 max 在 Swift 中定义:
func max<T : Comparable>(x: T, y: T, rest: T...) -> T
func min<T : Comparable>(x: T, y: T, rest: T...) -> T
并像这样使用:
let min = min(1, 2)
let max = max(1, 2)
在documented & undocumented built-in functions in Swift 上查看这篇精彩的文章。
【讨论】:
let a : Int = 5 并Command + 点击Int,你会看到很酷的东西!
a. 并滚动浏览 Xcode 完成的可能性......但“Command + Click”是票!
如前所述,Swift 提供了max 和min 函数。
一个示例(针对 Swift 2.x 更新)。
let numbers = [ 1, 42, 5, 21 ]
var maxNumber = Int()
for number in numbers {
maxNumber = max(maxNumber, number as Int)
}
print("the max number is \(maxNumber)") // will be 42
【讨论】:
对于 Swift 5,max(_:_:) 和 min(_:_:) 是 Global Numeric Functions 的一部分。 max(_:_:) 有以下声明:
func max<T>(_ x: T, _ y: T) -> T where T : Comparable
你可以像这样与Ints 一起使用它:
let maxInt = max(5, 12) // returns 12
另请注意,还有其他称为max(_:_:_:_:) 和min(_:_:_:_:) 的函数允许您比较更多参数。 max(_:_:_:_:) 有以下声明:
func max<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
你可以像这样与Floats 一起使用它:
let maxInt = max(12.0, 18.5, 21, 26, 32.9, 19.1) // returns 32.9
但是,使用 Swift,您不仅可以使用 max(_:_:) 及其带有数字的兄弟姐妹。实际上,这些函数是通用的,可以接受任何符合Comparable 协议的参数类型,可以是String、Character 或您自定义的class 或struct 之一。
因此,以下 Playground 示例代码可以完美运行:
class Route: Comparable, CustomStringConvertible {
let distance: Int
var description: String {
return "Route with distance: \(distance)"
}
init(distance: Int) {
self.distance = distance
}
static func ==(lhs: Route, rhs: Route) -> Bool {
return lhs.distance == rhs.distance
}
static func <(lhs: Route, rhs: Route) -> Bool {
return lhs.distance < rhs.distance
}
}
let route1 = Route(distance: 4)
let route2 = Route(distance: 8)
let maxRoute = max(route1, route2)
print(maxRoute) // prints "Route with distance: 8"
此外,如果您想获取 Array、Set、Dictionary 或任何其他 Comparable 元素序列中的元素的最小/最大元素,您可以使用 @987654326 @ 或 min() 方法(有关详细信息,请参阅 this Stack Overflow answer)。
【讨论】:
SWIFT 4 语法有点变化:
public func max<T>(_ x: T, _ y: T) -> T where T : Comparable
public func min<T>(_ x: T, _ y: T) -> T where T : Comparable
和
public func max<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
public func min<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
所以当你使用它时,你应该像下面这个例子那样写:
let min = 0
let max = 100
let value = -1000
let currentValue = Swift.min(Swift.max(min, value), max)
所以你得到从 0 到 100 的值,不管它是低于 0 还是高于 100。
【讨论】:
Ints,max() 也不存在,然后将其更改为 Swift。麦克斯和突然耶,事情变得更好了。感谢 wm.p1us!
试试这个:
let numbers = [2, 3, 10, 9, 14, 6]
let min = numbers.min()
let max = numbers.max()
print("Max = \(max) Min = \(min)")
【讨论】: