2015-05-31 43 views
-3

我試圖做一個簡單的日期格式斯威夫特,但我發現了以下錯誤:不能援引「stringFromDate」錯誤迅速

"Cannot invoke 'stringFromDate' with an argument list of type '(NSDate?!)'" 

我的代碼如下:

override func tableView(tableView: UITableView, cellForRowAtIndexPath 

    indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", 

    forIndexPath: indexPath) as! UITableViewCell 

    // Configure the cell... 

    let dateFormatter = NSDateFormatter() 

    dateFormatter.dateFormat = ("dd-MMM-yyyy") 

    var myUsers: AnyObject = users[indexPath.row] 

    let strDate = dateFormatter.stringFromDate(myUsers.createdAt) 


    return cell 
} 

}

有誰知道爲什麼我不能做到這一點在斯威夫特?我以前使用過這種方法,它工作正常。我已經搜索了其他答案,但我還沒有找到任何合適的。

欣賞任何可用的幫助。非常感謝

+0

你不需要首先將myUsers轉換爲用戶對象嗎?現在它是'AnyObject' –

回答

0

檢查下面的代碼:

var dateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd" 
    let d = NSDate() 
    let s = dateFormatter.stringFromDate(d) 
    println(s) 
+0

你是對的,但這個OP不理解它。他/她只是複製和粘貼而不理解它。 –

-1

這是您的第一篇文章:

這行代碼是不成立的格式正確,因爲這就是所謂的從String轉換到Date

dateFormatter.dateFromString("dd-MMM-yyyy") 

所以,你必須先設置格式磕此,它只是一個小錯誤,並注意下一次:

dateFormatter.dateFormat = "yyyy-MM-dd" 

這是後您編輯後:

必須有一個明顯的錯誤在這裏:

var myUsers: AnyObject = users[indexPath.row] 

AnyObject沒有財產createdAt。這就是爲什麼你無法做到的。並確保users數組是'PFUser'的數組。否則,它仍然會有錯誤。

+0

如果OP更改了這段代碼,它仍然不起作用。 'stringFromDate「...」)'應該用於輸入需要轉換爲日期的字符串。 dateFormat(確實)用於設置格式,但你仍然需要使用'stringFromDate' – milo526

+0

我的理解是,'myUsers.createdAt'是'Date'的一個實例。首先,格式必須設置,我在這一點上是正確的。目的是從'Date'轉換爲'String'。那麼,爲什麼你需要'dateFromString'。我沒有看到從'String'轉換爲'Date'的目的。 @ milo526 –