結論
これで良さそう。
let path = "..."
if let attr: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil) {
println(attr.fileModificationDate())
println(attr.fileSize())
}
事の経緯
関数の定義を見ると
func attributesOfItemAtPath(path: String, error: NSErrorPointer) -> [NSObject : AnyObject]?
というように、戻り値の型が[NSObject: AnyObject]?
になっているのですが、この辞書型から更新日付などを"お手軽に"取り出す方法が当初解りませんでした。
Objective-Cでは、NSDirectory
型で結果が得られ、カテゴリで各情報が取り出しやすいようになっていましたが、
- (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
@interface NSDictionary (NSFileAttributes)
- (unsigned long long)fileSize;
- (NSDate *)fileModificationDate;
- (NSString *)fileType;
- (NSUInteger)filePosixPermissions;
- (NSString *)fileOwnerAccountName;
- (NSString *)fileGroupOwnerAccountName;
- (NSInteger)fileSystemNumber;
- (NSUInteger)fileSystemFileNumber;
- (BOOL)fileExtensionHidden;
- (OSType)fileHFSCreatorCode;
- (OSType)fileHFSTypeCode;
- (BOOL)fileIsImmutable;
- (BOOL)fileIsAppendOnly;
- (NSDate *)fileCreationDate;
- (NSNumber *)fileOwnerAccountID;
- (NSNumber *)fileGroupOwnerAccountID;
@end
Swiftだとどうなるんだろう?と思い、調べていくうちにそれらしい補助関数を発見。
extension NSDictionary {
func fileSize() -> UInt64
func fileModificationDate() -> NSDate?
func fileType() -> String?
func filePosixPermissions() -> Int
func fileOwnerAccountName() -> String?
func fileGroupOwnerAccountName() -> String?
func fileSystemNumber() -> Int
func fileSystemFileNumber() -> Int
func fileExtensionHidden() -> Bool
func fileHFSCreatorCode() -> OSType
func fileHFSTypeCode() -> OSType
func fileIsImmutable() -> Bool
func fileIsAppendOnly() -> Bool
func fileCreationDate() -> NSDate?
func fileOwnerAccountID() -> NSNumber?
func fileGroupOwnerAccountID() -> NSNumber?
}
[NSObject: AnyObject]?
型からNSDictionary
型に変換すれば行けそう!ってな所まで来ましたが、どうやって変換すればいいのか判らず...
どうやら、普通にas
や型指定だけで[NSObject: AnyObject]
型からNSDictionary
型へは変換(ブリッジ)できるもよう。
この辺は公式ドキュメントにも載っていました(Dictionaries項目参照)。
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html
試したソースも載せておきます。
import UIKit
let dic: [NSObject: AnyObject] = ["aaa": "bbb"]
let test1 = dic as NSDictionary // OK
let test2: NSDictionary = dic // OK
ということで、if let
でアンラップしつつNSDictionary
型にするという冒頭のコードになりました。