Skip to content

Instantly share code, notes, and snippets.

@mrakowski
Last active October 19, 2016 16:08
Show Gist options
  • Save mrakowski/f3373760ea5c519d8f4293c9815ee772 to your computer and use it in GitHub Desktop.
Save mrakowski/f3373760ea5c519d8f4293c9815ee772 to your computer and use it in GitHub Desktop.
Swift 3 Notes

Absolute value

    abs(-4)

Array / NSArray

    // 2D array
    var matrix = [[Int]]()

    // Convert to String (only works for String objects)
    var array = ["1", "2", "3"]
    let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

    // Create an array of components separated by a given separator
    magazineString.componentsSeparatedByString(" ")

    // Empty array of String objects
    var patterns = [String]()

    // Get range from array
    var test = [1, 2, 3]
    var n = 2
    var test2 = Array(test[0..<n]) // cast to Array (cast Slice to Array)

    // Get last item
    let lastItem : Int = dataArray.last!

    // Insert at index
    anArray.insert("String", atIndex: 0)

    // Range to get subarray. Node: cast ArraySlice to Array
    let midPoint = (rightEnd - leftStart) / 2
    let leftArray = Array(array[0..<midPoint+1])

    // Remove last item
    dataArray.removeLast()

    // Remove an array of objects
    wordArray.removeObjectsInArray(wordsToDelete)

    // Sort array of integers (ascending order)
    var a = [3, 2, 1, 4]
    a = a.sort { $0 < $1 }  // or use sortInPlace
    a.sortInPlace { $0 < $1 }

    // Sort an array of characters
    var charArrayOne = firstString.characters.map{String($0)}
    charArrayOne.sortInPlace { $0 < $1 }
    firstString = charArrayOne.joinWithSeparator("")

    // Swap position of two elements
    swap(&tmpArray[j], &tmpArray[j+1])

Autoresizing mask

    self.customView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Binary

    let input : Int = 3
    let binaryString = String(input, radix: 2)

Bool

    var genBool : Bool = (2 == 1) ? true : false

    true
    false

CGRect

    CGRect(x: 0, y: 0, width: 30, height: 30)

CGSize

    CGSize(width:1, height: 1)

Characters

    // Comparison
    for char in binaryString.characters
        if char == "1" {
        }
    }

    // Convert character to String
    String(tmpChar)

Class

    //
    override init(frame: CGRect) {
      super.init(frame: frame)
      // customization
    }

    // Expose interface to Objective-C
    @objc class GENUtility : NSObject {

    }

    class GENUtility : NSObject {

    }

    // Node class
    public class Node {
        var posX: Int
        var posY: Int
        var filled : Bool

        init() {
            self.posX = -1
            self.posY = -1
            self.filled = false
        }
    }
    var tmpNode : Node

Comments

    //

    /* Block comment */

    // MARK: (similar to #pragma in Xcode)

Constants

let GENDefaultRegularFontName = "HelveticaNeue"

// Global Constant
static let FourInchPhoneScreenHeight = 568.0

Conversions

    // String to Int
    let hourInt = Int("07")

    // Int to String
    let hourString = String(21)

    // CGFloat constructor
    let myCGFloat = CGFloat(myFloat)

    // Int to Float
    Float(n)

Dictionary / NSDictionary

    // Check if object exists for key
    let keyExists = charDictionary[tmpLetter] != nil

    // key: Int. value: String.
    var namesOfIntegers = [Int : String]()

    // Key: String. Value: String.
    var magazineWordDictionary = [String : String]()

    // Iterate through keys/values
    for (word, count) in noteWordDictionary {

    }

Double

    // Convert Int to Double
    Double(tOne)

    // Print (specify precision)
    print(String(format: "%.2f", tmpD))

Enums

    self.selectionStyle = UITableViewCellSelectionStyle.none
    self.selectionStyle = .none

Extension (Category)

    extension SomeType {
      // new functionality to add to SomeType goes here
    }

Float

    // Round down
    floor(tmpFloat)

    // Specify number of decimal places
    print(String(format: "%.2f", 1.0321))

For loop

    for value in anArray {
    }

    //
    for index in 1...5 {
        print("\(index) times 5 is \(index * 5)")
    }

    //
    var i = 0
    while i < 10 {
        i = i + 1
    }

GCD

    let delayTime = DispatchTime.now() + Double(Int64(2.9 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
        // code to execute
    })

Import

    import Foundation

    // Import Swift files into Objective-C - import the Objective-C Generated Interface Header Name
    #import "TargetName-Swift.h"

Integer

    Int.min

Interface Builder

    // IBOutlet
    class MyViewController: UIViewController {

      @IBOutlet weak var button: UIButton!
      @IBOutlet var textFields: [UITextField]!
      @IBAction func buttonTapped(AnyObject) {
          println("button tapped!")
      }
    }

Iterate

    for char in "abcdefghijklmnopqrstuvwxyz".characters {
        print(char)
    }

Logging

    // String interpolation
    print("\(myString) is the integer \(integerValue)")

    // Write to stdout
    print("value")

    // Print without line break (or use custom terminator)
    print(" ", terminator:"")

    //
    print(self.helloLabel.text)
    print("a log in Swift")

Making builds

// May need to regenerate and rename Swift files to be prefixed with target name

Methods / Functions

    // return type void
    func reset() {
        count = 0
    }

    //
    func incrementBy(amount: Int, numberArray: [Int]) {

    }

    //
    func isToTheRightOfX(x: Double) -> Bool {
        return self.x > x
    }

    // inout parameter (modifiable within method)
    public func stairCombinations(n : Int, inout cache : Dictionary<Int, Int> ) -> Int {
    }

    // Multiple output parameters
    func AddAndSubtractTenFromNumber(number: Int) -> (small: Int, large: Int) {

        let smallResult = (number - 10)
        let largeResult = (number + 10)

        return (smallResult, largeResult)
    }
    let answer = AddAndSubtractTenFromNumber(24)
    answer.small
    answer.large

NSDecimalNumber

NSNumber

    NSNumber.init(float:3.1)

Optionals

You specify optional chaining by placing a question mark (?) after the optional value
on which you wish to call a property, method or subscript if the optional is non-nil.

This is very similar to placing an exclamation mark (!) after an optional value to
force the unwrapping of its value.

The main difference is that optional chaining fails gracefully when the optional is nil,
whereas forced unwrapping triggers a runtime error when the optional is nil.

Print

    // Print without line break (or with custom terminator)
    print(" ", terminator:"")

    //
    print(tmpObject)

Properties

  // Optional property
  @IBOutlet var infoView : GENInfoView?

  // Property initialized with value
  var numberLabel = UILabel()

Selector

    #selector(doCustomAction)

stdin / stdout

    // Read an Int from stdin
    let anInt = Int(readLine()!)!
    let intArray = readLine()!.characters.split(" ").map{Int(String($0))!}

    // Read a String from stdin
    let aString = readLine()!
    let stringArray = readLine()!.characters.split(" ").map{String($0)}

stderr


Set

    let numberOfChars = word.characters.count
    let numberOfDistinctChars = Set(word.characters).count

Strings / Characters

    // Append Character to a String
    tmpString = tmpString + String(tmpCharacter)

    // Find substring
    if string.rangeOfString("Swift") != nil {
        print("substring exists")
    }
    // renamed to range(of:"") in Swift 3.0

    // Get substring (using a range)
    let indexStartOfText = s.startIndex.advancedBy(2)
    let indexEndOfText = s.endIndex.advancedBy(-2)
    let midRange = indexStartOfText..<indexEndOfText
    let subString = s.substringWithRange(midRange)

    // Get a character (at a specific index)
    let charAtIndex = someString[someString.startIndex.advancedBy(10)] // Swift 2
    let charAtIndex = someString[someString.index(someString.startIndex, offsetBy: 10)] // Swift 3
    let firstChar = input[input.startIndex]
    let lastChar = input[input.endIndex.predecessor()]

    // Length
    a.characters.count

    // Lowercase
    filteredString = filteredString.lowercaseString

    // Replace
    let aString: String = "This is my string"
    let filteredString = aString.stringByReplacingOccurrencesOfString(" ", withString: "+")
    let filteredString = aString.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)

    // String interpolation
    let multiplier = 3
    let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
    // message is "3 times 2.5 is 7.5"

    // Specify Numeric Precision
    print(String(format: "%.2f", 1.0321))

TableView

    // Table view
    let myTableView: UITableView = UITableView(frame: CGRect(x:0, y:0, width:0, height:0), style: .grouped)

Tuples

    let http404Error = (404, "Not Found")

Type Properties / Type Methods (like Class Methods)

    class func reset() {
        count = 0
    }

UIFont

UIFont.init(name:"Helvetica", size:12)!

UIView

    // Custom UIView subclass - required methods
    required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
      super.init(frame: frame)
      // customization
    }

    // Add a subview
    var dynamicView = UIView(frame: CGRect(x:0, y:0, width:0, height:0))
    dynamicView.backgroundColor = UIColor.greenColor()
    dynamicView.layer.cornerRadius = 25
    dynamicView.layer.borderWidth = 2
    self.view.addSubview(dynamicView)

itun

Unpack local variable

    if let genString = aString {
    }

    let someString = (genString != nil) ? "option 1" : "option 2"

Variables

    var hue : CGFloat = 0.0

Warnings

    // Suppress unused return value warnings
    _ = methodWithAReturnType()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment