swift 迅捷的阶乘

迅捷的阶乘

gistfile1.swift
// Simple factorial generator. Doesn't handle numbers that overflow Int or the 0! = 1 case.

// Swift 2
let num = (1...17).reduce(1, combine: *) // 355687428096000

// Swift 1.x
let num = reduce(1...17, 1, *) // 355687428096000

swift 获取Swift中某些用户的推文

获取Swift中某些用户的推文

gistfile1.swift
let username = "myHandle" // Put Twitter handle without @ here.

let accountStore = ACAccountStore()
let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)

accountStore.requestAccessToAccountsWithType(accountType, options: nil) { granted, error in
    if granted == true {
        if let account = accountStore.accountsWithAccountType(accountType).first as? ACAccount {
            
            let finalURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + username + "&count=100"
            let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: finalURL)!, parameters: nil)
            
            request.account = account
            request.performRequestWithHandler { data, response, requestError in
                var parseError: NSError?
                if let parsedData = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: &parseError) as? [AnyObject] {
                    println(parsedData)
                } else {
                    // coundn't parse JSON.
                }
            }
        } else {
            // couldn't get logged in user
        }
    } else {
        // user wasn't logged in.
    }
}

swift 设置UIRefreshControl

设置UIRefreshControl

ViewController.swift
lazy var refreshControl: UIRefreshControl = {
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
    
    return refreshControl
}()

@objc func handleRefresh() {
  
}

swift ActionSheet.swift

ActionSheet.swift
import UIKit

typealias SheetAction = () -> Void

class ActionSheet: UIActionSheet {
    private var actions = [SheetAction]()

    convenience init() {
        self.init(frame: CGRectZero)
        delegate = self
    }

    override func addButtonWithTitle(title: String) -> Int {
        return addButtonWithTitle(title) {}
    }

    func addButtonWithTitle(title: String, action: SheetAction) -> Int {
        let index = super.addButtonWithTitle(title)
        actions.insert(action, atIndex: index)
        return index
    }
}

extension ActionSheet: UIActionSheetDelegate {
    func actionSheet(_: UIActionSheet, clickedButtonAtIndex index: Int) {
        // Check for the case of tapping outside an action sheet on iPad
        if index < actions.count {
            actions[index]()
        }
    }
}

swift Swift中的SHA1摘要

Swift中的SHA1摘要

Digest.swift
import Foundation

func sha1(data: NSData) -> String {
    let length = Int(CC_SHA1_DIGEST_LENGTH)
    var digest = [UInt8](count: length, repeatedValue: 0)
    CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
    return digest.map { String(format: "%02x", $0) }.reduce("", +)
}

func sha1(string: String) -> String? {
    return string.dataUsingEncoding(NSUTF8StringEncoding).map(sha1)
}

swift 通知の登录を简単にする扩展名参考:http://qiita.com/mono0926/items/e3a76dc95046f0eeeb29

通知の登录を简単にする扩展名参考:http://qiita.com/mono0926/items/e3a76dc95046f0eeeb29

file1.swift
// ViewControllerのappear系で登録
removeObserverClosure = observeDidBecomeActive("didBecomeActive:")

// ViewControllerのdisappear系で登録解除
removeObserverClosure()
file0.swift
extension UIViewController {
    // こんな感じの公開メソッドを増やしていく
    func observeKeyboard(willShowSelector: Selector, willHideSelector: Selector) -> () -> () {
        return observeNotification([
            (action: willShowSelector, name: UIKeyboardWillShowNotification),
            (action: willHideSelector, name: UIKeyboardWillHideNotification)])
    }
    func observeDidBecomeActive(action: Selector) -> () -> () {
        return observeNotification(action, name: UIApplicationDidBecomeActiveNotification)
    }

    // あるいはこちらを公開して直に使っちゃっても良いかも
    private func observeNotification(action: Selector, name: String) -> () -> () {
        return observeNotification([(action: action, name: name)])
    }
    private func observeNotification(pairs: [(action: Selector, name: String)]) -> () -> () {
        for p in pairs {
            NSNotificationCenter.defaultCenter().addObserver(self, selector: p.action, name: p.name, object: nil)
        }
        return { [unowned self] in // これ忘れるとメモリリークするので注意
            for p in pairs {
                return NSNotificationCenter.defaultCenter().removeObserver(self, name: p.name, object: nil)
            }
        }
    }
}

swift 注册并删除通知

注册并删除通知

gistfile1.swift
// extension
extension UIViewController {
    func observeDidBecomeActive(action: Selector) -> () -> () {
        return observeNotification(action, name: UIApplicationDidBecomeActiveNotification)
    }
    private func observeNotification(action: Selector, name: String) -> () -> () {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: action, name: name, object: nil)
        return {
            return NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: nil)
        }
    }
}
    
// 登録
let removeObserverClosure = observeDidBecomeActive("didBecomeActive")
    
// どこかで解除
removeObserverClosure()

swift gistfile1.m

gistfile1.m
ORSSerialRequest *request = 
    [ORSSerialRequest requestWithDataToSend:requestData
                                   userInfo:nil
                            timeoutInterval:2.0
                          responseEvaluator:^BOOL(NSData *inputData) {
                              if ([inputData length] != 8) return NO;
                              NSData *headerData = [inputData subdataWithRange:NSMakeRange(0, 4)];
                              NSString *header = [[NSString alloc] initWithData:headerData encoding:NSASCIIStringEncoding];
                              return [header isEqualToString:@"data"];
                          }];
gistfile2.swift
let request = ORSSerialRequest(dataToSend: NSData!, userInfo: nil, timeoutInterval: 2.0, 
    responseEvaluator: (inputData: NSData!) in { return true})

swift iOS设备在Swift中检查操作系统版本和屏幕大小

iOS设备在Swift中检查操作系统版本和屏幕大小

Device.swift
//
//  Device.swift
//  imHome
//
//  Created by Kevin Xu on 2/9/15. Updated on 6/20/15.
//  Copyright (c) 2015 Alpha Labs, Inc. All rights reserved.
//

import Foundation

// MARK: - Device Structure

struct Device {

    // MARK: - Singletons

    static var TheCurrentDevice: UIDevice {
        struct Singleton {
            static let device = UIDevice.currentDevice()
        }
        return Singleton.device
    }

    static var TheCurrentDeviceVersion: Float {
        struct Singleton {
            static let version = UIDevice.currentDevice().systemVersion.floatValue
        }
        return Singleton.version
    }

    static var TheCurrentDeviceHeight: CGFloat {
        struct Singleton {
            static let height = UIScreen.mainScreen().bounds.size.height
        }
        return Singleton.height
    }

    // MARK: - Device Idiom Checks

    static var PHONE_OR_PAD: String {
        if isPhone() {
            return "iPhone"
        } else if isPad() {
            return "iPad"
        }
        return "Not iPhone nor iPad"
    }

    static var DEBUG_OR_RELEASE: String {
        #if DEBUG
            return "Debug"
        #else
            return "Release"
        #endif
    }

    static var SIMULATOR_OR_DEVICE: String {
        #if (arch(i386) || arch(x86_64)) && os(iOS)
            return "Simulator"
        #else
            return "Device"
        #endif
    }

    static var CURRENT_DEVICE: String {
        return GBDeviceInfo.deviceInfo().modelString
    }

    static func isPhone() -> Bool {
        return TheCurrentDevice.userInterfaceIdiom == .Phone
    }

    static func isPad() -> Bool {
        return TheCurrentDevice.userInterfaceIdiom == .Pad
    }

    static func isDebug() -> Bool {
        return DEBUG_OR_RELEASE == "Debug"
    }

    static func isRelease() -> Bool {
        return DEBUG_OR_RELEASE == "Release"
    }

    static func isSimulator() -> Bool {
        return SIMULATOR_OR_DEVICE == "Simulator"
    }

    static func isDevice() -> Bool {
        return SIMULATOR_OR_DEVICE == "Device"
    }

    // MARK: - Device Version Checks

    enum Versions: Float {
        case Five = 5.0
        case Six = 6.0
        case Seven = 7.0
        case Eight = 8.0
        case Nine = 9.0
    }

    static func isVersion(version: Versions) -> Bool {
        return TheCurrentDeviceVersion >= version.rawValue && TheCurrentDeviceVersion < (version.rawValue + 1.0)
    }

    static func isVersionOrLater(version: Versions) -> Bool {
        return TheCurrentDeviceVersion >= version.rawValue
    }

    static func isVersionOrEarlier(version: Versions) -> Bool {
        return TheCurrentDeviceVersion < (version.rawValue + 1.0)
    }

    static var CURRENT_VERSION: String {
        return "\(TheCurrentDeviceVersion)"
    }

    // MARK: iOS 5 Checks

    static func IS_OS_5() -> Bool {
        return isVersion(.Five)
    }

    static func IS_OS_5_OR_LATER() -> Bool {
        return isVersionOrLater(.Five)
    }

    static func IS_OS_5_OR_EARLIER() -> Bool {
        return isVersionOrEarlier(.Five)
    }

    // MARK: iOS 6 Checks

    static func IS_OS_6() -> Bool {
        return isVersion(.Six)
    }

    static func IS_OS_6_OR_LATER() -> Bool {
        return isVersionOrLater(.Six)
    }

    static func IS_OS_6_OR_EARLIER() -> Bool {
        return isVersionOrEarlier(.Six)
    }

    // MARK: iOS 7 Checks

    static func IS_OS_7() -> Bool {
        return isVersion(.Seven)
    }

    static func IS_OS_7_OR_LATER() -> Bool {
        return isVersionOrLater(.Seven)
    }

    static func IS_OS_7_OR_EARLIER() -> Bool {
        return isVersionOrEarlier(.Seven)
    }

    // MARK: iOS 8 Checks

    static func IS_OS_8() -> Bool {
        return isVersion(.Eight)
    }

    static func IS_OS_8_OR_LATER() -> Bool {
        return isVersionOrLater(.Eight)
    }

    static func IS_OS_8_OR_EARLIER() -> Bool {
        return isVersionOrEarlier(.Eight)
    }

    // MARK: iOS 9 Checks

    static func IS_OS_9() -> Bool {
        return isVersion(.Nine)
    }

    static func IS_OS_9_OR_LATER() -> Bool {
        return isVersionOrLater(.Nine)
    }

    static func IS_OS_9_OR_EARLIER() -> Bool {
        return isVersionOrEarlier(.Nine)
    }

    // MARK: - Device Size Checks

    enum Heights: CGFloat {
        case Inches_3_5 = 480
        case Inches_4 = 568
        case Inches_4_7 = 667
        case Inches_5_5 = 736
    }

    static func isSize(height: Heights) -> Bool {
        return TheCurrentDeviceHeight == height.rawValue
    }

    static func isSizeOrLarger(height: Heights) -> Bool {
        return TheCurrentDeviceHeight >= height.rawValue
    }

    static func isSizeOrSmaller(height: Heights) -> Bool {
        return TheCurrentDeviceHeight <= height.rawValue
    }

    static var CURRENT_SIZE: String {
        if IS_3_5_INCHES() {
            return "3.5 Inches"
        } else if IS_4_INCHES() {
            return "4 Inches"
        } else if IS_4_7_INCHES() {
            return "4.7 Inches"
        } else if IS_5_5_INCHES() {
            return "5.5 Inches"
        }
        return "\(TheCurrentDeviceHeight) Points"
    }

    // MARK: Retina Check

    static func IS_RETINA() -> Bool {
        return UIScreen.mainScreen().respondsToSelector("scale")
    }

    // MARK: 3.5 Inch Checks

    static func IS_3_5_INCHES() -> Bool {
        return isPhone() && isSize(.Inches_3_5)
    }

    static func IS_3_5_INCHES_OR_LARGER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_3_5)
    }

    static func IS_3_5_INCHES_OR_SMALLER() -> Bool {
        return isPhone() && isSizeOrSmaller(.Inches_3_5)
    }

    // MARK: 4 Inch Checks

    static func IS_4_INCHES() -> Bool {
        return isPhone() && isSize(.Inches_4)
    }

    static func IS_4_INCHES_OR_LARGER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_4)
    }

    static func IS_4_INCHES_OR_SMALLER() -> Bool {
        return isPhone() && isSizeOrSmaller(.Inches_4)
    }

    // MARK: 4.7 Inch Checks

    static func IS_4_7_INCHES() -> Bool {
        return isPhone() && isSize(.Inches_4_7)
    }

    static func IS_4_7_INCHES_OR_LARGER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_4_7)
    }

    static func IS_4_7_INCHES_OR_SMALLER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_4_7)
    }

    // MARK: 5.5 Inch Checks

    static func IS_5_5_INCHES() -> Bool {
        return isPhone() && isSize(.Inches_5_5)
    }

    static func IS_5_5_INCHES_OR_LARGER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_5_5)
    }

    static func IS_5_5_INCHES_OR_SMALLER() -> Bool {
        return isPhone() && isSizeOrLarger(.Inches_5_5)
    }

    // MARK: - International Checks

    static var CURRENT_REGION: String {
        return NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
    }
}

swift 使用func logln()显示日志

使用func logln()显示日志

LoggingTextView.swift
// The MIT License (MIT)
//
// Copyright (c) 2015 James Tang (j@jamztang.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//
// Description:
// LoggingTextView and logln() is a println() replacement to display logs on screen
// Suitable to debug stuffs when the debugger cannot be attached in some situation
//
// Usage:
// Subclass any UITextView to LoggingTextView, and replace your println() to logln()
// Now all logs will go through that text view.
//

import UIKit

let LogNotification = "LogNotification"

public func logln(any: AnyObject) {
    NSNotificationCenter.defaultCenter().postNotificationName(LogNotification, object: any, userInfo: nil)
    println(any)
}

public class LoggingTextView: UITextView {

    override public func awakeFromNib() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "logNotification:", name: LogNotification, object: nil)
    }

    func logNotification(notification: NSNotification) {

        if let object: AnyObject = notification.object {
            self.text = "\(self.text)\n\(object)"
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}