Reputation: 2132
I have array of arrays - var days: [[Int]] = [[1], [1,2,3], [7]]
and I'd like to convert Int
into name by String
and add it at new array arrayOfStringDays
. My code:
var days: [[Int]] = [[1], [1,2,3], [7]]
var arrayOfStringDays = [[String]]()
for i in 0..<days.count {
switch days[i] {
case [1]:
arrayOfStringDays.append(["one"])
case [1,2,3]:
arrayOfStringDays.append(["one, two, three"])
case [7]:
arrayOfStringDays.append(["seven"])
default:
break
}
}
but I see error near every case:
Expression pattern of type '[Int]' cannot match values of type '[Int]'
in what is my mistake? thanks!
Upvotes: 1
Views: 158
Reputation: 539705
Update: Conditional conformance has been implemented Swift 4.1,
and in particular arrays (and some other collection types) conform
to Equatable
if their elements do.
Your code now compiles without problems in Xcode 9.3.
The switch
statement uses the "pattern-match" operator
public func ~=<T : Equatable>(a: T, b: T) -> Bool
to compare the given value against the various cases.
The problem is that Array
does not conform to
Equatable
, even if the array elements are Equatable
.
(This is going to change with Swift 4, see
SE-0143 Conditional conformances.)
May I suggest a different solution?
A nested map
to convert the nested array, and a number formatter
with "spell-out" style to convert numbers to words:
let days: [[Int]] = [[1], [1,2,3], [7]]
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.numberStyle = .spellOut
let arrayOfStringDays = days.map {
$0.map { formatter.string(from: $0 as NSNumber) ?? String($0) }
}
print(arrayOfStringDays)
// [["one"], ["one", "two", "three"], ["seven"]]
You can also set the formatter locale to a different language, or use the default value to get the result in the user's default language. Example:
formatter.locale = Locale(identifier: "ru")
// ...
print(arrayOfStringDays)
// [["один"], ["один", "два", "три"], ["семь"]]
Upvotes: 4
Reputation: 978
I don't know about exact error, but you can do conversion of [[Int]] something like this.
var days: [[Int]] = [[1], [1,2,3], [7]]
let numberStr = ["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
let daysInString = days.map { (intList) -> [String] in
return intList.map({ (intValue) -> String in
return numberStr[intValue]
})
}
print(daysInString)
// Output : [["One"], ["One", "Two", "Three"], ["Seven"]]
Upvotes: 1