Classes

Yay, I’m 10% done with 100 Days of Swift! Today was all about classes, and once again I learned a few new things. One thing I’d never explicitly thought about was that the automatic member-wise initializer in Swift structs isn’t available in Swift classes. Another thing that I theoretically knew about, but hadn’t ever used before, was that Swift classes can be marked final to make them un-extendable. I’ve used libraries that mark their classes as final but I’ve never marked any of my own classes that way.

Finally, one thing that was totally new to me was Swift’s deinit keyword in classes. You can use it in the same contexts that you might have used the Objective-C dealloc method:

class DatabaseConnection {
    var hostname: String
    var port: Int
    
    var inputStream: InputStream
    var outputStream: OutputStream
    
    init(hostname: String, port: Int) {
        self.hostname = hostname
        self.port = port
        
        var readStream: Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                           self.hostname as CFString,
                                           UInt32(self.port),
                                           &readStream,
                                           &writeStream)
        
        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()
    }
    
    deinit {
        self.inputStream.close()
        self.outputStream.close()
    }
}