【发布时间】:2016-01-27 10:26:17
【问题描述】:
将String 值转换为数组中的Int 值后,当我打印到日志时,我得到的只是:[0, 0, 0, 0],而输出应该是:["18:56:08", "18:56:28", "18:57:23", "18:58:01"]
(不带引号和: 冒号)。
我在将值添加到字符串数组之后直接转换字符串数组。我假设我没有在正确的时间转换值,或者我的方法放置错误,这就是我得到0 0 0 0 输出的原因。
这是我的 ViewController 代码:
class FeedTableViewController: UITableViewController {
var productName = [String]()
var productDescription = [String]()
var linksArray = [String]()
var timeCreatedString = [String]()
var minuteCreatedString = [String]()
var intArray = Array<Int>!()
override func viewDidLoad() {
super.viewDidLoad()
var query = PFQuery(className: "ProductInfo")
query.findObjectsInBackgroundWithBlock ({ (objects, error) -> Void in
if let objects = objects {
self.productName.removeAll(keepCapacity: true)
self.productDescription.removeAll(keepCapacity: true)
self.linksArray.removeAll(keepCapacity: true)
self.timeCreatedString.removeAll(keepCapacity: true)
for object in objects {
self.productName.append(object["pName"] as! String)
self.productDescription.append(object["pDescription"] as! String)
self.linksArray.append((object["pLink"] as? String)!)
// This is where I'm querying and converting the date:
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(createdAt as NSDate!)
var arrayOfCompontents = string.componentsSeparatedByString("/")
self.timeCreatedString.append("\(arrayOfCompontents[0]) \(arrayOfCompontents[1]) \(arrayOfCompontents[2])")
self.minuteCreatedString.append("\(arrayOfCompontents[3]):\(arrayOfCompontents[4]):\(arrayOfCompontents[5])")
self.intArray = self.minuteCreatedString.map { Int($0) ?? 0}
print("INT ARRAY \(self.intArray)")
print(self.minuteCreatedString.map { Int($0) ?? 0})
print(self.minuteCreatedString)
}
self.tableView.reloadData()
}
}
})
}
当我在 viewDidLoad 方法中的另一个 ViewController 中尝试此操作而没有发生解析/查询时,我得到了正确的输出:转换后的 Ints 数组。我假设存在 when 和 where 我将字符串转换为 Ints 的问题。
我应该以什么顺序/在哪里将字符串数组转换为整数数组?我应该从 Date 转换为 Int 吗?如果是这样,我该怎么做?我做错了什么吗?我很困惑....
非常感谢任何帮助!
【问题讨论】: