Skip to content

Instantly share code, notes, and snippets.

@VojtaStavik
VojtaStavik / HeyJude.swift
Created October 19, 2019 11:12
HeyJude - FizzBuzz style
var heyJude = ""
for verse in 0..<4 {
heyJude += "Hey Jude, don't "
switch verse {
case 0, 3: heyJude += "make it bad\nTake a sad song and make it better"
case 1: heyJude += "be afraid\nYou were made to go out and get her"
case 2: heyJude += "let me down\nYou have found her, now go and get her"
default: fatalError()
}
var vc1: UIViewController? = .init()
weak var weakVC1 = vc1
vc1 = nil
print(weakVC1 ?? "nil")
var vc2: UIViewController? = .init()
vc2?.loadViewIfNeeded() // Commenting this line out makes `weakVC2` nil, too.
weak var weakVC2 = vc2
vc2 = nil
print(weakVC2 ?? "nil")
class Object { }
var a: Object? = Object()
weak var weakA = a
a = nil
print(a ?? "nil")
print(weakA ?? "nil")
print("-------------------------------------------------")
@VojtaStavik
VojtaStavik / UIKit_Table.swift
Created November 14, 2017 13:13
Code from the blog post about namespacing UITableView API. See http://vojtastavik.com/2017/11/14/namespace-all-the-things/
import UIKit
enum UIKit { // UIKit namespace simulation
enum Table { // The new "root" namespace for UITableView
typealias View = UITableView
typealias ViewController = UITableViewController
typealias Cell = UITableViewCell
}
}
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
+ (NSInteger) calculateHammingDistanceFor:(NSInteger)x and:(NSInteger)y {
// Step 1: Find different bits
NSUInteger differentBits = x ^ y;
// Step 2: Count them
NSUInteger counter = 0;
while (differentBits > 0) {
NSUInteger maskedBits = differentBits & 1;
if (maskedBits != 0) {
counter++;
func calculateHammingDistance(x: Int, y: Int) -> Int {
// Step 1: Find different bits
let signedDifferentBits = x ^ y
// We bitcast Int to UInt to allow the algorithm work correctly also for negative numbers.
var differentBits: UInt = unsafeBitCast(signedDifferentBits, to: UInt.self)
// Step 2: Count them
var counter = 0
x & y
// Bitwise AND: Combines the bits of two numbers.
// It returns a new number whose bits are set to 1 only
// if the bits were equal to 1 in both input numbers
Example:
7 ==> 0 1 1 1
3 ==> 0 0 1 1
--------------
7 & 3 ==> 0 0 1 1
x >> a
// Bitwise shift: shifts all bits to the right of 'a' positions
// (operator << to the left)
Example:
8 ==> 1 0 0 0
8 >> 1 ==> 0 1 0 0
8 >> 2 ==> 0 0 1 0
8 >> 3 ==> 0 0 0 1
8 >> 4 ==> 0 0 0 0
2 ==> 0 1 0
6 ==> 1 1 0
----------------
2 ^ 6 ==> 1 0 0 // 100 in binary represents number 4