replacingOccurrences throws an error by using an array for options

為{幸葍}努か 提交于 2021-02-05 12:32:16

问题


Can someone explain me the difference between the following code snippets?
I do not understand why the second one throws an error.

This one works:

"Anno 1800".replacingOccurrences(of: "N", with: "#", options: [.regularExpression, .caseInsensitive], range: nil)

But this one gives an error:

let optionsArr = [NSString.CompareOptions.regularExpression, NSString.CompareOptions.caseInsensitive]
"Anno 1800".replacingOccurrences(of: "N", with: "#", options: optionsArr, range: nil)

error: StringExtensions.playground:110:63: error: cannot convert value of type '[NSString.CompareOptions]' to expected argument type 'String.CompareOptions' (aka 'NSString.CompareOptions') "Anno 1800".replacingOccurrences(of: "N", with: "#", options: optionsArr, range: nil)


回答1:


Please read the error message carefully.

cannot convert value of array something to expected argument type non-array something.

Well, the syntax of an OptionSet and an array is quite similar, we got comma separated items wrapped in square brackets.

Unfortunately they are different. To specify an OptionSet literally you have to annotate the type to avoid ambiguity.

let optionsArr : String.CompareOptions = [NSString.CompareOptions.regularExpression, NSString.CompareOptions.caseInsensitive]
"Anno 1800".replacingOccurrences(of: "N", with: "#", options: optionsArr, range: nil)

After specifying the type you can write the expression swiftier

let optionsArr : String.CompareOptions = [.regularExpression, .caseInsensitive]

The first version works because the compiler is clever enough to infer the type



来源:https://stackoverflow.com/questions/61447180/replacingoccurrences-throws-an-error-by-using-an-array-for-options

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!