Skip to content

Instantly share code, notes, and snippets.

View scotteg's full-sized avatar
🏠
Working from home

Scott Gardner scotteg

🏠
Working from home
View GitHub Profile
@scotteg
scotteg / Address.swift
Last active August 29, 2015 14:22
Vends formatted address string for CLPlacemark or MKMapItem
struct Address {
static let zipPlus4RegEx = NSRegularExpression(pattern: "\\-\\d{4}", options: nil, error: nil)!
static func formattedAddressForPlacemark(placemark: CLPlacemark, includeName: Bool = true, withLineBreaks: Bool = true, showCountryIfUSA: Bool = false) -> String {
var addressArray = [String]()
var index = 0
if placemark.name != nil && includeName { addressArray.append(placemark.name) }
if placemark.subLocality != nil { addressArray.append(placemark.subLocality) } // Neighborhood
@scotteg
scotteg / XCTestOptional.swift
Created December 25, 2014 16:22
How to use XCTest in Swift with an optional
func testCopyingLists() {
if let listCopy = list.copy() as? List {
XCTAssertEqual(list, listCopy, "listCopy should be equal to list")
} else {
XCTFail("listCopy should not be nil")
}
}
@scotteg
scotteg / SwiftArrayMiddleExtension.swift
Last active July 22, 2022 21:41
A Swift extension that adds a middle() method to Array using generics
protocol HasMiddleValue {
typealias ItemType
func middle() -> [ItemType]
}
extension Array: HasMiddleValue {
typealias ItemType = Generator.Element
@scotteg
scotteg / classVariadicSubscriptExample
Last active August 29, 2015 14:06
Example of a Swift class subscript that takes a variadic parameter and returns a tuple
class Introspector {
var values: Any!
subscript(theValues: Int...) -> (sum: Int, average: Double) {
values = theValues
var sum = 0
for integer in theValues {
sum += integer
}
let average = Double(sum) / Double(theValues.count)
return (sum: sum, average: average)
@scotteg
scotteg / printOutSumOfNumber:andNumber:withFormatter:
Last active August 29, 2015 14:06
Example of a Swift function that takes a function as a parameter, nests functions, and returns a function
func formatNumberAsSpelledOutString(number: Any) -> String {
var numberString: String!
let spellOutFormatter = NSNumberFormatter()
spellOutFormatter.numberStyle = .SpellOutStyle
if number is Int {
let num = number as Int
numberString = spellOutFormatter.stringFromNumber(num)
} else if number is Double {
spellOutFormatter.minimumFractionDigits = 1
let num = number as Double
@scotteg
scotteg / prepareForSegue:sender:_ObjCvsSwift
Last active November 4, 2016 06:28
Example of iOS -prepareForSegue:sender: in Objective-C and Swift
// Objective-C
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Item Detail"]) {
DetailViewController *d = (DetailViewController *)segue.destinationViewController;
d.title = segue.identifier;
d.itemForDetail = item;
} else if ([segue.identifier isEqualToString:@"Related Items"]) {
UINavigationController *nc = segue.destinationViewController;