简体   繁体   English

如何使用Swift将NSArray转换为[Int]

[英]How to convert NSArray to [Int] with Swift

My question is simple, 我的问题很简单,

let string = "1,2,3,4,5,6"

As I want to find the max value in the string, and I want to use the method in this way , so I need to do this: 因为我想在字符串中找到最大值,并且我想以这种方式使用方法,所以我需要这样做:

let array = string.componentsSeparatedByString(",") as [AnyObject]
let numArray = array as! [Int]
let maxNum = numArray.reduce(Int.min, combine: {max($0,$1)})  

But, there will be an error in " array as! [Int] " 但是,“ array as![Int] ”中会出现错误。

fatal error: array cannot be bridged from Objective-C

And if it's 如果是

let numArray = array as! [String]

It will be ok but we cannot use the reduce method. 可以,但是我们不能使用reduce方法。

So, how to convert the array with string to [Int]? 那么,如何将带有字符串的数组转换为[Int]?

you can map the array 你可以映射数组

let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map {$0.toInt()!}

You can use reduce and optionals, preventing usage of forced unwrapping, which can cause the app to crash if the string doesn't actually contain numbers. 您可以使用reduce和optionals,以防止使用强制展开,如果字符串实际上不包含数字,则可能导致应用程序崩溃。

Here's the code: 这是代码:

let array = string.componentsSeparatedByString(",")

let initial: Int? = .None
let max = array.reduce(initial) {
    let num = $1.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).toInt()

    return num > $0 ? num : $0
}

The first line splits the string into an array of strings - notice that there's no need of a cast, because the method already returns an array of strings. 第一行将字符串拆分为字符串数组-请注意,由于该方法已经返回字符串数组,因此无需强制转换。

The reduce method is used by passing an optional integer as initial value, set to .None (which is a synonym for nil ). 通过传递一个可选的整数作为初始值(设置为.None (这是nil的同义词))来使用reduce方法。

The closure passed to reduce converts the current value into an integer using toInt() , which returns an optional, to account for the string not convertible to a valid integer. 传递给reduce的闭包使用toInt()将当前值转换为整数,该整数返回一个可选值,以解决无法转换为有效整数的字符串的问题。

Next, the closure returns the converted number, if it's greater than the value calculated at the previous iteration (or than the initial value), otherwise it returns the value at the last iteration. 接下来,如果闭包大于上一次迭代计算的值(或大于初始值),则闭包将返回转换后的数字,否则它将返回上一次迭代的值。

Note that comparing integers and nil is perfectly legit: any integer value is always greater than nil (even a negative value). 请注意,比较整数和nil是完全合法的:任何整数值始终大于nil (甚至是负值)。

This method works with a "normal" list of numbers: 此方法适用于“普通”数字列表:

let string = "1, 2, 3, 4, 5, 6, 7" // The result is 7

but also with lists having numbers and non-numbers: 而且还包含具有数字和非数字的列表:

let string = "1, 2, three, 4, 5, 6, seven" // the result is 6

and with lists containing no numbers: 并包含不包含数字的列表:

let string = "one, two, three, three, four, five, six, seven" // the result is nil
let string = "1,2,3,4,5,6"

func toInt(str: String) -> Int {
    return str.toInt()!
}

let numArray = map(string.componentsSeparatedByString(",") as [String], toInt)

Then, numArray is [1, 2, 3, 4, 5, 6] . 然后, numArray[1, 2, 3, 4, 5, 6]

In Swift 2.0 , Swift 2.0中

let string = "1,2,3,4,5,6"
let numArray = string.componentsSeparatedByString(",").map{ Int($0)! }

In Swift 4.0: 在Swift 4.0中:

let string = "1,2,3,4,5,6"
let stringArray = string.split(separator: ",").map(String.init)
let intArray = stringArray.flatMap(Int.init)
intArray.max()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM