为什么 Swift 编译器会抛出: "Could not find an overload for '<' that accepts the supplied arguments"



我在一些新的Swift代码中使用FCModel来持久化我的模型数据。在我的模式管理/迁移代码中,当我对Int执行逻辑比较时,我得到一个编译时错误。我不知道这里是否有语法或类型错误,或者我是否发现了编译器错误。

这是一个有效的逻辑操作吗?我有没有漏掉什么错误?

Error: AppDelegate.swift:53:30: Could not find an overload for '<' that accepts the supplied arguments
相关代码:

var schemaVersion: Int = (settings["schemaVersion"] as String).toInt()!
FCModel.openDatabaseAtPath(databasePath, withSchemaBuilder: { database, schemaVersion in
    database.crashOnErrors = true
    database.traceExecution = true
    database.beginTransaction()
// 'failedAt' closure removed for brevity
if schemaVersion < 1 { // ERROR HAPPENS HERE
    if !database.executeUpdate("SQL STATEMENT HERE", withArgumentsInArray: nil)
    { failedAt(1) }
    schemaVersion = 1
}

openDatabaseAtPath()定义为:

func openDatabaseAtPath(path: String!, withSchemaBuilder schemaBuilder: ((FMDatabase!, CMutablePointer<CInt>) -> Void)!)

更新# 2 在下面Sulthan的帮助下,我想我已经缩小了问题的范围,但我不知道为什么。我认为这可能是Swift的一个bug。

更新代码:

var schemaVersion: Int = 0
let database: FMDatabase = FMDatabase(path: databasePath)
FCModel.openDatabaseAtPath(databasePath, withSchemaBuilder: { (database, schemaVersion: CMutablePointer<CInt>) in
    var x:Int = Int(schemaVersion.withUnsafePointer( { (unsafeSchemaVersion: UnsafePointer<CInt>) -> CInt in
        return unsafeSchemaVersion.memory
    }))
    ...
})

当我在Xcode中调试和使用REPL时,一些有趣的事情发生了。当执行在withSchemaBuilder块时,database不是nil,并且匹配上面创建的对象。schemaVersion不是可识别的标识符:

error: use of unresolved identifier 'schemaVersion'
schemaVersion

:

$R0: FMDatabase! = {
  Some = {
    NSObject = {
      isa = FMDatabase
    }
    _db =
    _databasePath = @"/Users/brian/Library/Developer/CoreSimulator/Devices/25115FDE-0DA8-4F2B-B4E5-5A0600720772/data/Containers/Data/Application/579A64D7-6C6B-4690-B503-2CA5B4229D55/Documents/userData.sqlite"
    _logsErrors = YES
    _crashOnErrors = NO
    _traceExecution = NO
    _checkedOut = NO
    _shouldCacheStatements = NO
    _isExecutingStatement = NO
    _inTransaction = NO
    _maxBusyRetryTimeInterval = 2
    _startBusyRetryTime = 0
    _cachedStatements = nil
    _openResultSets = 0 objects
    _openFunctions = nil
    _dateFormat = nil
  }
}

任何想法吗?

声明

var schemaVersion: Int = (settings["schemaVersion"] as String).toInt()!

与你的错误没有任何关系,因为你在本地重新定义了schemaVersion:

... withSchemaBuilder: { database, schemaVersion in 

方法定义为

+ (void)openDatabaseAtPath:(NSString *)path
         withSchemaBuilder:(void (^)(FMDatabase *db, int *schemaVersion))schemaBuilder;

那么我假设block中schemaVersion的类型应该是CMutablePointer <CInt>

逻辑上,您不能直接将其与Int (1)进行比较。如果它真的是一个CMutablePointer<Int>,你应该使用这样的东西:

schemaVersion.withUnsafePointer { unsafeSchemaVersion in
    if unsafeSchemaVersion.memory < 1
    ...
    unsafeSchemaVersion.memory = 1
}

这相当于Obj-C中的以下内容:

 if (*schemaVersion < 1) {
     ...
     *schemaVersion = 1;
 }

如果你想引用你在闭包外定义的变量,你应该重命名它或者重命名闭包参数。

最新更新