class Media {
var name :String = ""
init(name:String) {
self.name = name
}
}
class Song:Media {}
class Movie:Media{}
let s1 = Song(name :"Fireproof")
var m1 :Media = s1 //upcasting
//var s2 :Song = m1
var s2:Song = m1 as Song //down casting
// var x1 :Movie = m1 as Movie //
在
var m1: Media = s1
这行你可以设置m1
等于s1
因为m1
的类型是s1
的父类(super class)??在线
var s2: Song = m1 as Song
,据说是“向下转换”,是因为m1: Media
而你正在“转换” ” 它“作为”Song
类型以匹配相同类型的s2
? (如果这是真的,那么当s1
的类型与m1不同时,为什么我们之前设置了
??)m1
=s1
所有这些向上转换和向下转换的意义何在?我已经阅读了苹果文档并设法让自己更加困惑:'(
最佳答案
- On the line
var m1: Media = s1
you can setm1
equal tos1
becausem1
's type is the superclass ofs1
??
是的。 s1
是一首 Song
,这意味着根据定义它也是一个 Media
。因此,它可以分配给 Song
或 Media
类型的变量。
- On line
var s2: Song = m1 as Song
, it is supposedly "down casting", is that becausem1: Media
and you are "casting" it "as" aSong
type in order to match the same type ofs2
? (If this is true, then why did we setm1
=s1
earlier, whens1
had a different type thanm1
??)
在实际代码中没有理由先向上转型,然后立即向下转型。这只是向您展示您可以执行的操作的示例代码。
顺便说一句,简单的“as”语法是旧的 Swift - 你现在需要使用 as!
如果你确定它会在 100% 的时间内工作,或者 as?
如果你不确定。 (谷歌“swift optional casting”以获得更多信息。)普通的旧“as”现在只对编译器知道将始终有效的强制转换有效,比如从 String
到 NSString
.
- What's the point of all this up casting and down casting? I've read the apple documentation and managed to confuse myself even more :'(
这段代码中没有展示真正的意义。它通常用于与具有公共(public)基类的异构类型数组进行交互。例如,如果您有一组不同的 View ,您可能希望将它们放在一个数组中并对所有 View 执行一些操作:
class ViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
let button = UIButton()
let slider = UISlider()
let views = [label, button, slider] // views is a [UIView]
for view in views {
// view is known to be a UIView, even though it is also really a label, button, etc.
view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view)
}
}
}
如果您不确定是否需要了解这一点,暂时不要太担心。当您遇到这样一个问题,即您有一堆类型相似但又不完全相同的问题时,请回到这里。
关于swift - Swift 中的向上转换和向下转换混淆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32600522/