0

I need to convert the following Objective-C code to Swift.

static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
});

How do I do that? I Googled and found out this example.

class SingletonC {

    class var sharedInstance : SingletonC {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : SingletonC? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SingletonC()
        }
        return Static.instance!
    }
}

But is it for returning a single of a class.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Isuru
  • 30,617
  • 60
  • 187
  • 303
  • 1
    The other questions on this topic have had to do with shared singleton instances of a class, whereas this is about a static variable within the scope of a function. Initialization is different in this case from an always-available singleton, so a different question seems useful. – Nate Cook Dec 15 '14 at 19:54

1 Answers1

8

This is from this Ray Wenderlich tutorial, right? Swift doesn't have static variables that can be scoped to functions, but you can nest a type inside a function, and give it static variable. Here's a Swift equivalent version of the start of that method:

func heightForBasicCellAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
    struct Static {
        static var sizingCell: RWBasicCell?
    }

    if Static.sizingCell == nil {
        Static.sizingCell = tableView.dequeueReusableCellWithIdentifier(RWBasicCellIdentifier) as RWBasicCell
    }

    // ...
}
Nate Cook
  • 92,417
  • 32
  • 217
  • 178