I would like to define a constant string variable as a variable in class.(More precisely for both key and value).
The example I'm working on is as follows.This code is in a class called JsonHandler.
enum JsonTcpStatus: Int {
case JSON_GET = 4
}
let JSON_NAME_METHOD = "A"
let getJSON: String = {
do {
let temp_dic = [JSON_NAME_METHOD: JsonTcpStatus.JSON_GET.rawValue]
let jsonData = try JSONSerialization.data(withJSONObject: temp_dic, options: [])
let str = String(data: jsonData, encoding: String.Encoding.utf8)! + "\r"
return str
} catch let error as NSError {
print(error)
}
return ""
}()
This code does not work and gives error: "Instance member 'JSON_NAME_METHOD' cannot be used on type 'JsonHandler'"
I get the same error in the code below.
enum JsonTcpStatus: Int {
case JSON_GET = 4
}
let JSON_NAME_METHOD = "A"
let getJSON: String = {
do {
var temp_dic = [String: Any]()
temp_dic[JSON_NAME_METHOD] = JsonTcpStatus.JSON_GET.rawValue
let jsonData = try JSONSerialization.data(withJSONObject: temp_dic, options: [])
let str = String(data: jsonData, encoding: String.Encoding.utf8)! + "\r"
return str
} catch let error as NSError {
print(error)
}
return ""
}()
The json I want is => {"A":4}