【问题标题】:Swift2 - initializer for conditional binding must have Optional type, not 'String'Swift2 - 条件绑定的初始化程序必须具有可选类型,而不是“字符串”
【发布时间】:2016-01-29 04:49:34
【问题描述】:

我收到此错误。我找到了类似的代码。我尝试修复但无法修复。这是我的代码

    let path = docDir.stringByAppendingPathComponent(dbName)
    let fm = NSFileManager.defaultManager()
    if !(fm.fileExistsAtPath(path)) {


if let from = (NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(dbName)

{
             var error:NSError?
             do {
                try fm.copyItemAtPath(from, toPath: path)
            } catch let error1 as NSError {
                error = error1
                print("SQLiteDB - failed to copy writable version of DB!")
                print("Error - \(error!.localizedDescription)")
                return 
            }
        }
    }

错误在线

if let from = (NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(dbName)

报告错误:

条件绑定的初始化器必须是 Optional 类型,而不是 'String'

请有人帮助我。非常感谢

【问题讨论】:

    标签: swift2


    【解决方案1】:

    这是因为stringByAppendingPathComponent 只返回一个String,而不是可选字符串String?。所以你不能在if let 中解开这个String,只使用let

    func stringByAppendingPathComponent(_ str: String) -> String
    

    let from = (NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(dbName)
    
    var error:NSError?
        do {
            ...
    

    【讨论】:

      【解决方案2】:

      如下使用。

      let from:NSString = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent(dbPath)
              do {
                  try fileManager.copyItemAtPath(from as String, toPath: toPath as String)
      
              } catch let error1 as NSError {
                  error = error1
              }
      

      【讨论】:

        【解决方案3】:

        请指定变量类型

         if let imageURL:String = array[indexPath.row].absoluteString {
            //Do something
            }
        

        【讨论】:

        • 最好是评论吗?
        猜你喜欢
        • 2018-11-06
        • 2015-12-22
        • 1970-01-01
        • 2018-12-20
        • 2019-03-11
        • 2017-01-22
        • 2018-03-25
        • 2016-01-08
        • 2017-04-08
        相关资源
        最近更新 更多