【问题标题】:Error with Swift 2: Cannot assign a value of type '[NSURL]' to a value of type '[NSURL]'Swift 2 出错:无法将“[NSURL]”类型的值分配给“[NSURL]”类型的值
【发布时间】:2015-07-16 16:40:55
【问题描述】:

我有一个名为 downloadedPhotoURLs 的变量,其类型为 [NSURL]?

我正在尝试分配返回类型 [NSURL](非可选)的函数的结果。

我在赋值时解开变量downloadedPhotoURLs!

我得到错误:

无法将“[NSURL]”类型的值分配给“[NSURL]”类型的值

我不知道如何解决这个问题。

我正在使用 Xcode 7 测试版(只是因为我必须能够在设备上运行它,但我有免费帐户)

do {
    downloadedPhotoURLs! = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: nil, options: nil)
    collectionView!.reloadData()
} catch _ {
    downloadedPhotoURLs = nil
}

【问题讨论】:

  • 去掉!。只需分配dowloadedPhotoURLs = try ...
  • 不仅如此,options: nil 也不起作用。有swift2 标签,所以有OptionSetType...

标签: swift swift2


【解决方案1】:

有两个问题...

强制解包downloadedPhotoURLs!

您不能以这种方式分配。如果变量类型是可选的,你以一种常见的方式分配给它,比如如果它不是可选的,...

downloadedPhotoURLs = ...

当您确实想要读取/访问值时使用展开 (!, ...)。不是当您确实想分配新值时。你做对了就行了:

downloadedPhotoURLS = nil

Swift 2.0 中的 OptionSetType

您不能在 options: 参数中传递 nil。这个方法的签名是:

func contentsOfDirectoryAtURL(url: NSURL,
  includingPropertiesForKeys keys: [String]?,
  options mask: NSDirectoryEnumerationOptions) throws -> [NSURL]

NSDirectoryEnumerationOptions 是:

struct NSDirectoryEnumerationOptions : OptionSetType {
    init(rawValue: UInt)

    static var SkipsSubdirectoryDescendants: NSDirectoryEnumerationOptions { get }    
    static var SkipsPackageDescendants: NSDirectoryEnumerationOptions { get }   
    static var SkipsHiddenFiles: NSDirectoryEnumerationOptions { get }
}

所以它应该是这样的:

downloadedPhotoURLs = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(string: "")!,
  includingPropertiesForKeys: nil,
  options:NSDirectoryEnumerationOptions(rawValue: 0))

关于OptionSetType 的更多信息(随 Swift 2.0 引入)。

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多