Cómo escribir el método Init en Swift
Quiero escribir init
método en swift
, Aquí he dado NSObject
clase modelo en Objective-C
-(id)initWithNewsDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self) {
self.title = dictionary[@"title"];
self.shortDescription = dictionary[@"description"];
self.newsDescription = dictionary[@"content:encoded"];
self.link = dictionary[@"link"];
self.pubDate = [self getDate:dictionary[@"pubDate"]];
}
return self;
}
¿Cómo puedo escribir este método en swift
?
4 answers
Eso podría ser una buena base para tu clase, supongo:
class MyClass {
// you may need to set the proper types in accordance with your dictionarty's content
var title: String?
var shortDescription: String?
var newsDescription: String?
var link: NSURL?
var pubDate: NSDate?
//
init () {
// uncomment this line if your class has been inherited from any other class
//super.init()
}
//
convenience init(_ dictionary: Dictionary<String, AnyObject>) {
self.init()
title = dictionary["title"] as? NSString
shortDescription = dictionary["shortDescription"] as? NSString
newsDescription = dictionary["newsDescription"] as? NSString
link = dictionary["link"] as? NSURL
pubDate = self.getDate(dictionary["pubDate"])
}
//
func getDate(object: AnyObject?) -> NSDate? {
// parse the object as a date here and replace the next line for your wish...
return object as? NSDate
}
}
Modo avanzado
Me gustaría evitar copiar-pand-pegar las claves en un proyecto, así que pondría las posibles claves en, por ejemplo, un enum
como este:
enum MyKeys : Int {
case KeyTitle, KeyShortDescription, KeyNewsDescription, KeyLink, KeyPubDate
func toKey() -> String! {
switch self {
case .KeyLink:
return "title"
case .KeyNewsDescription:
return "newsDescription"
case .KeyPubDate:
return "pubDate"
case .KeyShortDescription:
return "shortDescription"
case .KeyTitle:
return "title"
default:
return ""
}
}
}
Y puede mejorar su método convenience init(...)
como, por ejemplo, este, y en el futuro puede evitar cualquier posible error de escritura de las claves en su código:
convenience init(_ dictionary: Dictionary<String, AnyObject>) {
self.init()
title = dictionary[MyKeys.KeyTitle.toKey()] as? NSString
shortDescription = dictionary[MyKeys.KeyShortDescription.toKey()] as? NSString
newsDescription = dictionary[MyKeys.KeyNewsDescription.toKey()] as? NSString
link = dictionary[MyKeys.KeyLink.toKey()] as? NSURL
pubDate = self.getDate(dictionary[MyKeys.KeyPubDate.toKey()])
}
NOTA: eso es solo una idea cruda de cómo podría hacerlo, no es necesario usar conveniece inicializador en absoluto, pero parecía elección obvia con respecto a no se nada acerca de su clase final – usted ha compartido un solo método.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 09:32:01
class myClass {
var text: String
var response: String?
init(text: String) {
self.text = text
}
}
Ver Swift: Inicialización (mejor googlear usted mismo la próxima vez..)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 08:44:46
No es necesario llamar a este método desde otra clase, se llamará automáticamente
override init()
{
super.init()
//synthesize.delegate = self
// println("my array elements are \(readingData)")
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 09:47:30
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 08:47:23