Skip to content

Instantly share code, notes, and snippets.

View RinniSwift's full-sized avatar
🔸
Swifting

Rinni Swift RinniSwift

🔸
Swifting
View GitHub Profile
var dict = ["blue": 2, "grey": 1, "purple": 4, "red": 2]
// subscript(key:)
dict["blue"] // Optional(2)
// subscript(key:default:)
dict["grey", default: 0] // 1
// subscript(position:)
if let ind = dict.firstIndex(where: { ($0.key == "red") }) {
// 1. initializing dictionaries with the minimumCapacity(_:)
var someDict = Dictionary<String, Int>(minimumCapacity: 8)
someDict.capacity // 12
// 2. initializing dictionaries with unique key-value sequences
let newDict = Dictionary(uniqueKeysWithValues: zip(["one", "two", "three"], 1...3))
// ["two": 2, "three": 3, "one": 1]
// 3. initializing dictionaries with sequence of key-value tuples (drops duplicates)
let romanNumTuples = [("I", 1), ("V", 5), ("X", 10), ("L", 50), ("L", 44)]
// 1. empty dictionary initialization
var numbers = Dictionary<String, Int>()
var newNumbers: Dictionary<String, Int> = Dictionary()
// 2. empty dictionary initialization using dictionary literals
var nums = [String: Int]()
var newNums: [String: Int] = [:]
// 3. predefininig elements with dictionary literals
var romanNumerals = ["I": 1, "V": 5, "X": 10, "L": 50] // using type inference
var numbers = Set<Int>(minimumCapacity: 30)
numbers.capacity // 48
var numbers = Set<Int>()
numbers.insert(3) // (true, 3)
numbers.insert(22) // (true, 22)
numbers.insert(22) // (false, 22)
// 1. empty set initialization
var numbers = Set<Int>()
var nums: Set<Int> = Set()
// 2. empty set initialization with array literal
var numbersSet: Set<Int> = []
// 3. creating set with predefined elements using array literals
var newNums: Set = [1, 2, 3, 4]
class CircularBuffer<T> {
var bufferMaxSize: Int
var size = 0
var elements = Array<T?>(repeating: nil, count: 8)
var front: T? {
if isEmpty() {
return nil
} else {
func dequeue() -> T? {
// ...
// 1.
if !isEmpty() {
// 2.
let front = elements[bufferMaxSize - size]
elements[bufferMaxSize - size] = nil
size -= 1
class CircularBuffer<T> {
// ...
func enqueue(item: T) {
// 1.
if isEmpty() {
elements[bufferMaxSize-1] = item
} else {
class CircularBuffer<T> {
// ...
// 1.
var front: T? {
if isEmpty() {
return nil
} else {
// 2.