无法转换字符串...为字符串斯威夫特
我试图做一个简单的debuger在视图中..我有以下几点: 无法转换字符串...为字符串斯威夫特
我使用Alamofire发出请求,用responseString
接收数据,然后用App.log(response)
向debugViewController
的log
发送数据,正如你所看到的那样,这个方法也需要一个字符串。
现在,试图编译这个返回的错误对我来说很奇怪,因为我是Swift新手。无法将字符串转换为debugViewController.log()
中预期的参数类型,实际上它也是String
?
请让我在这一个。
在这里,你有debugViewController
:
import UIKit
class debugViewController: UIViewController {
@IBOutlet weak var debugTextField: UITextView!
@IBAction func dismissDebug(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func log(data: String) {
debugTextField.text = data
}
}
在这里,你可以看到我是如何拨打电话和发送数据:
Alamofire.request(.POST, API_URL, parameters: [ "action": "authenticate", "email": userEmail!, "password": userPassword! ])
.responseString { response in
guard let value = response.result.value else
{
return App.alert("error", message: "Did not receive data")
}
guard response.result.error == nil else
{
print(response.result.error)
return App.alert("error", message: "An error occurred")
}
App.log (value)
}
debugViewController
是一个类(我建议你开始的类名用大写字母),并且您试图在类本身上调用一个实例方法,因此错误(因为它实际上预计类型为debugViewController
的实例)。
你应该保持debugViewController
的一个实例被创建,所以你可以调用实例,而不是在类中的日志方法
好吧,从外行的角度来说,我做错了什么是我正在调用非实例化类的动态方法吗?我的意思是,我没有Swift背景,但我知道一些OOP。关于camelCase的东西,我刚刚读过使用camelCase模式更好,但是,好像我错了。无论如何,为什么如果我将func更改为静态,我无法访问日志方法中的'debugTextField'? – Eduard
是@giorashc是对的。您正在调用debugViewController的实例方法。您可以创建实例或将方法日志方法作为类方法。 – iamyogish
@edduvs您无法访问log方法中的debugTextField,因为它是debugViewController类的属性。要访问一个类的属性,你需要创建一个实例。 – iamyogish
如何debugViewController定义了它?看起来你正在调用类本身的实例方法 – giorashc
@giorashc更新了我的问题。 – Eduard
你可以发布代码分配数据的地方吗?另外,检查数据是否不是可选的。如果是,然后尝试解开它像数据! –