我正在一个项目上,我创建了一个类来处理json响应,以将其转换为模态类,并根据需要将其更改回具有更新数据的json请求。
在该类中,我正在从字典中获取值并将其保存到字典中。我需要为字典键创建一个枚举,以使复杂键格式的错误机会减少。
我什至尝试使用
enum Fields {
case Name
case Email
}
但是Fields.Email返回Fields对象
如果我使用类似变量的协议
protocol someProtocol {
var name: String { get }
}
extension someProtocol {
var name:String {
return String(describing: self)
}
}
,然后扩展enum Fields:someProtocol
那么我可以像Fields.name.name or Fields.email.name
但是我的客户不同意这个,我想创建一个枚举,以便我可以直接访问该字符串,就像我想要键“ Name”的名称一样,并且应该让它看起来像“ Fields.name”或“ .name”。< / p>
所以这里我有两个目标
—
class PersonService {
class Update {
var name = ""
var email = ""
var personId = 0
func createDataFrom(dic:[AnyHashable : Any]) -> Update {
let update = Update()
update.name = dictionary["Name"]
update.email = dictionary["Email"]
update.personId = dictionary["Id"]
return update
}
func createDataTo() -> [AnyHashable:Any] {
var ret = [AnyHashable : Any]()
ret["Name"] = name
ret["Email"] = email
ret["Id"] = personId
return ret
}
}
}
答案 0 :(得分:0)
类似的东西吗?
function GetAge(const BirthDate, CurrentDate: TDateTime): Integer;
var
y1, m1, d1: Word; //born
y2, m2, d2: Word; //today
begin
Result := 0;
if CurrentDate < BirthDate then
Exit;
DecodeDate(BirthDate, y1, m1, d1);
DecodeDate(CurrentDate, y2, m2, d2);
//Fudge someone born on the leap-day to Feb 28th of the same year
//strictly for the purposes of this calculation
if ( (m1=2) and (d1=29) )
and
( not IsLeapYear(y2) ) then
begin
d1 := 28;
end;
Result := y2-y1; //rough count of years
//Take away a year of the month/day is before their birth month/day
if (m2 < m1) or
((m2=m1) and (d2<d1)) then
Dec(Result);
end;
enum Fields: String {
case Name = "Name"
case Email = "Email"
}
或
Print(Fields.Name.rawValue)
result: "Name"
struct Constants {
static let name = "Name"
static let email = "Email"
}