我试图理解为什么我不能从我的字典类型的AnyObject中获取swift String。如果我执行println(fileCreationDate)它可以工作,但我需要一个实际的字符串来处理。因此,当我尝试将其转换为NSString时(因为它是一个不像String的结构,一个结构),它是零。 这就是我所拥有的:
if let atts = fileManager.attributesOfItemAtPath(fileLocation.path!, error:&err) as? Dictionary<String, AnyObject> {
println(atts)
if let fileCreationDate:AnyObject = atts["NSFileCreationDate"] {
println(fileCreationDate) //prints a date
var mystring:NSString! = fileCreationDate as? NSString
println(mystring) //prints nil
}
谢谢!
答案 0 :(得分:4)
你必须使用if和条件强制转换为NSDate将anyObject转换为NSDate,你可以根据需要设置日期格式。
if let atts = NSFileManager.defaultManager().attributesOfItemAtPath(myUrl.path!, error:nil) as? Dictionary<String, AnyObject> {
if let fileCreationDate = atts["NSFileCreationDate"] as? NSDate {
println(fileCreationDate)
let mystring = fileCreationDate.description
println(mystring)
}
}
extension String {
var fileExists: Bool {
return NSFileManager.defaultManager().fileExistsAtPath(self)
}
var fileAttributes: [String:AnyObject] {
return fileExists ? NSFileManager.defaultManager().attributesOfItemAtPath(self, error:nil) as Dictionary<String, AnyObject> : [:]
}
var fileCreationDate:NSDate {
return fileAttributes["NSFileCreationDate"] as NSDate
}
var fileGroupOwnerAccountName:String{
return fileAttributes["NSFileGroupOwnerAccountName"] as String
}
var fileType: String {
return fileAttributes["NSFileType"] as String
}
var fileHFSTypeCode: Int {
return fileAttributes["NSFileHFSTypeCode"] as Int
}
var fileExtendedAttributes:[String:AnyObject] {
return fileAttributes["NSFileExtendedAttributes"] as [String:AnyObject]
}
var fileSystemNumber: Int {
return fileAttributes["NSFileSystemNumber"] as Int
}
var fileOwnerAccountName: String {
return fileAttributes["NSFileOwnerAccountName"] as String
}
var fileReferenceCount: Int {
return fileAttributes["NSFileReferenceCount"] as Int
}
var fileModificationDate: NSDate {
return fileAttributes["NSFileModificationDate"] as NSDate
}
var fileExtensionHidden: Bool {
return fileAttributes["NSFileExtensionHidden"] as Bool
}
var fileSize: Int {
return fileAttributes["NSFileSize"] as Int
}
var fileGroupOwnerAccountID: Int {
return fileAttributes["NSFileGroupOwnerAccountID"] as Int
}
var fileOwnerAccountID: Int {
return fileAttributes["NSFileOwnerAccountID"] as Int
}
var filePosixPermissions: Int {
return fileAttributes["NSFilePosixPermissions"] as Int
}
var fileHFSCreatorCode: Int {
return fileAttributes["NSFileHFSCreatorCode"] as Int
}
var fileSystemFileNumber: Int {
return fileAttributes["NSFileSystemFileNumber"] as Int
}
}