abs(-4)
// 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])
self.customView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let input : Int = 3
let binaryString = String(input, radix: 2)
var genBool : Bool = (2 == 1) ? true : false
true
false
CGRect(x: 0, y: 0, width: 30, height: 30)
CGSize(width:1, height: 1)
// Comparison
for char in binaryString.characters
if char == "1" {
}
}
// Convert character to String
String(tmpChar)
//
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
//
/* Block comment */
// MARK: (similar to #pragma in Xcode)
let GENDefaultRegularFontName = "HelveticaNeue"
// Global Constant
static let FourInchPhoneScreenHeight = 568.0
// 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)
// 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 {
}
// Convert Int to Double
Double(tOne)
// Print (specify precision)
print(String(format: "%.2f", tmpD))
self.selectionStyle = UITableViewCellSelectionStyle.none
self.selectionStyle = .none
extension SomeType {
// new functionality to add to SomeType goes here
}
// Round down
floor(tmpFloat)
// Specify number of decimal places
print(String(format: "%.2f", 1.0321))
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
}
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 Foundation
// Import Swift files into Objective-C - import the Objective-C Generated Interface Header Name
#import "TargetName-Swift.h"
Int.min
// IBOutlet
class MyViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBOutlet var textFields: [UITextField]!
@IBAction func buttonTapped(AnyObject) {
println("button tapped!")
}
}
for char in "abcdefghijklmnopqrstuvwxyz".characters {
print(char)
}
// 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")
// May need to regenerate and rename Swift files to be prefixed with target name
// 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
NSNumber.init(float:3.1)
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 without line break (or with custom terminator)
print(" ", terminator:"")
//
print(tmpObject)
// Optional property
@IBOutlet var infoView : GENInfoView?
// Property initialized with value
var numberLabel = UILabel()
#selector(doCustomAction)
// 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)}
let numberOfChars = word.characters.count
let numberOfDistinctChars = Set(word.characters).count
// 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))
// Table view
let myTableView: UITableView = UITableView(frame: CGRect(x:0, y:0, width:0, height:0), style: .grouped)
let http404Error = (404, "Not Found")
class func reset() {
count = 0
}
UIFont.init(name:"Helvetica", size:12)!
// 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
if let genString = aString {
}
let someString = (genString != nil) ? "option 1" : "option 2"
var hue : CGFloat = 0.0
// Suppress unused return value warnings
_ = methodWithAReturnType()