0
votes

I am playing with Swift and Xcode. This works in playground:

[["1","2"], ["3","4"]][0]

But this does not work in Xcode project:

enum UnitSystem: Int {
    case Standard = 0
    case Metric = 1
}

class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate {
    @IBOutlet weak var unitSystemControl: UISegmentedControl!  //"Standard" and "Metric"
    var units: [[String]]! = nil
    var currentUnitSystem: UnitSystem! = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        currentUnitSystem = UnitSystem(rawValue: unitSystemControl.selectedSegmentIndex)
        units = [["ft.", "in."], ["m.", "cm."]][currentUnitSystem.rawValue]
    }
    ...
    ...
}

I am getting this error: Type '[String]' does not conform to protocol 'StringLiteralConvertible'

Questions:

  • How to deal with this error?
  • Is there a cleaner/better way to switch out the units on the fly?
  • It seems like I don't quite grasp the whole idea of ! and ? types in Swift, is there an easy-to-understand tutorial somewhere?

Thank you!

1
The problem was my var units: [[String]]! = nil, making it var units: [String]? = nil makes it work. The last two questions still stand, though. - Dormidont

1 Answers

0
votes

This problem isn’t related to your use of optionals. It’s simpler than that.

In your playground, look at the value returned by [["1","2"], ["3","4"]][0]. It’s not a [[String]] (an array of arrays of strings). It’s a [String] (the first entry in your array of arrays).

But in your second example, you’re trying to assign this value to a variable that is of type [[String]]. Just change the type of units to [String].