新的SwiftUI教程有以下代码:
struct ContentView: View {
var body: some View {
Text("Hello World")
}
}
第二行是单词some,在他们的网站上突出显示,就好像它是一个关键字一样。
Swift 5.1似乎没有把some作为关键字,而且我不知道some这个词还能在那里做什么,因为它在类型通常的位置。有没有一个新的、未公布的Swift版本?它是一个我不知道的被用在类型上的函数吗?
关键字有的作用是什么?
'some'表示不透明类型。在SwiftUI中,View被声明为一个协议
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required `body` property.
associatedtype Body : View
/// Declares the content and behavior of this view.
var body: Self.Body { get }
}
当你将视图创建为Struct时,你要遵守视图协议,并告诉var主体将返回一些将确认视图协议的内容。它就像一个通用的协议抽象,你不必定义具体的类型。