How to write Init method in Swift

I want to write init method in swift, Here I given NSObject model class in 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;
}

How can I write this method in swift ?

  • How to check if an variable of any type is an array
  • Receive touch events at SKScene AND SKSpriteNode in SpriteKit
  • Inappropriate Expected declaration error
  • Automatically generate the Swift interface for a compiled module
  • Setting preferred focus in TVOS on an SKSpriteNode?
  • Swift 3: How do I pinch to scale and rotate UIImageView?
  • 4 Solutions Collect From Internet About “How to write Init method in Swift”

    that could be good bases for your class, I guess:

    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
        }
    
    }
    

    advanced-mode

    I would like to avoid to copy-pand-paste the keys in a project, so I’d put the possible keys into e.g. an enum like this:

    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 ""
            }
        }
    }
    

    and you can improve your convenience init(...) method like e.g. this, and in the future you can avoid any possible mistyping of the keys in your code:

    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()])
    
    }
    

    NOTE: that is just a raw idea of how you could do it, it is not necessary to use conveniece initializer at all, but it looked obvious choice regarding I don’t know anything about your final class – you have shared one method only.

    class myClass {
        var text: String
        var response: String?
    
        init(text: String) {
            self.text = text
        }
    }
    

    See Swift: Initialization (better off google it yourself next time..)

    Do not need for call this method from other class it will get called automatically

    override init()
        {
            super.init()
             //synthesize.delegate = self
           // println("my array elements are \(readingData)")
    
        }
    

    try:

    initWithDictionary(dictionary : NSDictionary) {
    
       init()
    
       self.title = ... etc
    
    }
    

    Source: