问题
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