我想創建一個new object
叫RegisterIn
,對象的目標是產生一個json
對象字典,並返回一個字符串如何在Swift中將JSONObject作爲字符串返回?
這裏是我的代碼
public class RegisterIn {
private var a : String = "" //required
private var b: String = "" //required
private var c: String = "" //required
private var d: Int = 0 //required
private let BD_a : String = "a"
private let BD_b : String = "b"
private let BD_c : String = "c"
private let BD_d : String = "d"
init(a: String, b: String, c: String, d: Int) {
self.a = a
self.b = b
self.c = c
self.d = d
}
func getJSONObject() {
let jsonDic : [String: AnyObject] = [
BD_a: a,
BD_b: b,
BD_c: c,
BD_d: d
]
do {
let jsonObject = try NSJSONSerialization.dataWithJSONObject(jsonDic, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
print(error)
}
}
func toString() {
return String(getJSONObject()) <- this line occur error
}
}
在功能getJSONObject
,我認爲它返回一個jsonObject as [String: AnyObject]
。在我ViewController
,我想將其分配給Label.text
,它總是
我ViewController
:
@IBOutlet weak var jsonLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let a = RegisterIn.init(a: "123", b: "456", c: "789", d: 00000)
jsonLabel.text = a
}
我想我必須改變RegisterIn類中的一些代碼,真的需要一些幫助!
這只是問題的一半。該行'jsonLabel.text =如果了'另一半。 – rmaddy
啊對,只需要'jsonLabel.text = a.toString()'我猜,但我覺得它真的很奇怪,它實際上擊中了函數然後,也許toString以某種方式隱含着一些快速的魔術 – Fonix
你不是指''jsonLabel.text = a.getJSONObject()'? – rmaddy