假设我有一个包含Usr
对象的数组。而Usr
对象具有属性age
。除了逐个读取Usr
对象并逐个比较age
值之外,是否有任何捷径可以这样做?谢谢。
struct User {
var age: Int
}
let users = [ User(age: 10), User(age: 20), User(age: 30)]
let oldestUser = users.max { $0.age < $1.age }
oldestUser?.age // 30
users.map
,而不是users.max
。 - toing_toingmap
方法单独返回一个数组,其中包含对每个元素应用给定转换后的结果。 max(by:)
方法根据给定谓词在序列中查找最大的元素。 - Hamishclass Usr {
var age: Int
init(_ age: Int) {
self.age = age
}
}
let users = [Usr(1), Usr(8), Usr(5)]
let maxAge = maxElement(users.map{$0.age}) // 8
arrayOfInts.max()
而在Swift 2中是arrayOfInts.maxElement()
。 max()
对于2个或更多值是可变参数的。 - KirsteinsSwift 3:
let users = [Usr(15), Usr(25), Usr(20)]
let max = users.map { $0.age }.max()
// 最大值 = 25
使用 max(by:) 函数
class Usr {
var age: Int
init(_ age: Int) {
self.age = age
}
}
let users = [Usr(3), Usr(8), Usr(6)]
if let userWithMaxAge : Usr = users.max(by: {$0.age < $1.age}){
print(userWithMaxAge.age)
}
它将打印8
其他方法:
class Usr {
var age: Int
init(_ age: Int) {
self.age = age
}
}
let users = [Usr(1), Usr(8), Usr(5)]
let largestAge = users.map{ $0.age }.reduce(0) { $0 > $1 ? $0 : $1 } // 8
之前的答案有点混乱,不能准确地描述出我将采用的方法。所以,根据您的需求,有两种不同的方法。
如果这是您的模型:
struct Purchase {
let id: String
let amount: Double
}
以下是您的对象:
let iPhonePurchase = Purchase(id: "iPhone", amount: 999.00)
let iPadPurchase = Purchase(id: "iPad", amount: 1299.00)
let purchases = [iPhonePurchase, iPadPurchase]
let highestPurchase = purchases.max { $0.amount < $1.amount }
这将返回对象。
另一方面,如果您不想获取整个对象,只需获取最高金额值:
let highestPurchase = purchases.map { $0.amount }.max()
在这里,您将获得最高价值为1299.00
。
let users = [Usr(1), Usr(8), Usr(5)]
let maxAge = users.map { $0.age }.max()
print(maxAge ?? "No users") // Optional(8)
let array1 = [75,37,45,80,75,24,65,97,60,83]
var smallvalue = 0
for countindex in 0..<array1.count {
let index1 = array1[countindex]
if countindex == 0 {
let index2 = array1[countindex + 1]
if index1 < index2 {
smallvalue = index1
} else {
smallvalue = index2
}
} else {
if smallvalue > index1 {
smallvalue = index1
}
}
}
print(smallvalue) //print 24
var studentsAndScores = ["Amy": Int(readLine()!)!, "James": Int(readLine()!)!, "Helen": Int(readLine()!)!]
func highestScore(scores: [String: Int]) {
let a = studentsAndScores["Amy"]!
let b = studentsAndScores["James"]!
let c = studentsAndScores["Helen"]!
var temp = 0
if a > temp {
temp = a
}
if b > temp {
temp = b
}
if c > temp {
temp = c
}
print(temp)
}
highestScore(scores: studentsAndScores)
[yourArray valueForKeyPath:@"@max.age"];
详情请见:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html。 - Larme