swift - 重新包装泛型类

标签 swift

<分区>

这是我的代码:

import UIKit

class GenericClass<T: NSObject> {

    let generic: T
    let somethingElse: String

    init(generic: T, somethingElse: String) {
        self.generic = generic
        self.somethingElse = somethingElse
    }

    func wrap<P: NSObject>(with: P) -> GenericClass<P> {
        return GenericClass(generic: with, somethingElse: somethingElse)
    }
}

class Person {
    func transform() {
        let classA: GenericClass<UIViewController> = GenericClass(generic: UIViewController(nibName: nil, bundle: nil), somethingElse: "")
        let rewrapped: GenericClass<UIView> = classA.wrap(with: UIView())
    }
}

我得到这个编译器错误:

Generic parameter 'P' could not be inferred

编译器无法推断类型,但我不明白为什么在方法中有必要这样做。它应该只返回具有指定类型的 GenericClass。

我想用另一种类型替换 generic 并保持 somethingElse 完整。为什么它不适用于 wrap 方法?

最佳答案

wrap中指定泛型类型

func wrap<P: NSObject>(with: P) -> GenericClass<P> {
    return GenericClass<P>(generic: with, somethingElse: somethingElse)
}

关于swift - 重新包装泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985692/

相关文章:

ios - 通过 Switch 语句调用 API

swift - 当表格单元格出现时,UILabel 不调整大小

ios - 无法将数据从 ViewControllerClass 传递到 TableViewControllerClass

objective-c - 如果没有抽象类,为什么他们在文档中引用它们?

ios - 如何解决 NSScanner 上的 "Undefined symbols for architecture x86_64"问题? React-Native 中的 Swift pod

ios - 如何为 UISearchBar 抓取颜色?

c++ - 在 Swift 中定义显式泛型方法

swift - 在 didMove 中调用带参数的函数

ios - 点击手势出现问题

xcode - 在 Xcode 断点显示时间