如何修复 'Int' 无法转换为 'Class'

How to fix 'Int' is not convertible to 'Class'

我是 Swift 的新手,我正在从 Java 迁移我的应用程序。在我的 Swift 项目中,我有一本 Book class,其函数名为 toBook:

class Book {
    func toBook(_ resource: Int) -> Int {
        return (resource & 0xFF0000) >> 16
    }
}

当我尝试在另一个 class 中调用 toBook 函数时,出现错误:Int is not convertible to Book

class Version {
    func reference(resource: Int) -> String {
        var bookId = Book.toBook(resource) //error:'Int' is not convertible to 'Book'
        return reference(bookId);
    }
}

我该如何解决这个错误?谢谢。

有多种方法可以实现您的目标。最简单的方法是在 func reference 方法中初始化 Book class:

class Version {
    func reference(resource: Int) -> String {
        let bookId = Book().toBook(resource) // notice the `()` after Book
        return reference(bookId);
    }

    // or even more simplified
    func reference(resource: Int) -> String {
        reference(Book().toBook(resource)) // compatible with Swift 5+
    }
}

正如 Leo Tabus 所建议的那样,将 toBook 方法更改为静态 on 也是有效的,因此您不需要首先初始化 book 对象。但是我会建议将书 class 更改为枚举(但仅当您完全使用静态方法或属性时,我的意思是绝对):

enum Book {
    static func toBook(_ resource: Int) -> Int {
        return (resource & 0xFF0000) >> 16
    }
}

有点远,但就我而言,干净的代码明智,我建议使用 class 方法并在 Book 上进行扩展,因为您正在尝试在那里映射值可能不是真正的 Book 实现的一部分:

class Book {
    // properties and methods and whatnot you need for this class
}

extension Book {
    func toBook(_ resource: Int) -> Int {
        return (resource & 0xFF0000) >> 16
    }
}

记得先初始化book对象。但这还是或多或少的味道。