swift - Swift 中的向上转换和向下转换混淆?

标签 swift casting type-conversion downcast upcasting

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 //
  1. var m1: Media = s1 这行你可以设置 m1 等于 s1 因为 m1的类型是s1的父类(super class)??

  2. 在线 var s2: Song = m1 as Song ,据说是“向下转换”,是因为 m1: Media 而你正在“转换” ” 它“作为”Song 类型以匹配相同类型的 s2? (如果这是真的,那么当 s1 的类型与 m1m1 = s1??)

  3. 所有这些向上转换和向下转换的意义何在?我已经阅读了苹果文档并设法让自己更加困惑:'(

最佳答案

  1. On the line var m1: Media = s1 you can set m1 equal to s1 because m1's type is the superclass of s1??

是的。 s1 是一首 Song,这意味着根据定义它也是一个 Media。因此,它可以分配给 SongMedia 类型的变量。

  1. On line var s2: Song = m1 as Song , it is supposedly "down casting", is that because m1: Media and you are "casting" it "as" a Song type in order to match the same type of s2? (If this is true, then why did we set m1 = s1 earlier, when s1 had a different type than m1??)

在实际代码中没有理由先向上转型,然后立即向下转型。这只是向您展示您可以执行的操作的示例代码。

顺便说一句,简单的“as”语法是旧的 Swift - 你现在需要使用 as! 如果你确定它会在 100% 的时间内工作,或者 as? 如果你不确定。 (谷歌“swift optional casting”以获得更多信息。)普通的旧“as”现在只对编译器知道将始终有效的强制转换有效,比如从 StringNSString.

  1. 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/

相关文章:

ios - 如何在 swift 中访问嵌套 JSON 对象内的值?

ios - 隐藏 CoreML 模型 (.mlmodel) 文件

c++ - const_cast<> 在 volatile 上的目的是什么?

c - 在C中将整数显示为十六进制

Pandas 数据框将列类型转换为字符串或分类

ios - 我如何确定我的 Alamofire 请求的优先级,以便它们在函数返回之前执行?

ios - 如何访问特定目录中的所有图像?

vb.net - 从类型 'String' 到类型 'String' 的转换无效

c++ - 对重载整数构造函数的调用不明确

ios - NSString 的值是 iOS 中的 NSInteger 值吗