Skip to content

Instantly share code, notes, and snippets.

@Gernot
Created April 1, 2015 10:06
Show Gist options
  • Save Gernot/18e08ea1cb446f445f2e to your computer and use it in GitHub Desktop.
Save Gernot/18e08ea1cb446f445f2e to your computer and use it in GitHub Desktop.
struct Time {
/* Is there any good way to do this without the intermediate vars? Swift 1.2 (Xcode 6.3b4) does not seem to let me write into the structs constants directly before initializing them. */
init(date: NSDate) {
var hour: Int = 0, minute: Int = 0, second: Int = 0, nanosecond: Int = 0
NSCalendar.currentCalendar().getHour(&hour, minute: &minute, second: &second, nanosecond: &nanosecond, fromDate: date)
self.hour = hour; self. minute = minute; self.second = second; self.nanosecond = nanosecond
}
let hour: Int
let minute: Int
let second: Int
let nanoSecond: Int
}
@mrcljx
Copy link

mrcljx commented Apr 1, 2015

Swift can’t know if getHour will try to read uninit’ed vars, will initialise them, or keeps refs and write them later. So it's good this got fixed in 1.2 so it doesn't allow that anymore.

I only see the option of using visibility modifiers.

import UIKit

struct Time {

  init(date: NSDate) {
    NSCalendar.currentCalendar().getHour(&self.hour, minute: &self.minute, second: &self.second, nanosecond: &self.nanoSecond, fromDate: date)
  }

  private(set) public var hour: Int = 0
  private(set) public var minute: Int = 0
  private(set) public var second: Int = 0
  private(set) public var nanoSecond: Int = 0
}

let t = Time(date: NSDate())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment