Ios 奇怪的快速协议行为
无法使用swift协议简化UIPageViewController: 我有这个协议Ios 奇怪的快速协议行为,ios,swift,protocols,swift-protocols,Ios,Swift,Protocols,Swift Protocols,无法使用swift协议简化UIPageViewController: 我有这个协议 protocol Pagable { var pageIndex: Int? { get set } } 我让UIPageViewController呈现的所有UIViewController都符合此要求 然后在我的UIPageViewController中,我执行以下操作: var vc = StoryboardScene.Challenges.acceptedViewController() as!
protocol Pagable {
var pageIndex: Int? { get set }
}
我让UIPageViewController呈现的所有UIViewController都符合此要求
然后在我的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
上得到一个错误,说“不能分配给Int?
类型的不可变表达式”
我完全糊涂了。我想了解一下为什么类型系统会对我这样做。中
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
vc
是一个变量,但(vc as?Pagable)
是一个不可变的表达式
解决方案是声明“仅类协议”:
然后编译器知道所有一致类型都是引用类型,
这样即使引用本身也可以将属性指定给
是常数。In
var vc = StoryboardScene.Challenges.acceptedViewController()
(vc as? Pagable)?.pageIndex = index
vc
是一个变量,但(vc as?Pagable)
是一个不可变的表达式
解决方案是声明“仅类协议”:
然后编译器知道所有一致类型都是引用类型,
这样即使引用本身也可以将属性指定给
是常量。如果让vc=StoryboardScene.Challenges.acceptedViewController()作为,请尝试
?pagatable{vc.pageIndex=index;return vc}
如果我的所有UIViewController…都符合使用可选绑定的目的是什么?为什么pageIndex
是可选的?我知道我试图做的不是最佳实践,而是重构为更好的方法(将pageIndex
转换为常量并在子VC中赋值)。但是我仍然想理解为什么不允许使用(vc作为?Pagable)?.pageIndex=index
,因为您使用的是可选链接,它不处理易变性/不可变性。如果让vc=StoryboardScene.Challenges.acceptedViewController()作为,请尝试?pagatable{vc.pageIndex=index;return vc}
如果我的所有UIViewController…都符合使用可选绑定的目的是什么?为什么pageIndex
是可选的?我知道我试图做的不是最佳实践,而是重构为更好的方法(将pageIndex
转换为常量并在子VC中赋值)。但是我仍然想理解为什么不允许使用(vc作为?Pagable)?.pageIndex=index
。这应该可以,因为您使用的是可选链接,它不处理易变性/不可变性。这很有意义,谢谢!是(vc as?Pagable)
if let语法的缩写?@AndrewSB:No。据我所知,as?
运算符返回一个新的(不可变)表达式。这里有一个更简单的例子:var x=123;x=456编译,但var x=123;(x as Int)=456
没有。这很有道理,谢谢!是(vc as?Pagable)
if let
语法的缩写?@AndrewSB:No。据我所知,as?
运算符返回一个新的(不可变)表达式。这里有一个更简单的例子:var x=123;x=456编译,但var x=123;(x为Int)=456
不适用。