Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift将数组作为参数传递错误_Ios_Swift - Fatal编程技术网

Ios Swift将数组作为参数传递错误

Ios Swift将数组作为参数传递错误,ios,swift,Ios,Swift,我刚开始学斯威夫特。有人能解释一下为什么我可以将数组作为参数传递(byRoundingCorners:) 但在变量中传递它会产生错误 var corners = [UIRectCorner.topLeft, UIRectCorner.bottomLeft] let path = UIBezierPath( roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSiz

我刚开始学斯威夫特。有人能解释一下为什么我可以将数组作为参数传递(byRoundingCorners:)

但在变量中传递它会产生错误

var corners = [UIRectCorner.topLeft, UIRectCorner.bottomLeft]
let path = UIBezierPath(
        roundedRect: self.bounds,
        byRoundingCorners: corners,
        cornerRadii: CGSize(width: radius, height: radius))

“无法将“[UIRectCorner]”类型的值转换为预期的参数类型“UIRectCorner”

它不是数组。这是一个
选项
byRoundingCorners
参数需要一种类型的
UIRectCorner
,它扩展了
OptionSet

如果您将
角点声明更新为:

var corners: UIRectCorner = [.topLeft, .bottomLeft]
然后您的代码将按预期工作

这里的
[]
语法不是真正的数组,而是集合的选项列表

您的第一次尝试是有效的,因为编译器可以从参数推断数据类型(
UIRectCorner

但当你这么做的时候:

var corners = [UIRectCorner.topLeft, UIRectCorner.bottomLeft]
推断的类型是
UIRectCorner
的数组,而不是
UIRectCorner
。通过将
:UIRectCorner
添加到行中,您可以清楚地知道类型是什么,并且使用
[]
的语法正确地解释为选项列表,而不是数组

正如Martin R(感谢)所提到的,
OptionSet
扩展了
expressiblebyaryarrayliteral
,它允许使用类似数组的文字语法在函数调用中为
UIRectCorner
赋值,因此当您在函数调用中编写
[.topLeft,.bottomLeft]
时,Swift会根据该数组文本自动创建
UIRectCorner
的实例

然而,当你写作的时候

var corners = [UIRectCorner.topLeft, UIRectCorner.bottomLeft]
您可以创建一个
UIRectCorner
选项集数组,而不是包含所有不同案例的单个选项集

您可以通过将
corners
的类型指定为
UIRectCorner
来解决这个问题。这还允许您推断数组文字中的类型:

var corners: UIRectCorner = [.topLeft, .topRight]

Swift 5对于有问题的人来说,尝试追加并最终找到insert是解决可变情况的方法

    var cornersToRound: UIRectCorner = []
    if topLeftRounded { cornersToRound.insert(.topLeft) }
    if topRightRounded { cornersToRound.insert(.topRight) }
    if bottomRightRounded { cornersToRound.insert(.bottomRight) }
    if bottomLeftRounded { cornersToRound.insert(.bottomLeft) }

已经有足够多的答案了,但是有人可能会添加OptionSet(间接)继承自ExpressibleByArrayLiteral,这就是允许在初始化中传递文本数组的原因。
    var cornersToRound: UIRectCorner = []
    if topLeftRounded { cornersToRound.insert(.topLeft) }
    if topRightRounded { cornersToRound.insert(.topRight) }
    if bottomRightRounded { cornersToRound.insert(.bottomRight) }
    if bottomLeftRounded { cornersToRound.insert(.bottomLeft) }