下标上下文时强制转换为数组或字典类型:任何

时间:2018-07-19 02:57:51

标签: swift

我已经知道下标context:Any时得到的数据具有 Any 类型。我正在尝试确保数据支持下标,例如数组或字典。

我尝试将数组和字典类型转换为不成功,并且阅读了许多与下标和转换有关的问题,但是没有一个问题说明下标context:Any的使用。我该怎么办?

public var recieverNumber = ""
public var recieverName = ""

class Messenger: WKInterfaceController, WCSessionDelegate {

@IBAction func send() {
    let newNumber = recieverNumber.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
    let escapedString = message.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    WKExtension.shared().openSystemURL(URL(string: "sms:&recipients=\(newNumber)&body=\(escapedString)")!)

    recieverNumber = ""
    recieverName = ""
    // ...code...
    dismiss()
}

@IBAction func contacts() {
    recieverNumber = ""
    recieverName = ""
    // ...code...
    dismiss()
}

// ...code...

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    // ...code...
    recieverName = context![0] as! String // error
    recieverNumber = context![1] as! String // error
}

1 个答案:

答案 0 :(得分:1)

最安全的方法是将Any?有条件下调到期望的类型(String数组)

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    guard let receiver = context as? [String], receiver.count > 1 else { return }
    recieverName = receiver[0]
    recieverNumber = receiver[1]
}