如何将定义的let a = [1, 2, 3]
转换为Array<CustomStringConvertible>
最方便?
类似于a as! [CustomStringConvertible]
,let b: [CustomStringConvertible] = a
,let b = Array<CustomStringConvertible>(s: a)
......
答案 0 :(得分:0)
let a = [1, 2, 3]
已经是符合CustomStringConvertible
的类型数组,因为a
是[Int]
,而Int
符合CustomStringConvertible
延期:
extension Int : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String { get }
}
所以这将始终有效:
let a = [1, 2, 3] as? Array<CustomStringConvertible> // Conditional cast always succeeds
答案 1 :(得分:0)
一个好问题!
正如我所想,Swift支持ALTER TABLE YOURSCHEMA.YOURTABLE
ALTER COLUMN YOURIDENTITYCOL RESTART WITH <new value>
类型的协方差,但似乎只支持类的协方差。例如,这段代码
Array
完美无缺。但是,如果我们将class Animal {
}
class Cat: Animal {
}
let cats = [Cat(), Cat()]
let animals: [Animal] = cats
更改为class Animal
,它就会停止工作并显示错误。
所以,我认为解决方案是
protocol Animal
let animals: [Animal] = cats