gpt4 book ai didi

swift - 是否可以将类的实例转换为子类的实例?

转载 作者:行者123 更新时间:2023-11-28 08:28:51 25 4
gpt4 key购买 nike

我最近遇到一个案例,将类的实例转换为子类非常方便,而实例已经在父类中创建。但我从未见过这样的事情。那么有没有办法做这样的事情:

class Foo {
var name: String
}

class Bar: Foo {
var friendName: String
}

let foo = Foo(name: "Alice")
foo.toBar(friendName: "Bob")
// foo now of type Bar, as if I'd done
// foo = Bar(name: "Alice", friendName: "Bob")

如果那不可能,从设计的角度来看是否有某些原因是不可能的?

===edit=== 有意义的用例描述

假设有两个 View 表示对应于一本书的同一数据库记录的内容,一个是该书的预览,另一个是更复杂的 View 。模型可以是:

protocol BookMetaDelegate {
func onReadStatusUpdate()
}

/// describe a book
class BookMeta {
var delegate: BookMetaDelegate?
private var _hasBeenRead: Bool
var hasBeenRead: Bool {
get {
return _hasBeenRead
}
set {
guard newValue != _hasBeenRead else { return }
_hasBeenRead = newValue
delegate?.onReadStatusUpdate()
}
}
var title: String
}

/// contains all the content of a book
class Book: BookMeta {
var content: BookContent
var lastPageRead: Int

/// some logic that only makes sense in a Book instance
func getLastPageRead() {
return content.getPage(lastPageRead)
}
}

View 可能看起来像:

class BookPreview: UIView, BookMetaDelegate {
var book: BookMeta
init(book: BookMeta) {
book.delegate = self
}
func onReadStatusUpdate() {
print("read status has changed! UI should update")
}
}

class BookView: UIView {
var book: Book
init(book: Book) {
book.hasBeenRead = true
}
}

然后事情可能会发生这样的

fetch(bookMetaWithId: 123).then { bookMeta in // bookMeta is of type BookMeta
let preview = BookPreview(book: bookMeta)
...

fetch(contentOf: bookMeta).then { content, lastPageRead in
bookMeta.asBook(content: content, lastPageRead: lastPageRead)
let bookView = BookView(book: bookMeta) // doing so will change the hasBeenRead flag and message the instance's delegate, ie the preview
...
}
}

最佳答案

仔细想想,听起来如果这样的事情是可能的,它会破坏像这样的东西:

class Foo {
var name: String
}

class Bar: Foo {
var friendName: String
}

class Bla: Foo {
var surname: String
}

func something(foo: Foo) {
foo.toBla(surname: "Will")
}

let bar = Bar(name: "Alice", friendName: "Bob")
something(foo: bar) // what does that do ??? is bar a Bla now ?

所以这就是使这种转换成为不可能的一个很好的理由。

关于swift - 是否可以将类的实例转换为子类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312946/

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