简体   繁体   English

从字符串数组中删除字符和元素Swift

[英]Remove characters and elements from Array of Strings Swift

I have an array of strings that have been converted from a date into a String from Parse like this: 我有一个字符串数组,这些字符串已从日期转换为Parse的字符串,如下所示:

var createdAt = object.createdAt
            if createdAt != nil {

            let date = NSDate()
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat =  "MM/dd/YYY/HH/mm/ss"
            let string = dateFormatter.stringFromDate(date)
            let arrayOfCompontents = string.componentsSeparatedByString("/")

            let dateTimeString = dateFormatter.stringFromDate(createdAt as! NSDate!)

                self.timeCreatedString.append("\(arrayOfCompontents[0...2])")

I'm appending to an Array called timeCreatedString . 我要追加到名为timeCreatedString的数组。

When I print to the logs the output is: ["[\\"10\\", \\"26\\", \\"2015\\"]"] 当我打印到日志时,输出为: ["[\\"10\\", \\"26\\", \\"2015\\"]"]

And when I put it on a UILabel I get this: ["10", "26", "2015"] 当我将其放在UILabel上时,得到的是: ["10", "26", "2015"]

Is there a simple way to remove the brackets, quotes and commas from a swift array and replace it with something else (or nothing)? 有没有一种简单的方法可以从快速数组中删除括号,引号和逗号,并用其他东西(或什么都不替换)替换它?

When you are using 使用时

self.timeCreatedString.append("\(arrayOfCompontents[0...2])")

it actually creates a new array with given range, then gets its "description" and adds that description to the array, you want to append actual items and not the description, the one way to do it is 它实际上创建了一个具有给定范围的新数组,然后获取其“描述”并将该描述添加到该数组中,您想添加实际项而不是描述,一种方法是

self.timeCreatedString += arrayOfCompontents[0...2]

or 要么

self.timeCreatedString.appendContentsOf(arrayOfCompontents[0...2])

if you want whole date string to be appended at once, then use 如果您希望一次附加整个日期字符串,请使用

self.timeCreatedString.append("\(arrayOfCompontents[0]) \(arrayOfCompontents[1]) \(arrayOfCompontents[2])")

You could create an extension which shows a string of all the array elements: 您可以创建一个扩展,以显示所有数组元素的字符串:

extension CollectionType where Generator.Element == String {
    var prettyPrinted: String {
        return self.joinWithSeparator(" ")
    }
}

Example usage: 用法示例:

let arr = ["10", "26", "2015"]

let pretty = arr.prettyPrinted

print(pretty)  // "10 26 2015"

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

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