奇怪的 Swift 协议行为
Strange Swift Protocol behaviour
使用 swift 协议来简化 UIPageViewController 时遇到问题:
我有这个协议
protocol Pagable {
var pageIndex: Int? { get set }
}
我的所有 UIViewController 都符合 UIPageViewController 的要求。
然后在我的 UIPageViewController 中,我这样做:
var vc = StoryboardScene.Challenges.acceptedViewController() as! Pagable
vc.pageIndex = index
return vc as? UIViewController
有效,但我真正想做的是:
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
return vc
并且出于某种原因,每当我这样做时(对我来说感觉与片段 1 完全相同),我在 (vc as? Pagable)?.pageIndex = index
上收到错误消息说 "Cannot assign to immutable expression of type Int?
".
我彻底糊涂了。很想深入了解为什么类型系统对我这样做。
在
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
vc
是一个变量,但是(vc as? Pagable)
是一个不可变的表达式。
解决方法是声明一个"class-only protocol":
protocol Pagable : class {
var pageIndex: Int? { get set }
}
那么编译器就知道所有的符合类型都是引用类型,
这样 属性 即使引用本身也可以分配给
是常数。
使用 swift 协议来简化 UIPageViewController 时遇到问题:
我有这个协议
protocol Pagable {
var pageIndex: Int? { get set }
}
我的所有 UIViewController 都符合 UIPageViewController 的要求。
然后在我的 UIPageViewController 中,我这样做:
var vc = StoryboardScene.Challenges.acceptedViewController() as! Pagable
vc.pageIndex = index
return vc as? UIViewController
有效,但我真正想做的是:
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
return vc
并且出于某种原因,每当我这样做时(对我来说感觉与片段 1 完全相同),我在 (vc as? Pagable)?.pageIndex = index
上收到错误消息说 "Cannot assign to immutable expression of type Int?
".
我彻底糊涂了。很想深入了解为什么类型系统对我这样做。
在
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
vc
是一个变量,但是(vc as? Pagable)
是一个不可变的表达式。
解决方法是声明一个"class-only protocol":
protocol Pagable : class {
var pageIndex: Int? { get set }
}
那么编译器就知道所有的符合类型都是引用类型, 这样 属性 即使引用本身也可以分配给 是常数。