gpt4 book ai didi

swift - 在 Swift 中,如何创建 String 的后代?我在尝试这样做时收到错误 "Inheritance from non-protocol, non-class type ' String'"

转载 作者:行者123 更新时间:2023-11-28 10:36:03 28 4
gpt4 key购买 nike

我想让一个函数返回一个类型,我可以添加一个新函数,但仍然可以被普遍识别为 String(仍然有所有的 String方法,并且仍然可以被接收 String 的任何参数接收。

但是当我尝试从 String 派生一个类时,我得到了这个错误:

Inheritance from non-protocol, non-class type 'String'

当然,我可以改为使用扩展来扩展现有的 String 以添加该功能,但我觉得这会用不必要和不相关的功能污染 String一般用途。

例如,我要添加的功能可能是这样的:

class ImageUrl : String {

func getImage (callback: ((UIImage?)->Void)) { ... }

}

或者像这样:

class Base64 : String {

var image : UIImage { ... }
var data : Data { ... }
var string : String { ... }

}

如果我将这些函数扩展到主要的 String 类型,这会让人感到困惑。

我如何在 Swift 中执行此操作?或者有什么解决方法吗?谢谢。

最佳答案

在 Swift 中你不能继承 String,因为它是一个 struct。您只能使用您提到的 extension 添加功能,但这不会让您使用存储的属性(允许您在问题中写的计算属性)。

但是,更好的方法是使用组合:

class Base64 {

let str: String

required init(value: String) {
self.str = value
}
}

您可以在此处添加所需的功能。

关于swift - 在 Swift 中,如何创建 String 的后代?我在尝试这样做时收到错误 "Inheritance from non-protocol, non-class type ' String'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53610268/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com