Skip to content

Instantly share code, notes, and snippets.

@marinho
Last active August 29, 2015 14:12
Show Gist options
  • Save marinho/f964357a203be98247a6 to your computer and use it in GitHub Desktop.
Save marinho/f964357a203be98247a6 to your computer and use it in GitHub Desktop.
Playing with Swift
// Interesting pieces of code while I learn the language
import UIKit
func isPrime(number: Int) -> Bool {
let basicPrimes = [1,2,3,5,7,11,13,17,19]
let basicNonPrimes = [0,4,6,8,9,10,12,14,15,16,18,20]
if contains(basicPrimes, number) {
return true
} else if contains(basicNonPrimes, number) {
return false
}
for var i = 2; i < (number + 1) / 2; i++ {
if number % i == 0 {
return false;
}
}
return true;
}
func measure(title: String!, call: () -> Void) {
/*
Meassures the time spent to run a block of code.
Source: https://medium.com/swift-programming/secret-of-swift-performance-a8ee86060843
Example:
measure("New") {
var arr1: [Int] = []
for var i = 1; i < 100; i++ {
if isPrime(i) {
arr1.append(i)
}
}
}
*/
let startTime = CACurrentMediaTime()
call()
let endTime = CACurrentMediaTime()
if let title = title {
print("\(title): ")
}
println("Time - \(endTime - startTime)")
}
import Foundation
class File {
/*
A simple class to facilitate basic interactions with a text file.
Source: https://gist.github.com/frozzare/d4a9bbeb39e5425e7c26
Example:
let write: Bool = File.write("/tmp/mario.txt", content: "Mario here looking at Leticia")
let read: String? = File.read("/tmp/mario.txt")
*/
class func exists (path: String) -> Bool {
return NSFileManager().fileExistsAtPath(path)
}
class func read (path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
if File.exists(path) {
return String(contentsOfFile: path, encoding: encoding, error: nil)!
}
return nil
}
class func write (path: String, content: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
return content.writeToFile(path, atomically: true, encoding: encoding, error: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment