转载

let 心得

在定义一个属性,但又需要设置一些属性,可以使用下面这种形式定义。

let dateFormatter: NSDateFormatter = {  let formatter = NSDateFormatter()  formatter.dateFormat = "yyyy.MM.dd"  return formatter }() let style: [String: NSObject] = {  let font = UIFont(name: "HelveticaNeue-Medium", size: 16.0)!  let textColor = UIColor.blueColor()  let paraStyle = NSMutableParagraphStyle()  paraStyle.lineSpacing = 5.0  paraStyle.lineBreakMode = .ByWordWrapping  paraStyle.paragraphSpacing = 0  paraStyle.paragraphSpacingBefore = 0  return [NSForegroundColorAttributeName: textColor,   NSKernAttributeName: CGFloat(0.5),   NSFontAttributeName: font,   NSParagraphStyleAttributeName: paraStyle  ] }()  

其实,我们应该尽量使用 let , @NatashaTheRobot 发过一条推:

Convert your CoreData NSManagedObjects into structs to avoid mutable state!

let 心得

如果不需要修改属性,我觉得可以更绝决一点,

import Foundation import CoreData struct Task: Equatable {  let id: String  let title: String } func ==(lhs: Task, rhs: Task) -> Bool {  return lhs.id == rhs.id && lhs.title == rhs.title } extension Task {  init(managedTask: NSManagedObject) {   id = managedTask.valueForKey("id") as! String   title = managedTask.valueForKey("title") as! String  } }  
正文到此结束
Loading...