Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

ios - How to get minimum & maximum value in a NSString/String array?

I'm getting data from a website in the form of NSString. The data may be just integers, sometimes integers with additional "a"/"b" representing additional information, or "#" meaning no data available. I've got the data into an array:

var labelMin = "-"
var labelMax = "-"

var arr = ["55a", "95a", "66", "25", "88b", "#"]

My question is:

How do I get the minimum & maximum value considering all objects in this array (e.g. also considering "95"in "95a", but no need to consider "#"), and print out subsequently on labelMin.text & labelMax.text?

[EDIT: The actual code will have 24 objects in the array, corresponding to data for every hour, which is continuously changing]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@user3815344's answer works, however you can simplify it by using minElement and maxElement to retrieve the minimum and maximum values. For example:

let arr = ["55a", "95a", "66", "25", "88b", "#"]
let numbers: [Int] = arr.reduce([]) {
    if let num = "".join($1.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)).toInt() {
        return $0 + [num]
    }

    return $0
}

minElement(numbers) // 25
maxElement(numbers) // 95

Updated for Swift 2: toInt has been replaced by a failable initialiser on Int that takes a String and minElement and maxElement have been replaced by protocol extensions:

let arr = ["55a", "95a", "66", "25", "88b", "#"]
let numbers: [Int] = arr.reduce([]) {
    if let num = Int("".join($1.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))) {
        return $0 + [num]
    }

    return $0
}

let min: Int? = numbers.minElement() // 25
let max: Int? = numbers.maxElement() // 95

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...