Reputation: 5616
When trying to create the array below, I get the following error:
type of expression is ambiguous without more context
Is an array such as this possible in Swift? If yes, how is it declared?
var jobArray = [
["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"],
["Babysitter", "Job Description", ["Tuesday", "Wednesday"], "15"],
["Leaves Raker", "Job Description", ["Sunday", ""], "10"]
]
Upvotes: 1
Views: 760
Reputation: 40955
I’m guessing in your playground you aren’t importing Foundation
or anything similar:
// uncommenting the below line fixes the problem
// import Foundation
// with it commented out,
var jobArray = [
["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"],
["Babysitter", "Job Description", ["Tuesday", "Wednesday"], "15"],
["Leaves Raker", "Job Description", ["Sunday", ""], "10"]
]
Without it you get two errors:
error: '_' is not convertible to 'StringLiteralConvertible' ["Dog Walker", "Job Description", ["Monday", "Wednesday", "Friday"], "7"], ^~~~~~~~~~~~~~~~~ error: type of expression is ambiguous without more context
The first one is much more important. The second one is an artifact of Swift going up and going home.
Why? Because what would the type of [jobArray]
be? There is no type in the Swift standard library that would fit this definition – you’d need a [[Something]]
where Something
conformed to both StringLiteralConvertible
(for "Dog Walker"
) and ArrayLiteralConvertible
(for ["Sunday", ""]
). And there ain’t one.
Sadly, very sadly IMHO, such things are defined within Foundation
. Which is why it compiles when you add the import.
I would strongly suggest, instead of defining this array like this, that you implement a simple struct
:
struct Job {
let jobDescription: String
let days: [String] // or even an enum for the days of the week
let hourlyPay: Double
}
var jobArray = [
Job(jobDescription: "Dog Walker", days: ["Monday", "Wednesday", "Friday"], hourlyPay: 7),
Job(jobDescription: "Babysitter", days: ["Tuesday", "Wednesday"], hourlyPay: 15),
// etc
]
Upvotes: 3