在Swift中将整数的字符串数组表示形式转换为整数数组 [英] Convert string array representation of integers into array of integers in Swift

查看:320
本文介绍了在Swift中将整数的字符串数组表示形式转换为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何转换:

let numbersStringArray = "[-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]"

成数组整数:

[-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]

我知道一种实现瘦快速的方法是这样的:

I know one way to implement thin swift is to do like this:

let formatter = NSNumberFormatter()
var numbers = numbersStringArray.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(",").map { formatter.numberFromString($0)?.integerValue
 }

但是我需要更短的编码解决方案。

But I need more shorter coded solution please.

推荐答案


我想简短些如果可能的话。类似于Array(numbersStringArray)

I would like something shorter if possible. Something like Array(numbersStringArray)

您可以通过简单地通过 Array创建便捷初始化程序来实现此目的扩展名。

You can do this by simply creating a convenience initialiser through an Array extension.

例如,通过JSON解码字符串,如 @Eric D 建议:

For example, decoding the string through JSON, as @Eric D suggests:

extension Array {

    init?(jsonString: String) {
        guard let array = (
            try? JSONSerialization.jsonObject(with: Data(jsonString.utf8))
            ) as? [Element] else { return nil }

        self.init(array)
    }
}

let numbersStringArray = "[-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]"

if let numberArray = [Int](jsonString: numbersStringArray) {
    print(numberArray) // prints: [-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]
}

这里我们返回一个可选数组,以反映类型可能不匹配的事实(有条件地向下转换为 [Element] 可能会失败),否则JSON反序列化可能会失败。

Here we're returning an optional array to reflect the fact that the types could mismatch (the conditional downcasting to [Element] could fail), or the JSON deserialisation could fail.

或以@vadian 建议:

protocol StringInitialisable {
    init?(string: String)
}

extension Int : StringInitialisable {
    init?(string: String) {
        self.init(string)
    }
}

extension Array where Element : StringInitialisable  {

    init(string: String) {
        self.init(
            string.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
                .components(separatedBy: ", ")
                .flatMap(Element.init)
        )
    }
}

let numbersStringArray = "[-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]"

let numberArray = [Int](string: numbersStringArray)
print(numberArray) // prints: [-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]

此处使用协议是为了明确指定可用于此初始化程序的类型,即可以初始化的类型用一个字符串。如果类型转换失败,此方法将不会返回可选参数,它只会从返回的数组中排除所有类型不匹配的内容。如果需要,您可以很容易地更改它以返回可选结果。

We're using a protocol here in order to explicitly specify the types that can be used for this initialiser – namely those that can be initialised with a string. This method won't return an optional if the type casting fails, it will simply exclude any type mismatches from the returned array. You could change it fairly easily to return an optional result if you want though.

您使用哪种方法完全取决于您-如果您的字符串始终为JSON格式,那么我建议您选择第一种方法以提高灵活性。

Which method you use is completely up to you – if your string is always in a JSON format, then I would recommend going with the first option for increased flexibility.

这篇关于在Swift中将整数的字符串数组表示形式转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆