repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zadr/conservatory
|
Code/Internal/Random/Seeding.swift
|
1
|
1369
|
#if os(iOS) || os(OSX)
import Darwin
#else
import Glibc
#endif
internal struct Seed {
#if os(iOS) || os(OSX)
fileprivate static var bootTime: UInt {
var bootTime = timeval()
var mib = [ CTL_KERN, KERN_BOOTTIME ]
var size = MemoryLayout<timeval>.stride
sysctl(&mib, u_int(mib.count), &bootTime, &size, nil, 0)
return UInt(bootTime.tv_sec) + UInt(bootTime.tv_usec)
}
fileprivate static var CPUTime: UInt {
return 0
}
internal static func generate() -> [UInt] {
// todo: add in thread time, cpu time, cpu load, processor load, memory usage
return [
UInt(mach_absolute_time()),
bootTime,
// threadTime,
// CPUTime,
UInt(getpid()),
UInt(time(nil)),
UInt(pthread_mach_thread_np(pthread_self()))
]
}
#elseif os(Linux)
internal static func generate() -> [UInt] {
let seeds = [
UInt(getpid()),
UInt(time(nil)),
UInt(pthread_mach_thread_np(pthread_self()))
]
// todo: add in processor load, memory usage
let ids = [ CLOCK_MONOTONIC_RAW, CLOCK_BOOTTIME,
CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID ]
return ids.map { return clock($0) } + seeds
}
private static func clock(id: clockid_t) -> UInt {
var ts: timespec = timespec()
return withUnsafeMutablePointer(&ts) { (time) -> UInt in
clock_gettime(id, time)
return UInt(time.memory.tv_sec) + UInt(time.memory.tv_nsec)
}
}
#endif
}
|
bsd-2-clause
|
8ec07b4e132e2a784b1a9e98a9a2cf69
| 22.603448 | 79 | 0.658875 | 2.799591 | false | false | false | false |
emilstahl/swift
|
test/decl/protocol/req/associated_type_default.swift
|
10
|
720
|
// RUN: %target-parse-verify-swift
struct X { }
// Simple default definition for associated types.
protocol P1 {
typealias AssocType1 = Int
}
extension X : P1 { }
var i: X.AssocType1 = 17
// Dependent default definition for associated types
protocol P2 {
typealias AssocType2 = Self
}
extension X : P2 { }
var xAssoc2: X.AssocType2 = X()
// Dependent default definition for associated types that doesn't meet
// requirements.
protocol P3 {
typealias AssocType3 : P1 = Self // expected-note{{default type 'X2' for associated type 'AssocType3' (from protocol 'P3') does not conform to 'P1'}}
}
extension X : P3 { } // okay
struct X2 : P3 { } // expected-error{{type 'X2' does not conform to protocol 'P3'}}
|
apache-2.0
|
7b9cba4876615d863e6500435f4fedcf
| 23 | 151 | 0.701389 | 3.412322 | false | false | false | false |
zzxuxu/TestKitchen
|
TestKitchen/TestKitchen/Classes/Ingredient/main/controller/IngredientViewController.swift
|
1
|
8292
|
//
// IngredientViewController.swift
// TestKitchen
//
// Created by 王健旭 on 2016/10/21.
// Copyright © 2016年 王健旭. All rights reserved.
//
import UIKit
class IngredientViewController: BaseViewController {
//滚动视图
private var scrollView: UIScrollView?
//推荐视图
private var recommendView: IngreRecommendView?
//食材视图
private var materiaView: IngreMaterrialView?
//分类视图
private var categoryView: IngreMaterrialView?
//导航上面的选择控件
private var segCtrl:KTCSegCtrl?
override func viewDidLoad() {
super.viewDidLoad()
// view.backgroundColor = UIColor.yellowColor()
//滚动视图或者子视图放在导航下面会自动加一个上面的间距,我们要取消这个间距
automaticallyAdjustsScrollViewInsets = false
//导航
createNav()
//创建首页视图
createHomePage()
//下载首页的推荐数据
downloadRecommendData()
//下载首页食材数据
downLoadRecommendMaterial()
//下载首页分类数据
downLoadCategoryData()
}
//下载首页分类数据
func downLoadCategoryData() {
//methodName=CategoryIndex
let dict = ["methodName":"CategoryIndex"]
let downloader = KTCDownload()
downloader.delegate = self
downloader.downloadType = KTCDownloadType.IngreCategory
downloader.postWithUrl(kHostUrl, params: dict)
}
//下载首页食材数据
func downLoadRecommendMaterial() {
//methodName=MaterialSubtype&token=&user_id=&version=4.32
let dict = ["methodName":"MaterialSubtype"]
let downloader = KTCDownload()
downloader.delegate = self
downloader.downloadType = KTCDownloadType.IngreMaterial
downloader.postWithUrl(kHostUrl, params: dict)
}
//创建首页视图
func createHomePage() {
scrollView = UIScrollView()
scrollView!.pagingEnabled = true
scrollView?.delegate = self
view.addSubview(scrollView!)
scrollView!.snp_makeConstraints { (make) in
make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
//容器视图
let containerView = UIView.createView()
scrollView!.addSubview(containerView)
containerView.snp_makeConstraints { (make) in
make.edges.equalTo(scrollView!)
make.height.equalTo(scrollView!)
}
//上一次的子视图
// let lastView: UIView? = nil
//添加子视图
//1.推荐视图
recommendView = IngreRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.left.equalTo(containerView)
make.width.equalTo(kScreenW)
})
//2.食材视图
materiaView = IngreMaterrialView()
materiaView?.backgroundColor = UIColor.blueColor()
containerView.addSubview(materiaView!)
materiaView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenW)
make.left.equalTo((recommendView?.snp_right)!)
})
//3.分类视图
categoryView = IngreMaterrialView()
categoryView?.backgroundColor = UIColor.redColor()
containerView.addSubview(categoryView!)
categoryView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenW)
make.left.equalTo((materiaView?.snp_right)!)
})
//修改容器视图的大小
containerView.snp_makeConstraints { (make) in
make.right.equalTo(categoryView!)
}
}
//创建导航
func createNav() {
//扫一扫
addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true)
//搜索
addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false)
//选择控件
let frame = CGRectMake(80, 0, kScreenW-80*2, 44)
segCtrl = KTCSegCtrl(frame: frame, titleArray: ["推荐","食材","分类"])
segCtrl!.delegate = self
navigationItem.titleView = segCtrl
}
//扫一扫
func scanAction() {
print("扫一扫")
}
//搜索
func searchAction() {
print("搜索")
}
//下载首页的推荐数据
func downloadRecommendData(){
//methodName=SceneHome&token=&user_id=&version=4.5
let params = ["methodName":"SceneHome"]
let downloader = KTCDownload()
downloader.delegate = self
downloader.downloadType = .IngreRecommend
downloader.postWithUrl(kHostUrl, params: params)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK:KTCDownloader代理方法
extension IngredientViewController:KTCDownloadDelegate {
//下载失败
func downloader(downloader: KTCDownload, didFailWithError error: NSError) {
print(error)
}
//下载成功
func downloader(downloader: KTCDownload, didFinishWithData data: NSData?) {
if downloader.downloadType == KTCDownloadType.IngreRecommend {
//推荐
if let tmpData = data {
//1.json解析
let recommendModel = IngreRecommend.parseData(tmpData)
//2.显示UI
// let recommendView = IngreRecommendView(frame: CGRectZero)
recommendView!.model = recommendModel
// view.addSubview(recommendView)
//3.点击食材的推荐页面的某一部分,跳转到后面的界面
recommendView!.jumpClosure = {[weak self] jumpUrl in
self?.handleClickEvent(jumpUrl)
}
}
}else if downloader.downloadType == KTCDownloadType.IngreMaterial {
//食材
if let tmpData = data {
//1.json解析
let materialModel = IngreMaterial.parseData(tmpData)
//2.显示UI
// let recommendView = IngreRecommendView(frame: CGRectZero)
materiaView!.model = materialModel
// view.addSubview(recommendView)
//点击事件
materiaView!.jumpClosure = {[weak self] jumpUrl in
self?.handleClickEvent(jumpUrl)
}
}
}else if downloader.downloadType == KTCDownloadType.IngreCategory {
//分类
if let tmpData = data {
//1.json解析
let categoryModel = IngreMaterial.parseData(tmpData)
//2.显示UI
// let recommendView = IngreRecommendView(frame: CGRectZero)
categoryView!.model = categoryModel
// view.addSubview(recommendView)
//点击事件
categoryView!.jumpClosure = {[weak self] jumpUrl in
self?.handleClickEvent(jumpUrl)
}
}
}
//约束
// recommendView.snp_makeConstraints(closure: { (make) in
// make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
// })
}
//处理点击事件的方法
func handleClickEvent(urlString:String) {
IngreService.handleEvent(urlString, onViewController: self)
}
}
//MARK: KTCSegCtrl代理
extension IngredientViewController:KTCSegCtrlDelegate {
func segCtrl(segCtrl: KTCSegCtrl, didClickBtnAtIndex index: Int) {
scrollView?.setContentOffset(CGPointMake(CGFloat(index)*kScreenW, 0), animated: true)
}
}
//MARK:UIScrollView的代理
extension IngredientViewController:UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = scrollView.contentOffset.x/scrollView.bounds.width
segCtrl?.selectIndex = Int(index)
}
}
|
mit
|
18e5b358a136310d461583ca05a7019d
| 25.785467 | 93 | 0.599147 | 4.697209 | false | false | false | false |
banxi1988/Staff
|
Staff/AppAppearance.swift
|
1
|
3519
|
import Foundation
import UIKit
import BXiOSUtils
struct AppMetrics{
static let cornerRadius : CGFloat = 4.0
static let iconPadding : CGFloat = 8.0
static let seperatorLineWidth :CGFloat = 0.5
}
// 相关主题颜色的命名,参考 Material Design 以便开发统一
struct AppColors{
static let seperatorLineColor = UIColor(hex: 0xe8e8e8) // UIColor(white: 0.914, alpha: 1.0) // 0.914 white
static let primaryTextColor = UIColor(hex:0xb9b0aa) // .08627451 white
static let secondaryTextColor = UIColor(hex:0xa6acb4) // .08627451 white
static let tertiaryTextColor = UIColor(hex:0x808994) //
static let hintTextColor = UIColor(hex:0xccc3c8) // .509803922 white
static let colorPrimary = UIColor(hex:0x3b4047)// 0x454950 // v2.5 :01c5b7 v2.0: 00aca0
static let accentColor = UIColor(hex:0xffd54d)
static let colorPrimaryDark = UIColor(hex:0x3b4047)
static let grayColor = UIColor(hex: 0xcccccc)
static let darkGrayTextColor = UIColor(hex: 0x868686)
static let tintColor = UIColor(hex: 0xb9b0aa)
static let colorPrimaryLight = UIColor(hex:0xfa5555)
static let redColor = UIColor(hex:0xf04a4a)
static let colorBackground = UIColor(hex: 0x3b4047)
static let orangeColor = UIColor(hex: 0xffb359)
}
extension AppDelegate{
func setUpAppearanceProxy(){
let colorPrimary = AppColors.colorPrimary
let app = UIApplication.sharedApplication()
self.window?.tintColor = AppColors.tintColor
app.statusBarStyle = .LightContent
setUpNavigationBarAppearance()
setUpSearchBarAppearance()
setUpTextFieldAppearance()
setUpBarButtonItemAppearance()
// setupZjdjLibAppApperance()
}
private func setUpNavigationBarAppearance(){
let nap = UINavigationBar.appearance()
nap.barStyle = UIBarStyle.Default
nap.tintColor = AppColors.tintColor
nap.barTintColor = AppColors.colorPrimary
nap.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
nap.backIndicatorImage = UIImage(named: "ic_arrow_left")
let navBg = UIImage.bx_image(AppColors.colorPrimary) //UIImage.imageWithColor(AppColors.colorPrimary)
nap.setBackgroundImage(navBg, forBarPosition:.Any, barMetrics: .Default)
nap.shadowImage = navBg
}
private func setUpSearchBarAppearance(){
let sbap = UISearchBar.appearance()
sbap.translucent = false
sbap.barStyle = .Default
sbap.barTintColor = AppColors.tintColor
let sbbg = UIImage.bx_image(.whiteColor(), size: CGSize(width: 320, height: 44))
sbap.setBackgroundImage(sbbg, forBarPosition: .Any, barMetrics: .Default)
let sfbg = UIImage.bx_roundImage(UIColor(hex: 0xefeff4), size: CGSize(width: 320, height: 33), cornerRadius: 4)
sbap.setSearchFieldBackgroundImage(sfbg, forState: .Normal)
}
private func setUpTextFieldAppearance(){
let teap = UITextField.appearance()
teap.borderStyle = .None
teap.keyboardAppearance = .Light
}
private func setUpBarButtonItemAppearance(){
let bap = UIBarButtonItem.appearance()
bap.tintColor = AppColors.tintColor
let attrs = [NSFontAttributeName:UIFont.systemFontOfSize(17)]
bap.setTitleTextAttributes(attrs, forState: .Normal)
// 隐藏 backbutton 中的 title
bap.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -64), forBarMetrics: .Default)
}
}
func themedBackgroundView() -> UIView{
let view = UIView(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
view.backgroundColor = AppColors.colorPrimary
return view
}
|
mit
|
e283b257aedb2be9a69f8ef8e015efd1
| 35.6 | 115 | 0.742594 | 3.919955 | false | false | false | false |
coderZsq/coderZsq.target.swift
|
StudyNotes/iOS Collection/Business/Business/Audio/AudioViewController.swift
|
1
|
5341
|
//
// AudioViewController.swift
// Business
//
// Created by 朱双泉 on 2018/11/13.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
import AVFoundation
class AudioViewController: UIViewController {
@IBAction func music(_ sender: UIButton) {
if let vc = UIStoryboard(name: "ListViewController", bundle: nil).instantiateInitialViewController() {
navigationController?.pushViewController(vc, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Audio"
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try session.setActive(true, options: AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation)
} catch {
print(error)
return
}
}
var recoder: AVAudioRecorder?
var path: String?
@IBAction func startRecoding(_ sender: UIButton) {
if let url = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first {
let fullPath = url + "/test.caf"
path = fullPath
guard let fullURL = URL(string: fullPath) else {return}
let settings = [
//编码格式
AVFormatIDKey : NSNumber(integerLiteral: Int(kAudioFormatLinearPCM)),
//采样率
AVSampleRateKey : NSNumber(floatLiteral: 11025.0),
//通道数
AVNumberOfChannelsKey : NSNumber(integerLiteral: 2),
//录音质量
AVEncoderAudioQualityKey : NSNumber(integerLiteral: Int(AVAudioQuality.min.rawValue))
]
do {
recoder = try AVAudioRecorder(url: fullURL, settings: settings)
} catch {
print("错误")
return
}
if let recoder = recoder {
recoder.prepareToRecord()
recoder.record()
print(fullPath)
// recoder.record(atTime: recoder.deviceCurrentTime + 2)
// recoder.record(atTime: recoder.deviceCurrentTime + 2, forDuration: 3)
// recoder.record(forDuration: 5)
}
}
}
@IBAction func stopRecoding(_ sender: UIButton) {
guard let recoder = recoder else {
return
}
if recoder.currentTime < 2 {
print("录音时间太短")
recoder.stop()
// recoder.deleteRecording()
} else {
print("录音成功")
recoder.stop()
if let path = path {
lameTool.audio(toMP3: path, isDeleteSourchFile: false)
}
}
}
@IBAction func playAudio(_ sender: UIButton) {
if let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first {
AudioTool.playAudio(path: path + "/test.caf", isAlert: true) {
print("播放完成")
}
}
}
lazy var audioPlayer: AVAudioPlayer? = {
guard let url = Bundle.main.url(forResource: "老李.mp3", withExtension: nil) else {return nil}
do {
let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.enableRate = true //开始速率播放的开关必须放到准备播放之前
audioPlayer.prepareToPlay()
return audioPlayer
} catch {
print(error)
return nil
}
}()
@IBAction func playMusic(_ sender: UIButton) {
audioPlayer?.delegate = self
audioPlayer?.play()
}
@IBAction func pauseMusic(_ sender: UIButton) {
audioPlayer?.pause()
}
@IBAction func stopMusic(_ sender: UIButton) {
audioPlayer?.currentTime = 0
audioPlayer?.stop()
}
@IBAction func forward5s(_ sender: UIButton) {
audioPlayer?.currentTime += 5
}
@IBAction func rewind5s(_ sender: UIButton) {
audioPlayer?.currentTime -= 5 //系统做了容错处理
}
@IBAction func play2x(_ sender: UIButton) {
audioPlayer?.rate = 2.0
}
lazy var player: AVPlayer? = {
if let url = Bundle.main.url(forResource: "老李.mp3", withExtension: nil) {
// let player = AVPlayer(url: url)
let playItem = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: playItem)
return player
}
return nil
}()
@IBAction func remotePlay(_ sender: UIButton) {
player?.play()
// player?.replaceCurrentItem(with: <#T##AVPlayerItem?#>)
}
@IBAction func volumn(_ sender: UISlider) {
audioPlayer?.volume = sender.value
}
}
extension AudioViewController: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("播放完成")
}
}
|
mit
|
809f07c370786040425b8de2df16019f
| 31.72956 | 171 | 0.573597 | 5.008662 | false | false | false | false |
tgsala/HackingWithSwift
|
project09/project09/AppDelegate.swift
|
2
|
3748
|
//
// AppDelegate.swift
// project07
//
// Created by g5 on 3/8/16.
// Copyright © 2016 tgsala. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let tabBarController = splitViewController.viewControllers[0] as! UITabBarController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .TopRated, tag: 1)
tabBarController.viewControllers?.append(vc)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
unlicense
|
567d3148c16cabbb71d5ec9c8d40a187
| 52.528571 | 285 | 0.755538 | 6.183168 | false | false | false | false |
knehez/edx-app-ios
|
Source/LoadStateViewController.swift
|
2
|
6739
|
//
// LoadStateViewController.swift
// edX
//
// Created by Akiva Leffert on 5/13/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
enum LoadState {
case Initial
case Loaded
case Empty(icon : Icon, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?)
// if attributed message is set then message is ignored
// if message is set then the error is ignored
case Failed(error : NSError?, icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?)
var accessibilityMessage : String? {
switch self {
case Initial: return nil
case Loaded: return nil
case let Empty(info): return info.accessibilityMessage
case let Failed(info): return info.accessibilityMessage
}
}
var isInitial : Bool {
switch self {
case .Initial: return true
default: return false
}
}
var isLoaded : Bool {
switch self {
case .Loaded: return true
default: return false
}
}
var isError : Bool {
switch self {
case .Failed(_): return true
default: return false
}
}
static func failed(error : NSError? = nil, icon : Icon? = nil, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil) -> LoadState {
return LoadState.Failed(error : error, icon : icon, message : message, attributedMessage : attributedMessage, accessibilityMessage : accessibilityMessage)
}
static func empty(#icon : Icon, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil) -> LoadState {
return LoadState.Empty(icon: icon, message: message, attributedMessage: attributedMessage, accessibilityMessage : accessibilityMessage)
}
}
class LoadStateViewController : UIViewController, OEXStatusMessageControlling {
private let loadingView : UIView
private var contentView : UIView?
private let messageView : IconMessageView
private var madeInitialAppearance : Bool = false
var state : LoadState = .Initial {
didSet {
updateAppearanceAnimated(madeInitialAppearance)
}
}
var insets : UIEdgeInsets = UIEdgeInsetsZero {
didSet {
self.view.setNeedsUpdateConstraints()
}
}
init(styles : OEXStyles?) {
messageView = IconMessageView(styles: styles)
loadingView = SpinnerView(size: .Large, color: .Primary)
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var messageStyle : OEXTextStyle {
return messageView.messageStyle
}
func setupInController(controller : UIViewController, contentView : UIView) {
controller.addChildViewController(self)
didMoveToParentViewController(controller)
self.contentView = contentView
contentView.alpha = 0
controller.view.addSubview(loadingView)
controller.view.addSubview(messageView)
controller.view.addSubview(self.view)
}
override func viewDidLoad() {
super.viewDidLoad()
messageView.alpha = 0
view.addSubview(messageView)
view.addSubview(loadingView)
state = .Initial
self.view.setNeedsUpdateConstraints()
self.view.userInteractionEnabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
madeInitialAppearance = true
}
override func updateViewConstraints() {
loadingView.snp_updateConstraints {make in
make.center.equalTo(view)
}
messageView.snp_updateConstraints {make in
make.center.equalTo(view)
}
view.snp_updateConstraints { make in
if let superview = view.superview {
make.edges.equalTo(superview).insets(insets)
}
}
super.updateViewConstraints()
}
private func updateAppearanceAnimated(animated : Bool) {
var alphas : (loading : CGFloat, message : CGFloat, content : CGFloat) = (loading : 0, message : 0, content : 0)
UIView.animateWithDuration(0.3 * NSTimeInterval(animated)) {
switch self.state {
case .Initial:
alphas = (loading : 1, message : 0, content : 0)
case .Loaded:
alphas = (loading : 0, message : 0, content : 1)
case let .Empty(info):
UIView.performWithoutAnimation {
if let message = info.attributedMessage {
self.messageView.attributedMessage = message
}
else {
self.messageView.message = info.message
}
self.messageView.icon = info.icon
}
alphas = (loading : 0, message : 1, content : 0)
case let .Failed(info):
UIView.performWithoutAnimation {
if let error = info.error where error.oex_isNoInternetConnectionError() {
self.messageView.showNoConnectionError()
}
else {
if let message = info.attributedMessage {
self.messageView.attributedMessage = message
}
else {
self.messageView.message = info.message ?? info.error?.localizedDescription
}
self.messageView.icon = info.icon ?? .UnknownError
}
}
alphas = (loading : 0, message : 1, content : 0)
}
self.messageView.accessibilityMessage = self.state.accessibilityMessage
self.loadingView.alpha = alphas.loading
self.messageView.alpha = alphas.message
self.contentView?.alpha = alphas.content
}
}
func overlayViewsForStatusController(controller: OEXStatusMessageViewController!) -> [AnyObject]! {
return []
}
func verticalOffsetForStatusController(controller: OEXStatusMessageViewController!) -> CGFloat {
return 0
}
func showOverlayError(message : String) {
OEXStatusMessageViewController.sharedInstance().showMessage(message, onViewController: self)
}
}
|
apache-2.0
|
6ffe412338317e9eee204197824561a1
| 33.213198 | 191 | 0.59267 | 5.528302 | false | false | false | false |
srn214/Floral
|
Floral/Pods/SwiftDate/Sources/SwiftDate/Date/Date.swift
|
2
|
5789
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
#if os(Linux)
#else
internal enum AssociatedKeys: String {
case customDateFormatter = "SwiftDate.CustomDateFormatter"
}
#endif
extension Date: DateRepresentable {
/// Just return itself to be compliant with `DateRepresentable` protocol.
public var date: Date { return self }
/// For absolute Date object the default region is obtained from the global `defaultRegion` variable.
public var region: Region {
return SwiftDate.defaultRegion
}
#if os(Linux)
public var customFormatter: DateFormatter? {
get {
debugPrint("Not supported on Linux")
return nil
}
set { debugPrint("Not supported on Linux") }
}
#else
/// Assign a custom formatter if you need a special behaviour during formatting of the object.
/// Usually you will not need to do it, SwiftDate uses the local thread date formatter in order to
/// optimize the formatting process. By default is `nil`.
public var customFormatter: DateFormatter? {
get {
let fomatter: DateFormatter? = getAssociatedValue(key: AssociatedKeys.customDateFormatter.rawValue, object: self as AnyObject)
return fomatter
}
set {
set(associatedValue: newValue, key: AssociatedKeys.customDateFormatter.rawValue, object: self as AnyObject)
}
}
#endif
/// Extract the date components.
public var dateComponents: DateComponents {
return region.calendar.dateComponents(DateComponents.allComponentsSet, from: self)
}
/// Initialize a new date object from string expressed in given region.
///
/// - Parameters:
/// - string: date expressed as string.
/// - format: format of the date (`nil` uses provided list of auto formats patterns.
/// Pass it if you can in order to optimize the parse task).
/// - region: region in which the date is expressed. `nil` uses the `SwiftDate.defaultRegion`.
public init?(_ string: String, format: String? = nil, region: Region = SwiftDate.defaultRegion) {
guard let dateInRegion = DateInRegion(string, format: format, region: region) else { return nil }
self = dateInRegion.date
}
/// Initialize a new date from the number of seconds passed since Unix Epoch.
///
/// - Parameter interval: seconds
/// Initialize a new date from the number of seconds passed since Unix Epoch.
///
/// - Parameters:
/// - interval: seconds from Unix epoch time.
/// - region: region in which the date, `nil` uses the default region at UTC timezone
public init(seconds interval: TimeInterval, region: Region = Region.UTC) {
self = DateInRegion(seconds: interval, region: region).date
}
/// Initialize a new date corresponding to the number of milliseconds since the Unix Epoch.
///
/// - Parameters:
/// - interval: seconds since the Unix Epoch timestamp.
/// - region: region in which the date must be expressed, `nil` uses the default region at UTC timezone
public init(milliseconds interval: Int, region: Region = Region.UTC) {
self = DateInRegion(milliseconds: interval, region: region).date
}
/// Initialize a new date with the opportunity to configure single date components via builder pattern.
/// Date is therfore expressed in passed region (`DateComponents`'s `timezone`,`calendar` and `locale` are ignored
/// and overwritten by the region if not `nil`).
///
/// - Parameters:
/// - configuration: configuration callback
/// - region: region in which the date is expressed. Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components configuration: ((inout DateComponents) -> Void), region: Region? = SwiftDate.defaultRegion) {
guard let date = DateInRegion(components: configuration, region: region)?.date else { return nil }
self = date
}
/// Initialize a new date with given components.
///
/// - Parameters:
/// - components: components of the date.
/// - region: region in which the date is expressed.
/// Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components: DateComponents, region: Region?) {
guard let date = DateInRegion(components: components, region: region)?.date else { return nil }
self = date
}
/// Initialize a new date with given components.
public init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int = 0, nanosecond: Int = 0, region: Region = SwiftDate.defaultRegion) {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
components.timeZone = region.timeZone
components.calendar = region.calendar
self = region.calendar.date(from: components)!
}
/// Express given absolute date in the context of the default region.
///
/// - Returns: `DateInRegion`
public func inDefaultRegion() -> DateInRegion {
return DateInRegion(self, region: SwiftDate.defaultRegion)
}
/// Express given absolute date in the context of passed region.
///
/// - Parameter region: destination region.
/// - Returns: `DateInRegion`
public func `in`(region: Region) -> DateInRegion {
return DateInRegion(self, region: region)
}
/// Return a date in the distant future.
///
/// - Returns: Date instance.
public static func past() -> Date {
return Date.distantPast
}
/// Return a date in the distant past.
///
/// - Returns: Date instance.
public static func future() -> Date {
return Date.distantFuture
}
}
|
mit
|
37c8104e8df6647993f3f27582e59c7f
| 34.728395 | 151 | 0.717346 | 3.967101 | false | false | false | false |
designatednerd/ILGDynamicObjC
|
Example/Tests/ILGClasses_Tests_Swift.swift
|
1
|
2017
|
//
// ILGClasses_Tests_Swift.swift
// ILGDynamicObjC
//
// Created by Ellen Shapiro on 2/29/16.
// Copyright © 2016 Isaac Greenspan. All rights reserved.
//
import XCTest
@testable import ILGDynamicObjC_Example
class ILGClasses_Tests_Swift: XCTestCase {
//MARK: - Generic passing test tests
func testNonIncludedTestWorks() {
let expectedClasses = NSSet(array:[
SwiftChildClass1.self,
SwiftGrandchildClass1.self,
ILGChildClass1.self,
ILGGrandchildClass1.self,
])
let retrievedClasses = ILGClasses.classesPassingTest {
aClass -> Bool in
let className = NSStringFromClass(aClass)
return className.containsString("Class1")
}
XCTAssertEqual(expectedClasses, retrievedClasses);
}
//MARK: - Subclass tests
func testGettingSubclassesOfCustomSwiftClassNotInheritingFromNSObject() {
let expectedSubclasses = NSSet(array:[
SwiftChildClass1.self,
SwiftChildClass2.self,
SwiftChildClass3.self,
SwiftGrandchildClass1.self,
])
let retrievedSubclasses = ILGClasses.subclassesOfClass(SwiftParentClass.self)
XCTAssertEqual(expectedSubclasses, retrievedSubclasses)
}
//MARK: - Protocol Tests
func testParentClassConformingToObjcProtocolMakesChildAndGrandchildClassesReturned() {
let expectedProtocolConformingClasses = NSSet(array:[
SwiftParentClass.self,
SwiftChildClass1.self,
SwiftChildClass2.self,
SwiftChildClass3.self,
SwiftGrandchildClass1.self,
])
guard let retrievedClasses = ILGClasses.classesConformingToProtocol(SwiftProtocolMarkedWithObjC.self) else {
XCTFail("No classes found!")
return
}
XCTAssertEqual(expectedProtocolConformingClasses, retrievedClasses)
}
}
|
mit
|
022bb64f7174b3e1e3d12f2940a4d4e3
| 29.089552 | 116 | 0.640873 | 4.953317 | false | true | false | false |
sbooth/SFBAudioEngine
|
Device/AudioHardwareIOProcStreamUsageWrapper.swift
|
1
|
2554
|
//
// Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
import CoreAudio
extension AudioHardwareIOProcStreamUsage {
/// Returns the size in bytes of an `AudioHardwareIOProcStreamUsage` struct
/// - parameter maximumStreams: The number of streams
public static func sizeInBytes(maximumStreams: Int) -> Int {
let offset = MemoryLayout.offset(of: \AudioHardwareIOProcStreamUsage.mStreamIsOn)!
return offset + (MemoryLayout<UInt32>.stride * maximumStreams)
}
}
/// A thin wrapper around a variable-length `AudioHardwareIOProcStreamUsage` structure
public class AudioHardwareIOProcStreamUsageWrapper {
/// The underlying memory
let ptr: UnsafePointer<UInt8>
/// Creates a new `AudioHardwareIOProcStreamUsage` instance
/// - note: The returned object assumes ownership of `mem`
init(_ mem: UnsafePointer<UInt8>) {
ptr = mem
}
deinit {
ptr.deallocate()
}
/// Returns the stream usage's `mIOProc`
public var ioProc: UnsafeRawPointer {
return ptr.withMemoryRebound(to: AudioHardwareIOProcStreamUsage.self, capacity: 1) { UnsafeRawPointer($0.pointee.mIOProc) }
}
/// Returns the stream usage's `mNumberStreams`
public var numberStreams: UInt32 {
return ptr.withMemoryRebound(to: AudioHardwareIOProcStreamUsage.self, capacity: 1) { $0.pointee.mNumberStreams }
}
/// Returns the stream usage's `mStreamIsOn`
public var streamIsOn: UnsafeBufferPointer<UInt32> {
let count = Int(numberStreams)
// Does not compile (!) : MemoryLayout<AudioHardwareIOProcStreamUsage>.offset(of: \.mStreamIsOn)
let offset = MemoryLayout.offset(of: \AudioHardwareIOProcStreamUsage.mStreamIsOn)!
let bufPtr = UnsafeRawPointer(ptr.advanced(by: offset)).assumingMemoryBound(to: UInt32.self)
return UnsafeBufferPointer<UInt32>(start: bufPtr, count: count)
}
/// Performs `block` with a pointer to the underlying `AudioHardwareIOProcStreamUsage` structure
public func withUnsafePointer<T>(_ block: (UnsafePointer<AudioHardwareIOProcStreamUsage>) throws -> T) rethrows -> T {
return try ptr.withMemoryRebound(to: AudioHardwareIOProcStreamUsage.self, capacity: 1) { return try block($0) }
}
}
extension AudioHardwareIOProcStreamUsageWrapper: CustomDebugStringConvertible {
// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
return "<\(type(of: self)): mNumberStreams = \(numberStreams), mStreamIsOn = [\(streamIsOn.map({ $0 == 0 ? "Off" : "On" }).joined(separator: ", "))]>"
}
}
|
mit
|
4372d66b07f9139435615d1f57e8fd7e
| 38.90625 | 152 | 0.758418 | 3.744868 | false | false | false | false |
dcunited001/SpectraNu
|
Spectra/Classes/Transform3D.swift
|
1
|
8248
|
//
// SpectraTransforms.swift
// Spectra
//
// Created by David Conner on 9/25/15.
// Copyright © 2015 Spectra. All rights reserved.
//
import simd
//TODO: evaluate moving this elsewhere
// - perhaps protocol with default behavior,
// - so these methods can be added where needed
public class Transform3D {
// sx 0 0 0
// 0 sy 0 0
// 0 0 sz 0
// 0 0 0 1
class func scale(x: Float, y: Float, z: Float) -> float4x4 {
let v: float4 = [x, y, z, 1.0]
return float4x4(diagonal: v)
}
class func scale(s: float3) -> float4x4 {
let v: float4 = [s.x, s.y, s.z, 1.0]
return float4x4(diagonal: v)
}
class func scale(s: float4) -> float4x4 {
return float4x4(diagonal: s)
}
// 1 0 0 tx
// 0 1 0 ty
// 0 0 1 tz
// 0 0 0 1
class func translate(x: Float, y: Float, z: Float) -> float4x4 {
return translate(float3(x, y, z))
}
class func translate(t: float3) -> float4x4 {
var M = float4x4(diagonal: float4(1.0,1.0,1.0,1.0))
M[3] = [t.x, t.y, t.z, 1.0]
return M
}
//alternate implementation
class func translate(t: float4) -> float4x4 {
var M = float4x4(diagonal: float4(1.0,1.0,1.0,1.0))
M[3] = t
return M
}
static let k1Div180_f: Float = 1.0 / 180.0;
class func radiansOverPi(degrees: Float) -> Float {
return (degrees * k1Div180_f)
}
class func toRadians(val:Float) -> Float {
return val * Float(M_PI) / 180.0;
}
class func rotate(r: float4) -> float4x4{
let a = radiansOverPi(r.w)
var c:Float = 0.0
var s:Float = 0.0
__sincospif(a, &c, &s)
var u = normalize(float3(r.x, r.y, r.z))
let k = 1.0 - c
let v = s * u
let w = k * u
let P:float4 = [
w.x * u.x + c,
w.x * u.y + v.z,
w.x * u.z - v.y, 0.0]
let Q:float4 = [
w.x * u.y - v.z,
w.y * u.y + c,
w.y * u.z + v.x, 0.0]
let R:float4 = [
w.x * u.z + v.y,
w.y * u.z - v.x,
w.z * u.z + c, 0.0]
let S:float4 = [0.0, 0.0, 0.0, 1.0]
return float4x4(rows: [P, Q, R, S])
}
class func lookAt(eye: float4, center: float4, up: float4) -> float4x4 {
let eye:float3 = [eye[0], eye[1], eye[2]]
let center:float3 = [center[0], center[1], center[2]]
let up:float3 = [up[0], up[1], up[2]]
return lookAt(eye, center: center, up: up)
}
class func lookAt(eye: float3, center: float3, up: float3) -> float4x4 {
let E:float3 = -eye
let N:float3 = normalize(center + E)
let U:float3 = normalize(cross(up, N))
let V:float3 = cross(N, U)
let P:float4 = [U.x, V.x, N.x, 0.0]
let Q:float4 = [U.y, V.y, N.y, 0.0]
let R:float4 = [U.z, V.z, N.z, 0.0]
let S:float4 = [dot(U,E), dot(V,E), dot(N,E), 1.0]
return float4x4(rows: [P, Q, R, S])
}
// w - width
// h - height
// d - depth
// n - near
// w 0 0 0
// 0 h 0 0
// 0 0 d 1
// 0 0 d*n 0
class func frustum(fovH:Float, fovV:Float, near:Float, far:Float) -> float4x4 {
let width:Float = 1.0 / tan(toRadians(0.5 * fovH))
let height:Float = 1.0 / tan(toRadians(0.5 * fovV))
let sDepth:Float = far / (far-near)
var P = float4(0.0)
var Q = float4(0.0)
var R = float4(0.0)
var S = float4(0.0)
P.x = width
Q.y = height
R.z = sDepth
R.w = 1.0
S.z = -sDepth * near
return float4x4([P,Q,R,S])
}
class func frustum(left:Float, right:Float, bottom:Float, top:Float, near:Float, far:Float) -> float4x4 {
let width = right - left
let height = top - bottom
let depth = far - near
let sDepth = far / depth
var P = float4(0.0)
var Q = float4(0.0)
var R = float4(0.0)
var S = float4(0.0)
P.x = width
Q.y = height
R.z = sDepth
R.w = 1.0
S.z = -sDepth * near
return float4x4([P,Q,R,S])
}
class func frustum_oc(left:Float, right:Float, bottom:Float, top:Float, near:Float, far:Float) -> float4x4 {
let sWidth = 1.0 / (right - left)
let sHeight = 1.0 / (top - bottom)
let sDepth = far / (far - near)
let dNear = 2.0 * near
var P = float4(0.0)
var Q = float4(0.0)
var R = float4(0.0)
var S = float4(0.0)
P.x = dNear * sWidth
Q.y = dNear * sHeight
R.x = -sWidth * (right + left)
R.y = -sHeight * (top + bottom)
R.z = sDepth
R.w = 1.0
S.z = -sDepth * near
return float4x4([P,Q,R,S])
}
class func perspective(width:Float, height:Float, near:Float, far:Float) -> float4x4 {
let zNear = 2.0 * near
let zFar = far / (far - near)
var P = float4(0.0, 0.0, 0.0, 0.0)
var Q = float4(0.0, 0.0, 0.0, 0.0)
var R = float4(0.0, 0.0, 0.0, 0.0)
var S = float4(0.0, 0.0, 0.0, 0.0)
P.x = zNear / width
Q.y = zNear / height
R.z = zFar
R.w = 1.0
S.z = -near * zFar
return float4x4([P,Q,R,S])
}
class func perspectiveFov(fovy:Float, aspect:Float, near:Float, far:Float) -> float4x4 {
let angle:Float = toRadians(0.5 * fovy)
let yScale:Float = 1.0 / tanf(angle)
let xScale:Float = yScale / aspect
let zScale = far / (far - near)
var P = float4(0.0, 0.0, 0.0, 0.0)
var Q = float4(0.0, 0.0, 0.0, 0.0)
var R = float4(0.0, 0.0, 0.0, 0.0)
var S = float4(0.0, 0.0, 0.0, 0.0)
P.x = xScale
Q.y = yScale
R.z = zScale
R.w = 1.0
S.z = -near * zScale
return float4x4([P, Q, R, S])
}
//
// static matrix_float4x4 matrix_from_perspective_fov_aspectLH(const float fovY, const float aspect, const float nearZ, const float farZ) {
// // 1 / tan == cot
// float yscale = 1.0f / tanf(fovY * 0.5f);
// float xscale = yscale / aspect;
// float q = farZ / (farZ - nearZ);
//
// matrix_float4x4 m = {
// .columns[0] = { xscale, 0.0f, 0.0f, 0.0f },
// .columns[1] = { 0.0f, yscale, 0.0f, 0.0f },
// .columns[2] = { 0.0f, 0.0f, q, 1.0f },
// .columns[3] = { 0.0f, 0.0f, q * -nearZ, 0.0f }
// };
//
// return m;
// }
class func perspectiveFov(fovy:Float, width:Float, height:Float, near:Float, far:Float) -> float4x4 {
let aspect:Float = width / height
return perspectiveFov(fovy, aspect: aspect, near: near, far: far)
}
// simd::float4x4 perspective(const float& width,
// const float& height,
// const float& near,
// const float& far);
//
// simd::float4x4 perspective_fov(const float& fovy,
// const float& aspect,
// const float& near,
// const float& far);
//
// simd::float4x4 perspective_fov(const float& fovy,
// const float& width,
// const float& height,
// const float& near,
// const float& far);
//
// simd::float4x4 ortho2d_oc(const float& left,
// const float& right,
// const float& bottom,
// const float& top,
// const float& near,
// const float& far);
//
// simd::float4x4 ortho2d_oc(const simd::float3& origin,
// const simd::float3& size);
//
// simd::float4x4 ortho2d(const float& left,
// const float& right,
// const float& bottom,
// const float& top,
// const float& near,
// const float& far);
//
// simd::float4x4 ortho2d(const simd::float3& origin,
// const simd::float3& size);
//
}
|
mit
|
f985f588fbde19a7b896d90138e0a18f
| 27.735192 | 146 | 0.476901 | 2.884575 | false | false | false | false |
ashfurrow/Nimble-Snapshots
|
Bootstrap/Bootstrap/DynamicTypeView.swift
|
1
|
2131
|
import Foundation
import UIKit
public final class DynamicTypeView: UIView {
public let label: UILabel
override public init(frame: CGRect) {
label = UILabel()
super.init(frame: frame)
backgroundColor = .white
translatesAutoresizingMaskIntoConstraints = false
label.font = .preferredFont(forTextStyle: .body)
label.text = "Example"
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
addSubview(label)
setNeedsUpdateConstraints()
#if swift(>=4.2)
let notName = UIContentSizeCategory.didChangeNotification
#else
let notName = NSNotification.Name.UIContentSizeCategoryDidChange
#endif
NotificationCenter.default.addObserver(self, selector: #selector(updateFonts),
name: notName,
object: nil)
}
private var createdConstraints = false
override public func updateConstraints() {
if !createdConstraints {
label.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
}
super.updateConstraints()
}
@objc
func updateFonts(_ notification: Notification) {
#if swift(>=4.2)
let newValueKey = UIContentSizeCategory.newValueUserInfoKey
#else
let newValueKey = UIContentSizeCategoryNewValueKey
#endif
guard let category = notification.userInfo?[newValueKey] as? String else {
return
}
label.font = .preferredFont(forTextStyle: .body)
label.text = category.replacingOccurrences(of: "UICTContentSizeCategory", with: "")
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
3c4fa86f50b6953bd58db82219b348ab
| 31.784615 | 91 | 0.640544 | 5.65252 | false | false | false | false |
Pingco/Side-Menu.iOS
|
MenuExample/Controller/MenuViewController.swift
|
12
|
1728
|
//
// Copyright © 2014 Yalantis
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at http://github.com/yalantis/Side-Menu.iOS
//
import UIKit
import SideMenu
protocol MenuViewControllerDelegate: class {
func menu(menu: MenuViewController, didSelectItemAtIndex index: Int, atPoint point: CGPoint)
func menuDidCancel(menu: MenuViewController)
}
class MenuViewController: UITableViewController {
weak var delegate: MenuViewControllerDelegate?
var selectedItem = 0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let indexPath = NSIndexPath(forRow: selectedItem, inSection: 0)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
}
extension MenuViewController {
@IBAction
private func dismissMenu() {
delegate?.menuDidCancel(self)
}
}
extension MenuViewController: Menu {
var menuItems: [UIView] {
return [tableView.tableHeaderView!] + tableView.visibleCells() as [UIView]
}
}
extension MenuViewController: UITableViewDelegate {
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return indexPath == tableView.indexPathForSelectedRow() ? nil : indexPath
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rect = tableView.rectForRowAtIndexPath(indexPath)
var point = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
point = tableView.convertPoint(point, toView: nil)
delegate?.menu(self, didSelectItemAtIndex: indexPath.row, atPoint:point)
}
}
|
mit
|
14287748db01e7e62937a83014e50b66
| 32.862745 | 118 | 0.736537 | 5.049708 | false | false | false | false |
johnno1962b/swift-corelibs-foundation
|
Foundation/Unit.swift
|
5
|
68411
|
/*
NSUnitConverter describes how to convert a unit to and from the base unit of its dimension. Use the NSUnitConverter protocol to implement new ways of converting a unit.
*/
open class UnitConverter : NSObject {
/*
The following methods perform conversions to and from the base unit of a unit class's dimension. Each unit is defined against the base unit for the dimension to which the unit belongs.
These methods are implemented differently depending on the type of conversion. The default implementation in NSUnitConverter simply returns the value.
These methods exist for the sole purpose of creating custom conversions for units in order to support converting a value from one kind of unit to another in the same dimension. NSUnitConverter is an abstract class that is meant to be subclassed. There is no need to call these methods directly to do a conversion -- the correct way to convert a measurement is to use [NSMeasurement measurementByConvertingToUnit:]. measurementByConvertingToUnit: uses the following 2 methods internally to perform the conversion.
When creating a custom unit converter, you must override these two methods to implement the conversion to and from a value in terms of a unit and the corresponding value in terms of the base unit of that unit's dimension in order for conversion to work correctly.
*/
/*
This method takes a value in terms of a unit and returns the corresponding value in terms of the base unit of the original unit's dimension.
@param value Value in terms of the unit class
@return Value in terms of the base unit
*/
open func baseUnitValue(fromValue value: Double) -> Double {
return value
}
/*
This method takes in a value in terms of the base unit of a unit's dimension and returns the equivalent value in terms of the unit.
@param baseUnitValue Value in terms of the base unit
@return Value in terms of the unit class
*/
open func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return baseUnitValue
}
}
open class UnitConverterLinear : UnitConverter, NSSecureCoding {
open private(set) var coefficient: Double
open private(set) var constant: Double
public convenience init(coefficient: Double) {
self.init(coefficient: coefficient, constant: 0)
}
public init(coefficient: Double, constant: Double) {
self.coefficient = coefficient
self.constant = constant
}
open override func baseUnitValue(fromValue value: Double) -> Double {
return value * coefficient + constant
}
open override func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return (baseUnitValue - constant) / coefficient
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let coefficient = aDecoder.decodeDouble(forKey: "NS.coefficient")
let constant = aDecoder.decodeDouble(forKey: "NS.constant")
self.init(coefficient: coefficient, constant: constant)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.coefficient, forKey:"NS.coefficient")
aCoder.encode(self.constant, forKey:"NS.constant")
}
public static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConverterLinear else {
return false
}
if self === other {
return true
}
return self.coefficient == other.coefficient
&& self.constant == other.constant
}
}
private class UnitConverterReciprocal : UnitConverter, NSSecureCoding {
private private(set) var reciprocal: Double
fileprivate init(reciprocal: Double) {
self.reciprocal = reciprocal
}
fileprivate override func baseUnitValue(fromValue value: Double) -> Double {
return reciprocal / value
}
fileprivate override func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return reciprocal / baseUnitValue
}
fileprivate required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let reciprocal = aDecoder.decodeDouble(forKey: "NS.reciprocal")
self.init(reciprocal: reciprocal)
}
fileprivate func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.reciprocal, forKey:"NS.reciprocal")
}
fileprivate static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConverterReciprocal else {
return false
}
if self === other {
return true
}
return self.reciprocal == other.reciprocal
}
}
/*
NSUnit is the base class for all unit types (dimensional and dimensionless).
*/
open class Unit : NSObject, NSCopying, NSSecureCoding {
open private(set) var symbol: String
public required init(symbol: String) {
self.symbol = symbol
}
open func copy(with zone: NSZone?) -> Any {
return self
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let symbol = aDecoder.decodeObject(forKey: "NS.symbol") as? String
else { return nil }
self.symbol = symbol
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.symbol._bridgeToObjectiveC(), forKey:"NS.symbol")
}
public static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Unit else {
return false
}
if self === other {
return true
}
return self.symbol == other.symbol
}
}
open class Dimension : Unit {
open private(set) var converter: UnitConverter
public required init(symbol: String, converter: UnitConverter) {
self.converter = converter
super.init(symbol: symbol)
}
/*
This class method returns an instance of the dimension class that represents the base unit of that dimension.
e.g.
NSUnitSpeed *metersPerSecond = [NSUnitSpeed baseUnit];
*/
open class func baseUnit() -> Self {
fatalError("*** You must override baseUnit in your class to define its base unit.")
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard
let symbol = aDecoder.decodeObject(forKey: "NS.symbol") as? String,
let converter = aDecoder.decodeObject(forKey: "NS.converter") as? UnitConverter
else { return nil }
self.converter = converter
super.init(symbol: symbol)
}
public required init(symbol: String) {
let T = type(of: self)
fatalError("\(T) must be initialized with designated initializer \(T).init(symbol: String, converter: UnitConverter)")
}
open override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.converter, forKey:"converter")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Dimension else {
return false
}
if self === other {
return true
}
return super.isEqual(object) && self.converter == other.converter
}
}
open class UnitAcceleration : Dimension {
/*
Base unit - metersPerSecondSquared
*/
private struct Symbol {
static let metersPerSecondSquared = "m/s²"
static let gravity = "g"
}
private struct Coefficient {
static let metersPerSecondSquared = 1.0
static let gravity = 9.81
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var metersPerSecondSquared: UnitAcceleration {
get {
return UnitAcceleration(symbol: Symbol.metersPerSecondSquared, coefficient: Coefficient.metersPerSecondSquared)
}
}
open class var gravity: UnitAcceleration {
get {
return UnitAcceleration(symbol: Symbol.gravity, coefficient: Coefficient.gravity)
}
}
open override class func baseUnit() -> UnitAcceleration {
return UnitAcceleration.metersPerSecondSquared
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitAcceleration else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitAngle : Dimension {
/*
Base unit - degrees
*/
private struct Symbol {
static let degrees = "°"
static let arcMinutes = "ʹ"
static let arcSeconds = "ʹʹ"
static let radians = "rad"
static let gradians = "grad"
static let revolutions = "rev"
}
private struct Coefficient {
static let degrees = 1.0
static let arcMinutes = 1.0 / 60.0
static let arcSeconds = 1.0 / 3600.0
static let radians = 180.0 / .pi
static let gradians = 0.9
static let revolutions = 360.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var degrees: UnitAngle {
get {
return UnitAngle(symbol: Symbol.degrees, coefficient: Coefficient.degrees)
}
}
open class var arcMinutes: UnitAngle {
get {
return UnitAngle(symbol: Symbol.arcMinutes, coefficient: Coefficient.arcMinutes)
}
}
open class var arcSeconds: UnitAngle {
get {
return UnitAngle(symbol: Symbol.arcSeconds, coefficient: Coefficient.arcSeconds)
}
}
open class var radians: UnitAngle {
get {
return UnitAngle(symbol: Symbol.radians, coefficient: Coefficient.radians)
}
}
open class var gradians: UnitAngle {
get {
return UnitAngle(symbol: Symbol.gradians, coefficient: Coefficient.gradians)
}
}
open class var revolutions: UnitAngle {
get {
return UnitAngle(symbol: Symbol.revolutions, coefficient: Coefficient.revolutions)
}
}
open override class func baseUnit() -> UnitAngle {
return UnitAngle.degrees
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitAngle else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitArea : Dimension {
/*
Base unit - squareMeters
*/
private struct Symbol {
static let squareMegameters = "Mm²"
static let squareKilometers = "km²"
static let squareMeters = "m²"
static let squareCentimeters = "cm²"
static let squareMillimeters = "mm²"
static let squareMicrometers = "µm²"
static let squareNanometers = "nm²"
static let squareInches = "in²"
static let squareFeet = "ft²"
static let squareYards = "yd²"
static let squareMiles = "mi²"
static let acres = "ac"
static let ares = "a"
static let hectares = "ha"
}
private struct Coefficient {
static let squareMegameters = 1e12
static let squareKilometers = 1e6
static let squareMeters = 1.0
static let squareCentimeters = 1e-4
static let squareMillimeters = 1e-6
static let squareMicrometers = 1e-12
static let squareNanometers = 1e-18
static let squareInches = 0.00064516
static let squareFeet = 0.092903
static let squareYards = 0.836127
static let squareMiles = 2.59e+6
static let acres = 4046.86
static let ares = 100.0
static let hectares = 10000.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var squareMegameters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMegameters, coefficient: Coefficient.squareMegameters)
}
}
open class var squareKilometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareKilometers, coefficient: Coefficient.squareKilometers)
}
}
open class var squareMeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMeters, coefficient: Coefficient.squareMeters)
}
}
open class var squareCentimeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareCentimeters, coefficient: Coefficient.squareCentimeters)
}
}
open class var squareMillimeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMillimeters, coefficient: Coefficient.squareMillimeters)
}
}
open class var squareMicrometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMicrometers, coefficient: Coefficient.squareMicrometers)
}
}
open class var squareNanometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareNanometers, coefficient: Coefficient.squareNanometers)
}
}
open class var squareInches: UnitArea {
get {
return UnitArea(symbol: Symbol.squareInches, coefficient: Coefficient.squareInches)
}
}
open class var squareFeet: UnitArea {
get {
return UnitArea(symbol: Symbol.squareFeet, coefficient: Coefficient.squareFeet)
}
}
open class var squareYards: UnitArea {
get {
return UnitArea(symbol: Symbol.squareYards, coefficient: Coefficient.squareYards)
}
}
open class var squareMiles: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMiles, coefficient: Coefficient.squareMiles)
}
}
open class var acres: UnitArea {
get {
return UnitArea(symbol: Symbol.acres, coefficient: Coefficient.acres)
}
}
open class var ares: UnitArea {
get {
return UnitArea(symbol: Symbol.ares, coefficient: Coefficient.ares)
}
}
open class var hectares: UnitArea {
get {
return UnitArea(symbol: Symbol.hectares, coefficient: Coefficient.hectares)
}
}
open override class func baseUnit() -> UnitArea {
return UnitArea.squareMeters
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitArea else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitConcentrationMass : Dimension {
/*
Base unit - gramsPerLiter
*/
private struct Symbol {
static let gramsPerLiter = "g/L"
static let milligramsPerDeciliter = "mg/dL"
static let millimolesPerLiter = "mmol/L"
}
private struct Coefficient {
static let gramsPerLiter = 1.0
static let milligramsPerDeciliter = 0.01
static let millimolesPerLiter = 18.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var gramsPerLiter: UnitConcentrationMass {
get {
return UnitConcentrationMass(symbol: Symbol.gramsPerLiter, coefficient: Coefficient.gramsPerLiter)
}
}
open class var milligramsPerDeciliter: UnitConcentrationMass {
get {
return UnitConcentrationMass(symbol: Symbol.milligramsPerDeciliter, coefficient: Coefficient.milligramsPerDeciliter)
}
}
open class func millimolesPerLiter(withGramsPerMole gramsPerMole: Double) -> UnitConcentrationMass {
return UnitConcentrationMass(symbol: Symbol.millimolesPerLiter, coefficient: Coefficient.millimolesPerLiter * gramsPerMole)
}
open override class func baseUnit() -> UnitConcentrationMass {
return UnitConcentrationMass.gramsPerLiter
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConcentrationMass else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitDispersion : Dimension {
/*
Base unit - partsPerMillion
*/
private struct Symbol {
static let partsPerMillion = "ppm"
}
private struct Coefficient {
static let partsPerMillion = 1.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var partsPerMillion: UnitDispersion {
get {
return UnitDispersion(symbol: Symbol.partsPerMillion, coefficient: Coefficient.partsPerMillion)
}
}
open override class func baseUnit() -> UnitDispersion {
return UnitDispersion.partsPerMillion
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitDispersion else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitDuration : Dimension {
/*
Base unit - seconds
*/
private struct Symbol {
static let seconds = "s"
static let minutes = "m"
static let hours = "h"
}
private struct Coefficient {
static let seconds = 1.0
static let minutes = 60.0
static let hours = 3600.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var seconds: UnitDuration {
get {
return UnitDuration(symbol: Symbol.seconds, coefficient: Coefficient.seconds)
}
}
open class var minutes: UnitDuration {
get {
return UnitDuration(symbol: Symbol.minutes, coefficient: Coefficient.minutes)
}
}
open class var hours: UnitDuration {
get {
return UnitDuration(symbol: Symbol.hours, coefficient: Coefficient.hours)
}
}
open override class func baseUnit() -> UnitDuration {
return UnitDuration.seconds
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitDuration else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitElectricCharge : Dimension {
/*
Base unit - coulombs
*/
private struct Symbol {
static let coulombs = "C"
static let megaampereHours = "MAh"
static let kiloampereHours = "kAh"
static let ampereHours = "Ah"
static let milliampereHours = "mAh"
static let microampereHours = "µAh"
}
private struct Coefficient {
static let coulombs = 1.0
static let megaampereHours = 3.6e9
static let kiloampereHours = 3600000.0
static let ampereHours = 3600.0
static let milliampereHours = 3.6
static let microampereHours = 0.0036
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var coulombs: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.coulombs, coefficient: Coefficient.coulombs)
}
}
open class var megaampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.megaampereHours, coefficient: Coefficient.megaampereHours)
}
}
open class var kiloampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.kiloampereHours, coefficient: Coefficient.kiloampereHours)
}
}
open class var ampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.ampereHours, coefficient: Coefficient.ampereHours)
}
}
open class var milliampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.milliampereHours, coefficient: Coefficient.milliampereHours)
}
}
open class var microampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.microampereHours, coefficient: Coefficient.microampereHours)
}
}
open override class func baseUnit() -> UnitElectricCharge {
return UnitElectricCharge.coulombs
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricCharge else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitElectricCurrent : Dimension {
/*
Base unit - amperes
*/
private struct Symbol {
static let megaamperes = "MA"
static let kiloamperes = "kA"
static let amperes = "A"
static let milliamperes = "mA"
static let microamperes = "µA"
}
private struct Coefficient {
static let megaamperes = 1e6
static let kiloamperes = 1e3
static let amperes = 1.0
static let milliamperes = 1e-3
static let microamperes = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var megaamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.megaamperes, coefficient: Coefficient.megaamperes)
}
}
open class var kiloamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.kiloamperes, coefficient: Coefficient.kiloamperes)
}
}
open class var amperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.amperes, coefficient: Coefficient.amperes)
}
}
open class var milliamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.milliamperes, coefficient: Coefficient.milliamperes)
}
}
open class var microamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.microamperes, coefficient: Coefficient.microamperes)
}
}
open override class func baseUnit() -> UnitElectricCurrent {
return UnitElectricCurrent.amperes
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricCurrent else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitElectricPotentialDifference : Dimension {
/*
Base unit - volts
*/
private struct Symbol {
static let megavolts = "MV"
static let kilovolts = "kV"
static let volts = "V"
static let millivolts = "mV"
static let microvolts = "µV"
}
private struct Coefficient {
static let megavolts = 1e6
static let kilovolts = 1e3
static let volts = 1.0
static let millivolts = 1e-3
static let microvolts = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var megavolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.megavolts, coefficient: Coefficient.megavolts)
}
}
open class var kilovolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.kilovolts, coefficient: Coefficient.kilovolts)
}
}
open class var volts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.volts, coefficient: Coefficient.volts)
}
}
open class var millivolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.millivolts, coefficient: Coefficient.millivolts)
}
}
open class var microvolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.microvolts, coefficient: Coefficient.microvolts)
}
}
open override class func baseUnit() -> UnitElectricPotentialDifference {
return UnitElectricPotentialDifference.volts
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricPotentialDifference else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitElectricResistance : Dimension {
/*
Base unit - ohms
*/
private struct Symbol {
static let megaohms = "MΩ"
static let kiloohms = "kΩ"
static let ohms = "Ω"
static let milliohms = "mΩ"
static let microohms = "µΩ"
}
private struct Coefficient {
static let megaohms = 1e6
static let kiloohms = 1e3
static let ohms = 1.0
static let milliohms = 1e-3
static let microohms = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var megaohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.megaohms, coefficient: Coefficient.megaohms)
}
}
open class var kiloohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.kiloohms, coefficient: Coefficient.kiloohms)
}
}
open class var ohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.ohms, coefficient: Coefficient.ohms)
}
}
open class var milliohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.milliohms, coefficient: Coefficient.milliohms)
}
}
open class var microohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.microohms, coefficient: Coefficient.microohms)
}
}
open override class func baseUnit() -> UnitElectricResistance {
return UnitElectricResistance.ohms
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricResistance else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitEnergy : Dimension {
/*
Base unit - joules
*/
private struct Symbol {
static let kilojoules = "kJ"
static let joules = "J"
static let kilocalories = "kCal"
static let calories = "cal"
static let kilowattHours = "kWh"
}
private struct Coefficient {
static let kilojoules = 1e3
static let joules = 1.0
static let kilocalories = 4184.0
static let calories = 4.184
static let kilowattHours = 3600000.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var kilojoules: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilojoules, coefficient: Coefficient.kilojoules)
}
}
open class var joules: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.joules, coefficient: Coefficient.joules)
}
}
open class var kilocalories: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilocalories, coefficient: Coefficient.kilocalories)
}
}
open class var calories: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.calories, coefficient: Coefficient.calories)
}
}
open class var kilowattHours: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilowattHours, coefficient: Coefficient.kilowattHours)
}
}
open override class func baseUnit() -> UnitEnergy {
return UnitEnergy.joules
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitEnergy else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitFrequency : Dimension {
/*
Base unit - hertz
*/
private struct Symbol {
static let terahertz = "THz"
static let gigahertz = "GHz"
static let megahertz = "MHz"
static let kilohertz = "kHz"
static let hertz = "Hz"
static let millihertz = "mHz"
static let microhertz = "µHz"
static let nanohertz = "nHz"
}
private struct Coefficient {
static let terahertz = 1e12
static let gigahertz = 1e9
static let megahertz = 1e6
static let kilohertz = 1e3
static let hertz = 1.0
static let millihertz = 1e-3
static let microhertz = 1e-6
static let nanohertz = 1e-9
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var terahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.terahertz, coefficient: Coefficient.terahertz)
}
}
open class var gigahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.gigahertz, coefficient: Coefficient.gigahertz)
}
}
open class var megahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.megahertz, coefficient: Coefficient.megahertz)
}
}
open class var kilohertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.kilohertz, coefficient: Coefficient.kilohertz)
}
}
open class var hertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.hertz, coefficient: Coefficient.hertz)
}
}
open class var millihertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.millihertz, coefficient: Coefficient.millihertz)
}
}
open class var microhertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.microhertz, coefficient: Coefficient.microhertz)
}
}
open class var nanohertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.nanohertz, coefficient: Coefficient.nanohertz)
}
}
open override class func baseUnit() -> UnitFrequency {
return UnitFrequency.hertz
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitFrequency else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitFuelEfficiency : Dimension {
/*
Base unit - litersPer100Kilometers
*/
private struct Symbol {
static let litersPer100Kilometers = "L/100km"
static let milesPerImperialGallon = "mpg"
static let milesPerGallon = "mpg"
}
private struct Coefficient {
static let litersPer100Kilometers = 1.0
static let milesPerImperialGallon = 282.481
static let milesPerGallon = 235.215
}
private convenience init(symbol: String, reciprocal: Double) {
self.init(symbol: symbol, converter: UnitConverterReciprocal(reciprocal: reciprocal))
}
open class var litersPer100Kilometers: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.litersPer100Kilometers, reciprocal: Coefficient.litersPer100Kilometers)
}
}
open class var milesPerImperialGallon: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.milesPerImperialGallon, reciprocal: Coefficient.milesPerImperialGallon)
}
}
open class var milesPerGallon: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.milesPerGallon, reciprocal: Coefficient.milesPerGallon)
}
}
open override class func baseUnit() -> UnitFuelEfficiency {
return UnitFuelEfficiency.litersPer100Kilometers
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitFuelEfficiency else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitLength : Dimension {
/*
Base unit - meters
*/
private struct Symbol {
static let megameters = "Mm"
static let kilometers = "km"
static let hectometers = "hm"
static let decameters = "dam"
static let meters = "m"
static let decimeters = "dm"
static let centimeters = "cm"
static let millimeters = "mm"
static let micrometers = "µm"
static let nanometers = "nm"
static let picometers = "pm"
static let inches = "in"
static let feet = "ft"
static let yards = "yd"
static let miles = "mi"
static let scandinavianMiles = "smi"
static let lightyears = "ly"
static let nauticalMiles = "NM"
static let fathoms = "ftm"
static let furlongs = "fur"
static let astronomicalUnits = "ua"
static let parsecs = "pc"
}
private struct Coefficient {
static let megameters = 1e6
static let kilometers = 1e3
static let hectometers = 1e2
static let decameters = 1e1
static let meters = 1.0
static let decimeters = 1e-1
static let centimeters = 1e-2
static let millimeters = 1e-3
static let micrometers = 1e-6
static let nanometers = 1e-9
static let picometers = 1e-12
static let inches = 0.0254
static let feet = 0.3048
static let yards = 0.9144
static let miles = 1609.34
static let scandinavianMiles = 10000.0
static let lightyears = 9.461e+15
static let nauticalMiles = 1852.0
static let fathoms = 1.8288
static let furlongs = 201.168
static let astronomicalUnits = 1.496e+11
static let parsecs = 3.086e+16
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var megameters: UnitLength {
get {
return UnitLength(symbol: Symbol.megameters, coefficient: Coefficient.megameters)
}
}
open class var kilometers: UnitLength {
get {
return UnitLength(symbol: Symbol.kilometers, coefficient: Coefficient.kilometers)
}
}
open class var hectometers: UnitLength {
get {
return UnitLength(symbol: Symbol.hectometers, coefficient: Coefficient.hectometers)
}
}
open class var decameters: UnitLength {
get {
return UnitLength(symbol: Symbol.decameters, coefficient: Coefficient.decameters)
}
}
open class var meters: UnitLength {
get {
return UnitLength(symbol: Symbol.meters, coefficient: Coefficient.meters)
}
}
open class var decimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.decimeters, coefficient: Coefficient.decimeters)
}
}
open class var centimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.centimeters, coefficient: Coefficient.centimeters)
}
}
open class var millimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.millimeters, coefficient: Coefficient.millimeters)
}
}
open class var micrometers: UnitLength {
get {
return UnitLength(symbol: Symbol.micrometers, coefficient: Coefficient.micrometers)
}
}
open class var nanometers: UnitLength {
get {
return UnitLength(symbol: Symbol.nanometers, coefficient: Coefficient.nanometers)
}
}
open class var picometers: UnitLength {
get {
return UnitLength(symbol: Symbol.picometers, coefficient: Coefficient.picometers)
}
}
open class var inches: UnitLength {
get {
return UnitLength(symbol: Symbol.inches, coefficient: Coefficient.inches)
}
}
open class var feet: UnitLength {
get {
return UnitLength(symbol: Symbol.feet, coefficient: Coefficient.feet)
}
}
open class var yards: UnitLength {
get {
return UnitLength(symbol: Symbol.yards, coefficient: Coefficient.yards)
}
}
open class var miles: UnitLength {
get {
return UnitLength(symbol: Symbol.miles, coefficient: Coefficient.miles)
}
}
open class var scandinavianMiles: UnitLength {
get {
return UnitLength(symbol: Symbol.scandinavianMiles, coefficient: Coefficient.scandinavianMiles)
}
}
open class var lightyears: UnitLength {
get {
return UnitLength(symbol: Symbol.lightyears, coefficient: Coefficient.lightyears)
}
}
open class var nauticalMiles: UnitLength {
get {
return UnitLength(symbol: Symbol.nauticalMiles, coefficient: Coefficient.nauticalMiles)
}
}
open class var fathoms: UnitLength {
get {
return UnitLength(symbol: Symbol.fathoms, coefficient: Coefficient.fathoms)
}
}
open class var furlongs: UnitLength {
get {
return UnitLength(symbol: Symbol.furlongs, coefficient: Coefficient.furlongs)
}
}
open class var astronomicalUnits: UnitLength {
get {
return UnitLength(symbol: Symbol.astronomicalUnits, coefficient: Coefficient.astronomicalUnits)
}
}
open class var parsecs: UnitLength {
get {
return UnitLength(symbol: Symbol.parsecs, coefficient: Coefficient.parsecs)
}
}
open override class func baseUnit() -> UnitLength {
return UnitLength.meters
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitLength else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitIlluminance : Dimension {
/*
Base unit - lux
*/
private struct Symbol {
static let lux = "lx"
}
private struct Coefficient {
static let lux = 1.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var lux: UnitIlluminance {
get {
return UnitIlluminance(symbol: Symbol.lux, coefficient: Coefficient.lux)
}
}
open override class func baseUnit() -> UnitIlluminance {
return UnitIlluminance.lux
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitIlluminance else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitMass : Dimension {
/*
Base unit - kilograms
*/
private struct Symbol {
static let kilograms = "kg"
static let grams = "g"
static let decigrams = "dg"
static let centigrams = "cg"
static let milligrams = "mg"
static let micrograms = "µg"
static let nanograms = "ng"
static let picograms = "pg"
static let ounces = "oz"
static let pounds = "lb"
static let stones = "st"
static let metricTons = "t"
static let shortTons = "ton"
static let carats = "ct"
static let ouncesTroy = "oz t"
static let slugs = "slug"
}
private struct Coefficient {
static let kilograms = 1.0
static let grams = 1e-3
static let decigrams = 1e-4
static let centigrams = 1e-5
static let milligrams = 1e-6
static let micrograms = 1e-9
static let nanograms = 1e-12
static let picograms = 1e-15
static let ounces = 0.0283495
static let pounds = 0.453592
static let stones = 0.157473
static let metricTons = 1000.0
static let shortTons = 907.185
static let carats = 0.0002
static let ouncesTroy = 0.03110348
static let slugs = 14.5939
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var kilograms: UnitMass {
get {
return UnitMass(symbol: Symbol.kilograms, coefficient: Coefficient.kilograms)
}
}
open class var grams: UnitMass {
get {
return UnitMass(symbol: Symbol.grams, coefficient: Coefficient.grams)
}
}
open class var decigrams: UnitMass {
get {
return UnitMass(symbol: Symbol.decigrams, coefficient: Coefficient.decigrams)
}
}
open class var centigrams: UnitMass {
get {
return UnitMass(symbol: Symbol.centigrams, coefficient: Coefficient.centigrams)
}
}
open class var milligrams: UnitMass {
get {
return UnitMass(symbol: Symbol.milligrams, coefficient: Coefficient.milligrams)
}
}
open class var micrograms: UnitMass {
get {
return UnitMass(symbol: Symbol.micrograms, coefficient: Coefficient.micrograms)
}
}
open class var nanograms: UnitMass {
get {
return UnitMass(symbol: Symbol.nanograms, coefficient: Coefficient.nanograms)
}
}
open class var picograms: UnitMass {
get {
return UnitMass(symbol: Symbol.picograms, coefficient: Coefficient.picograms)
}
}
open class var ounces: UnitMass {
get {
return UnitMass(symbol: Symbol.ounces, coefficient: Coefficient.ounces)
}
}
open class var pounds: UnitMass {
get {
return UnitMass(symbol: Symbol.pounds, coefficient: Coefficient.pounds)
}
}
open class var stones: UnitMass {
get {
return UnitMass(symbol: Symbol.stones, coefficient: Coefficient.stones)
}
}
open class var metricTons: UnitMass {
get {
return UnitMass(symbol: Symbol.metricTons, coefficient: Coefficient.metricTons)
}
}
open class var shortTons: UnitMass {
get {
return UnitMass(symbol: Symbol.shortTons, coefficient: Coefficient.shortTons)
}
}
open class var carats: UnitMass {
get {
return UnitMass(symbol: Symbol.carats, coefficient: Coefficient.carats)
}
}
open class var ouncesTroy: UnitMass {
get {
return UnitMass(symbol: Symbol.ouncesTroy, coefficient: Coefficient.ouncesTroy)
}
}
open class var slugs: UnitMass {
get {
return UnitMass(symbol: Symbol.slugs, coefficient: Coefficient.slugs)
}
}
open override class func baseUnit() -> UnitMass {
return UnitMass.kilograms
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitMass else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitPower : Dimension {
/*
Base unit - watts
*/
private struct Symbol {
static let terawatts = "TW"
static let gigawatts = "GW"
static let megawatts = "MW"
static let kilowatts = "kW"
static let watts = "W"
static let milliwatts = "mW"
static let microwatts = "µW"
static let nanowatts = "nW"
static let picowatts = "nW"
static let femtowatts = "nHz"
static let horsepower = "hp"
}
private struct Coefficient {
static let terawatts = 1e12
static let gigawatts = 1e9
static let megawatts = 1e6
static let kilowatts = 1e3
static let watts = 1.0
static let milliwatts = 1e-3
static let microwatts = 1e-6
static let nanowatts = 1e-9
static let picowatts = 1e-12
static let femtowatts = 1e-15
static let horsepower = 745.7
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var terawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.terawatts, coefficient: Coefficient.terawatts)
}
}
open class var gigawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.gigawatts, coefficient: Coefficient.gigawatts)
}
}
open class var megawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.megawatts, coefficient: Coefficient.megawatts)
}
}
open class var kilowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.kilowatts, coefficient: Coefficient.kilowatts)
}
}
open class var watts: UnitPower {
get {
return UnitPower(symbol: Symbol.watts, coefficient: Coefficient.watts)
}
}
open class var milliwatts: UnitPower {
get {
return UnitPower(symbol: Symbol.milliwatts, coefficient: Coefficient.milliwatts)
}
}
open class var microwatts: UnitPower {
get {
return UnitPower(symbol: Symbol.microwatts, coefficient: Coefficient.microwatts)
}
}
open class var nanowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.nanowatts, coefficient: Coefficient.nanowatts)
}
}
open class var picowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.picowatts, coefficient: Coefficient.picowatts)
}
}
open class var femtowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.femtowatts, coefficient: Coefficient.femtowatts)
}
}
open class var horsepower: UnitPower {
get {
return UnitPower(symbol: Symbol.horsepower, coefficient: Coefficient.horsepower)
}
}
open override class func baseUnit() -> UnitPower {
return UnitPower.watts
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitPower else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitPressure : Dimension {
/*
Base unit - newtonsPerMetersSquared (equivalent to 1 pascal)
*/
private struct Symbol {
static let newtonsPerMetersSquared = "N/m²"
static let gigapascals = "GPa"
static let megapascals = "MPa"
static let kilopascals = "kPa"
static let hectopascals = "hPa"
static let inchesOfMercury = "inHg"
static let bars = "bar"
static let millibars = "mbar"
static let millimetersOfMercury = "mmHg"
static let poundsForcePerSquareInch = "psi"
}
private struct Coefficient {
static let newtonsPerMetersSquared = 1.0
static let gigapascals = 1e9
static let megapascals = 1e6
static let kilopascals = 1e3
static let hectopascals = 1e2
static let inchesOfMercury = 3386.39
static let bars = 1e5
static let millibars = 1e2
static let millimetersOfMercury = 133.322
static let poundsForcePerSquareInch = 6894.76
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var newtonsPerMetersSquared: UnitPressure {
get {
return UnitPressure(symbol: Symbol.newtonsPerMetersSquared, coefficient: Coefficient.newtonsPerMetersSquared)
}
}
open class var gigapascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.gigapascals, coefficient: Coefficient.gigapascals)
}
}
open class var megapascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.megapascals, coefficient: Coefficient.megapascals)
}
}
open class var kilopascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.kilopascals, coefficient: Coefficient.kilopascals)
}
}
open class var hectopascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.hectopascals, coefficient: Coefficient.hectopascals)
}
}
open class var inchesOfMercury: UnitPressure {
get {
return UnitPressure(symbol: Symbol.inchesOfMercury, coefficient: Coefficient.inchesOfMercury)
}
}
open class var bars: UnitPressure {
get {
return UnitPressure(symbol: Symbol.bars, coefficient: Coefficient.bars)
}
}
open class var millibars: UnitPressure {
get {
return UnitPressure(symbol: Symbol.millibars, coefficient: Coefficient.millibars)
}
}
open class var millimetersOfMercury: UnitPressure {
get {
return UnitPressure(symbol: Symbol.millimetersOfMercury, coefficient: Coefficient.millimetersOfMercury)
}
}
open class var poundsForcePerSquareInch: UnitPressure {
get {
return UnitPressure(symbol: Symbol.poundsForcePerSquareInch, coefficient: Coefficient.poundsForcePerSquareInch)
}
}
open override class func baseUnit() -> UnitPressure {
return UnitPressure.newtonsPerMetersSquared
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitPressure else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitSpeed : Dimension {
/*
Base unit - metersPerSecond
*/
private struct Symbol {
static let metersPerSecond = "m/s"
static let kilometersPerHour = "km/h"
static let milesPerHour = "mph"
static let knots = "kn"
}
private struct Coefficient {
static let metersPerSecond = 1.0
static let kilometersPerHour = 0.277778
static let milesPerHour = 0.44704
static let knots = 0.514444
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var metersPerSecond: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.metersPerSecond, coefficient: Coefficient.metersPerSecond)
}
}
open class var kilometersPerHour: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.kilometersPerHour, coefficient: Coefficient.kilometersPerHour)
}
}
open class var milesPerHour: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.milesPerHour, coefficient: Coefficient.milesPerHour)
}
}
open class var knots: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.knots, coefficient: Coefficient.knots)
}
}
open override class func baseUnit() -> UnitSpeed {
return UnitSpeed.metersPerSecond
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitSpeed else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitTemperature : Dimension {
/*
Base unit - kelvin
*/
private struct Symbol {
static let kelvin = "K"
static let celsius = "°C"
static let fahrenheit = "°F"
}
private struct Coefficient {
static let kelvin = 1.0
static let celsius = 1.0
static let fahrenheit = 0.55555555555556
}
private struct Constant {
static let kelvin = 0.0
static let celsius = 273.15
static let fahrenheit = 255.37222222222427
}
private convenience init(symbol: String, coefficient: Double, constant: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant))
}
open class var kelvin: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.kelvin, coefficient: Coefficient.kelvin, constant: Constant.kelvin)
}
}
open class var celsius: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.celsius, coefficient: Coefficient.celsius, constant: Constant.celsius)
}
}
open class var fahrenheit: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.fahrenheit, coefficient: Coefficient.fahrenheit, constant: Constant.fahrenheit)
}
}
open override class func baseUnit() -> UnitTemperature {
return UnitTemperature.kelvin
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitTemperature else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
open class UnitVolume : Dimension {
/*
Base unit - liters
*/
private struct Symbol {
static let megaliters = "ML"
static let kiloliters = "kL"
static let liters = "L"
static let deciliters = "dl"
static let centiliters = "cL"
static let milliliters = "mL"
static let cubicKilometers = "km³"
static let cubicMeters = "m³"
static let cubicDecimeters = "dm³"
static let cubicCentimeters = "cm³"
static let cubicMillimeters = "mm³"
static let cubicInches = "in³"
static let cubicFeet = "ft³"
static let cubicYards = "yd³"
static let cubicMiles = "mi³"
static let acreFeet = "af"
static let bushels = "bsh"
static let teaspoons = "tsp"
static let tablespoons = "tbsp"
static let fluidOunces = "fl oz"
static let cups = "cup"
static let pints = "pt"
static let quarts = "qt"
static let gallons = "gal"
static let imperialTeaspoons = "tsp Imperial"
static let imperialTablespoons = "tbsp Imperial"
static let imperialFluidOunces = "fl oz Imperial"
static let imperialPints = "pt Imperial"
static let imperialQuarts = "qt Imperial"
static let imperialGallons = "gal Imperial"
static let metricCups = "metric cup Imperial"
}
private struct Coefficient {
static let megaliters = 1e6
static let kiloliters = 1e3
static let liters = 1.0
static let deciliters = 1e-1
static let centiliters = 1e-2
static let milliliters = 1e-3
static let cubicKilometers = 1e12
static let cubicMeters = 1000.0
static let cubicDecimeters = 1.0
static let cubicCentimeters = 0.01
static let cubicMillimeters = 0.001
static let cubicInches = 0.0163871
static let cubicFeet = 28.3168
static let cubicYards = 764.555
static let cubicMiles = 4.168e+12
static let acreFeet = 1.233e+6
static let bushels = 35.2391
static let teaspoons = 0.00492892
static let tablespoons = 0.0147868
static let fluidOunces = 0.0295735
static let cups = 0.24
static let pints = 0.473176
static let quarts = 0.946353
static let gallons = 3.78541
static let imperialTeaspoons = 0.00591939
static let imperialTablespoons = 0.0177582
static let imperialFluidOunces = 0.0284131
static let imperialPints = 0.568261
static let imperialQuarts = 1.13652
static let imperialGallons = 4.54609
static let metricCups = 0.25
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
open class var megaliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.megaliters, coefficient: Coefficient.megaliters)
}
}
open class var kiloliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.kiloliters, coefficient: Coefficient.kiloliters)
}
}
open class var liters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.liters, coefficient: Coefficient.liters)
}
}
open class var deciliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.deciliters, coefficient: Coefficient.deciliters)
}
}
open class var centiliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.centiliters, coefficient: Coefficient.centiliters)
}
}
open class var milliliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.milliliters, coefficient: Coefficient.milliliters)
}
}
open class var cubicKilometers: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicKilometers, coefficient: Coefficient.cubicKilometers)
}
}
open class var cubicMeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMeters, coefficient: Coefficient.cubicMeters)
}
}
open class var cubicDecimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicDecimeters, coefficient: Coefficient.cubicDecimeters)
}
}
open class var cubicCentimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicCentimeters, coefficient: Coefficient.cubicCentimeters)
}
}
open class var cubicMillimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMillimeters, coefficient: Coefficient.cubicMillimeters)
}
}
open class var cubicInches: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicInches, coefficient: Coefficient.cubicInches)
}
}
open class var cubicFeet: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicFeet, coefficient: Coefficient.cubicFeet)
}
}
open class var cubicYards: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicYards, coefficient: Coefficient.cubicYards)
}
}
open class var cubicMiles: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMiles, coefficient: Coefficient.cubicMiles)
}
}
open class var acreFeet: UnitVolume {
get {
return UnitVolume(symbol: Symbol.acreFeet, coefficient: Coefficient.acreFeet)
}
}
open class var bushels: UnitVolume {
get {
return UnitVolume(symbol: Symbol.bushels, coefficient: Coefficient.bushels)
}
}
open class var teaspoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.teaspoons, coefficient: Coefficient.teaspoons)
}
}
open class var tablespoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.tablespoons, coefficient: Coefficient.tablespoons)
}
}
open class var fluidOunces: UnitVolume {
get {
return UnitVolume(symbol: Symbol.fluidOunces, coefficient: Coefficient.fluidOunces)
}
}
open class var cups: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cups, coefficient: Coefficient.cups)
}
}
open class var pints: UnitVolume {
get {
return UnitVolume(symbol: Symbol.pints, coefficient: Coefficient.pints)
}
}
open class var quarts: UnitVolume {
get {
return UnitVolume(symbol: Symbol.quarts, coefficient: Coefficient.quarts)
}
}
open class var gallons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.gallons, coefficient: Coefficient.gallons)
}
}
open class var imperialTeaspoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialTeaspoons, coefficient: Coefficient.imperialTeaspoons)
}
}
open class var imperialTablespoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialTablespoons, coefficient: Coefficient.imperialTablespoons)
}
}
open class var imperialFluidOunces: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialFluidOunces, coefficient: Coefficient.imperialFluidOunces)
}
}
open class var imperialPints: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialPints, coefficient: Coefficient.imperialPints)
}
}
open class var imperialQuarts: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialQuarts, coefficient: Coefficient.imperialQuarts)
}
}
open class var imperialGallons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialGallons, coefficient: Coefficient.imperialGallons)
}
}
open class var metricCups: UnitVolume {
get {
return UnitVolume(symbol: Symbol.metricCups, coefficient: Coefficient.metricCups)
}
}
open override class func baseUnit() -> UnitVolume {
return UnitVolume.liters
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitVolume else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
|
apache-2.0
|
b1cc841e1bf81acc032419f593056723
| 29.23839 | 520 | 0.589536 | 4.618903 | false | false | false | false |
icoderRo/SMAnimation
|
SMDemo/iOS-MVX/MVVM/TableView/MVVMController.swift
|
2
|
1526
|
//
// MVVMController.swift
// iOS-MVX
//
// Created by simon on 2017/3/2.
// Copyright © 2017年 simon. All rights reserved.
//
import UIKit
class MVVMController: UIViewController {
fileprivate lazy var mvvmVM: MVVMVM = {return $0}(MVVMVM())
fileprivate lazy var tableView: UITableView = {[unowned self] in
let tableView = UITableView(frame: self.view.bounds)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .yellow
tableView.rowHeight = 70
tableView.register(UINib(nibName: "MVVMCell", bundle: nil), forCellReuseIdentifier: "cellId")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "MVVMTableView"
view.addSubview(tableView)
mvvmVM.loadData()
mvvmVM.reloadData = {[weak self] in
self?.tableView.reloadData()
}
}
}
extension MVVMController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mvvmVM.models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
mvvmVM.setCell(cell!, indexPath.row)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
mit
|
d34266c7ebbd0e0670d9e708f91061c7
| 27.203704 | 101 | 0.644123 | 4.81962 | false | false | false | false |
ovyhlidal/Billingo
|
Billingo/DetailGroupViewController.swift
|
1
|
4275
|
//
// DerailGroupTableViewController.swift
// Billingo
//
// Created by Zuzana Plesingerova on 28.04.16.
// Copyright © 2016 MU. All rights reserved.
//
import UIKit
class DetailGroupViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let reuseIdentifier = "ExpenseCell"
let reuseIdentifierForAddExpenseSegue = "addExpenseSegue"
let reuseIdentifierForExpenseDetailSegue = "showExpenseDetail"
let reuseIdentifierForGroupStatisticsSegue = "showStatistics"
var expenses: Array = [Expense]()
var groupMembers: [Member]?
var myID: String?
var groupID: String?
var group: Group?
@IBOutlet weak var statisticButton: UIBarButtonItem!
@IBOutlet weak var tableView: UITableView!
@IBAction func backToGroupsView(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
if expenses.isEmpty {
statisticButton.enabled = false
}
let name = "Pattern~\("DetailGroupViewController")"
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: name)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == reuseIdentifierForExpenseDetailSegue {
if let indexPath = self.tableView.indexPathForCell(sender as! ExpenseTableViewCell) {
let expense = expenses[indexPath.row]
let nav = segue.destinationViewController as! UINavigationController
let controller = nav.topViewController as! DetailExpenseViewController
controller.expense = expense
}
}
if segue.identifier == reuseIdentifierForAddExpenseSegue {
let groupID: String = self.groupID!
let payerID: String = self.myID!
let controller = segue.destinationViewController as! AddExpenseViewController
controller.groupID = groupID
controller.payerID = payerID
controller.groupMembers = groupMembers
}
if segue.identifier == reuseIdentifierForGroupStatisticsSegue {
let group: Group = self.group!
let controller = segue.destinationViewController as! StatisticGroupViewController
controller.group = group
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return expenses.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ExpenseTableViewCell
let expense = expenses[indexPath.row]
cell.expenseName.text = expense.expenseName
let costAdapted = String(format: "%.2f", expense.cost)
cell.expenseCost.text = "Cost: " + String(costAdapted)
cell.numberOfExpenseMembers.text = " Members: " + String(expense.payments.count)
return cell
}
// MARK: - Table view data source
}
|
mit
|
d3057f4d8b518b096d640bf9f33f9757
| 37.504505 | 129 | 0.678521 | 5.465473 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Business/DataSource/ActionableTimeInfo.swift
|
1
|
3240
|
//
// StartingTimeInfo.swift
// YourGoals
//
// Created by André Claaßen on 22.06.19.
// Copyright © 2019 André Claaßen. All rights reserved.
//
import Foundation
/// a calculated time info with starting, end time and an indicator if this time is in a conflicting state
struct ActionableTimeInfo:Equatable, ActionableItem {
/// state of this item
///
/// - open: the task is open but not progressing
/// - progressing: the task is currently progressing
/// - done: the task is done
/// - progress: this is a done task progress entry
enum State {
case open
case progressing
case progress
case done
func asString() -> String {
switch self {
case .progress: return "Progress"
case .progressing: return "Progressing"
case .open: return "Open"
case .done: return "Done"
}
}
}
/// the estimated starting time (not date) of an actionable
let startingTime:Date
/// the estimated ending time
let endingTime:Date
/// the estimated time left for the task as a timeinterval
let estimatedLength:TimeInterval
/// the start of this time is in danger cause of the previous task is being late
let conflicting: Bool
/// indicator, if the starting time is fixed
let fixedStartingTime: Bool
/// the actionable for this time info
let actionable:Actionable
/// an optional progress, if this time info is corresponding with a done task progress
let progress:TaskProgress?
/// calculate the state for the time info
///
/// - Parameter forDate: the date/time for the calculating
/// - Returns: a state
func state(forDate date: Date) -> State {
if progress != nil {
return .progress
}
if actionable.isProgressing(atDate: date) {
return .progressing
}
let actionableState = actionable.checkedState(forDate: date)
switch actionableState {
case .active:
return .open
case .done:
return .done
}
}
static func == (lhs: ActionableTimeInfo, rhs: ActionableTimeInfo) -> Bool {
return
lhs.startingTime == rhs.startingTime &&
lhs.endingTime == rhs.endingTime &&
lhs.estimatedLength == rhs.estimatedLength &&
lhs.actionable.name == rhs.actionable.name
}
/// initalize this time info
///
/// - Parameters:
/// - start: starting time
/// - estimatedLength: remaining time
/// - conflicting: actionable is conflicting with another actionable
/// - fixed: indicator if starting time is fixed
init(start:Date, end:Date, remainingTimeInterval:TimeInterval, conflicting: Bool, fixed: Bool, actionable: Actionable, progress: TaskProgress? = nil) {
self.startingTime = start.extractTime()
self.endingTime = end.extractTime()
self.estimatedLength = remainingTimeInterval
self.conflicting = conflicting
self.fixedStartingTime = fixed
self.actionable = actionable
self.progress = progress
}
}
|
lgpl-3.0
|
2869fdc7491507e4f84d7fbf82af9861
| 30.715686 | 155 | 0.616692 | 4.828358 | false | false | false | false |
anzfactory/QiitaCollection
|
QiitaCollection/QiitaAccount.swift
|
1
|
4049
|
//
// QiitaAccount.swift
// QiitaCollection
//
// Created by ANZ on 2015/03/23.
// Copyright (c) 2015年 anz. All rights reserved.
//
import UIKit
class QiitaAccount: OtherAccount {
private var qiitaId: String = "";
override init() {
super.init()
self.qiitaId = userDataManager.qiitaAuthenticatedUserID
if self.qiitaId.isEmpty {
fatalError("not authorized user...")
}
}
override func signin(code: String, completion: (qiitaAccount: QiitaAccount) -> Void) {
completion(qiitaAccount: self);
}
override func signout(completion: (anonymous: AnonymousAccount?) -> Void) {
self.qiitaApiManager.deleteAccessToken(UserDataManager.sharedInstance.qiitaAccessToken, completion: { (isError) -> Void in
if isError {
completion(anonymous: nil)
return
}
UserDataManager.sharedInstance.clearQiitaAccessToken()
let anonymus: AnonymousAccount = AnonymousAccount()
completion(anonymous: anonymus)
})
}
func isSelf(userId: String) -> Bool {
return self.qiitaId == userId
}
override func sync(completion: (user: UserEntity?) -> Void) {
self.qiitaApiManager.getAuthenticatedUser({ (item, isError) -> Void in
if item != nil {
self.userDataManager.qiitaAuthenticatedUserID = item!.id
}
completion(user: item)
return
})
}
func entries(page:Int, completion: (total: Int, entries: [EntryEntity]) -> Void) {
self.qiitaApiManager.getAuthenticatedUserItems(page, completion: { (total, items, isError) -> Void in
if isError {
completion(total: total, entries: [EntryEntity]())
return
}
completion(total: total, entries: items)
})
}
func isFollowed(userId: String, completion: (followed: Bool) -> Void ) {
self.qiitaApiManager.getUserFollowing(userId, completion: completion)
}
func follow(userId: String, completion: (isError: Bool) -> Void) {
self.qiitaApiManager.putUserFollowing(userId, completion: completion)
}
func cancelFollow(userId: String, completion: (isError: Bool) -> Void) {
self.qiitaApiManager.deleteUserFollowing(userId, completion: completion)
}
func canFollow(userId: String) -> Bool {
return self.qiitaId != userId
}
func canCommentEdit(authorId: String) -> Bool {
// 認証済みでかつ認証ユーザーがコメント投稿ユーザーの場合
// 記事事態の所有者なら、他人のコメントも消せるかとおもったけどwebでは無理っぽいので
// とりあえず認証ユーザー=投稿ユーザーだけで
return authorId == self.qiitaId
}
func comment(entryId:String, text: String, completion: (isError: Bool) -> Void) {
self.qiitaApiManager.postComment(entryId, body: text, completion: completion)
}
func commentEdit(commentId: String, text: String, completion:(isError: Bool) -> Void) {
self.qiitaApiManager.patchComment(commentId, body: text, completion: completion)
}
func deleteComment(commentId: String, completion: (isError: Bool) -> Void) {
self.qiitaApiManager.deleteComment(commentId, completion: completion)
}
func isStocked(entryId: String, completion: (stocked: Bool) -> Void) {
self.qiitaApiManager.getItemStock(entryId, completion: completion)
}
func stock(entryId:String, completion: (isError: Bool) -> Void) {
QiitaApiManager.sharedInstance.putItemStock(entryId, completion: completion)
}
func cancelStock(entryId: String, completion: (isError: Bool) -> Void) {
self.qiitaApiManager.deleteItemStock(entryId, completion: completion)
}
}
|
mit
|
62249517312aa9c67522af4cdbab20b8
| 32.387931 | 130 | 0.616576 | 4.332215 | false | false | false | false |
shu223/ARKit-Sampler
|
common/Common.swift
|
1
|
4176
|
//
// Common.swift
//
// Created by Shuichi Tsutsumi on 2017/09/20.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
import SceneKit.ModelIO
extension UIColor {
class var arBlue: UIColor {
get {
return UIColor(red: 0.141, green: 0.540, blue: 0.816, alpha: 1)
}
}
}
extension ARSession {
func run() {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.isLightEstimationEnabled = true
run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
}
extension SCNNode {
class func sphereNode(color: UIColor) -> SCNNode {
let geometry = SCNSphere(radius: 0.01)
geometry.materials.first?.diffuse.contents = color
return SCNNode(geometry: geometry)
}
class func textNode(text: String) -> SCNNode {
let geometry = SCNText(string: text, extrusionDepth: 0.01)
geometry.alignmentMode = convertFromCATextLayerAlignmentMode(CATextLayerAlignmentMode.center)
if let material = geometry.firstMaterial {
material.diffuse.contents = UIColor.white
material.isDoubleSided = true
}
let textNode = SCNNode(geometry: geometry)
geometry.font = UIFont.systemFont(ofSize: 1)
textNode.scale = SCNVector3Make(0.02, 0.02, 0.02)
// Translate so that the text node can be seen
let (min, max) = geometry.boundingBox
textNode.pivot = SCNMatrix4MakeTranslation((max.x - min.x)/2, min.y - 0.5, 0)
// Always look at the camera
let node = SCNNode()
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = SCNBillboardAxis.Y
node.constraints = [billboardConstraint]
node.addChildNode(textNode)
return node
}
class func lineNode(length: CGFloat, color: UIColor) -> SCNNode {
let geometry = SCNCapsule(capRadius: 0.004, height: length)
geometry.materials.first?.diffuse.contents = color
let line = SCNNode(geometry: geometry)
let node = SCNNode()
node.eulerAngles = SCNVector3Make(Float.pi/2, 0, 0)
node.addChildNode(line)
return node
}
func loadScn(name: String, inDirectory directory: String) {
guard let scene = SCNScene(named: "\(name).scn", inDirectory: directory) else { fatalError() }
for child in scene.rootNode.childNodes {
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
addChildNode(child)
}
}
func loadUsdz(name: String) {
guard let url = Bundle.main.url(forResource: name, withExtension: "usdz") else { fatalError() }
let scene = try! SCNScene(url: url, options: [.checkConsistency: true])
for child in scene.rootNode.childNodes {
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
addChildNode(child)
}
}
}
extension SCNView {
private func enableEnvironmentMapWithIntensity(_ intensity: CGFloat) {
if scene?.lightingEnvironment.contents == nil {
if let environmentMap = UIImage(named: "models.scnassets/sharedImages/environment_blur.exr") {
scene?.lightingEnvironment.contents = environmentMap
}
}
scene?.lightingEnvironment.intensity = intensity
}
func updateLightingEnvironment(for frame: ARFrame) {
// If light estimation is enabled, update the intensity of the model's lights and the environment map
let intensity: CGFloat
if let lightEstimate = frame.lightEstimate {
intensity = lightEstimate.ambientIntensity / 400
} else {
intensity = 2
}
DispatchQueue.main.async(execute: {
self.enableEnvironmentMapWithIntensity(intensity)
})
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromCATextLayerAlignmentMode(_ input: CATextLayerAlignmentMode) -> String {
return input.rawValue
}
|
mit
|
e8f93194b7c2985170213a6360af33d4
| 32.669355 | 109 | 0.648144 | 4.592959 | false | false | false | false |
iAugux/iBBS-Swift
|
iBBS/Additions/PanDirectionGestureRecognizer+Addtions.swift
|
1
|
1156
|
//
// PanDirectionGestureRecognizer+Addtions.swift
// TinderSwipeCellSwift
//
// Created by Augus on 8/23/15.
// Copyright © 2015 iAugus. All rights reserved.
// http://stackoverflow.com/a/30607392/4656574
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum PanDirection {
case Vertical
case Horizontal
}
class PanDirectionGestureRecognizer: UIPanGestureRecognizer {
let direction : PanDirection
init(direction: PanDirection, target: AnyObject, action: Selector) {
self.direction = direction
super.init(target: target, action: action)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if state == .Began {
let velocity = velocityInView(self.view!)
switch direction {
case .Horizontal where fabs(velocity.y) > fabs(velocity.x):
state = .Cancelled
case .Vertical where fabs(velocity.x) > fabs(velocity.y):
state = .Cancelled
default:
break
}
}
}
}
|
mit
|
5941ece0656ad726c51e675e68220fea
| 26.52381 | 81 | 0.625974 | 4.714286 | false | false | false | false |
cs-joao-souza/JPAlertController
|
JPAlertController/ViewController.swift
|
1
|
2582
|
//
// ViewController.swift
// JPAlertController
//
// Created by Joao Souza on 24/03/17.
// Copyright © 2017 JoaoSouza. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showAlert(_ sender: Any) {
let titleOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)!, NSForegroundColorAttributeName: UIColor.blue ]
let messageOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 14.0)!, NSForegroundColorAttributeName: UIColor.red ]
let alert = JPAlertController(title: "Alert", message: "This is a customizable Alert", titleOptions: titleOptions, messageOptions: messageOptions)
let okAction = JPAlertAction(title: "OK", titleOptions: titleOptions) { action in
print("OK action")
}
alert.addAction(action: okAction)
let cancelOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 14.0)!, NSForegroundColorAttributeName: UIColor.red ]
let cancelAction = JPAlertAction(title: "Cancel", titleOptions: cancelOptions) { action in
print("Cancel action")
}
alert.addAction(action: cancelAction)
self.present(alert, animated: true, completion: nil)
}
@IBAction func showAlertWithThreeButtons(_ sender: Any) {
let titleOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)!, NSForegroundColorAttributeName: UIColor.blue ]
let messageOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 14.0)!, NSForegroundColorAttributeName: UIColor.red ]
let alert = JPAlertController(title: "Alert", message: "This is a JPAlertController. You can customize font, color and everything that an AttributedString accept. Just send the attributed string options in the constructor.", titleOptions: titleOptions, messageOptions: messageOptions)
let firstAction = JPAlertAction(title: "One", titleOptions: titleOptions, handler: nil)
alert.addAction(action: firstAction)
let secondOptions = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 14.0)!, NSForegroundColorAttributeName: UIColor.red ]
let secondAction = JPAlertAction(title: "Two", titleOptions: secondOptions, handler: nil)
alert.addAction(action: secondAction)
let thirdAction = JPAlertAction(title: "Third", titleOptions: nil, handler: nil)
alert.addAction(action: thirdAction)
self.present(alert, animated: true, completion: nil)
}
}
|
mit
|
68433d3b523bf6102ab9fd5a354dddb8
| 35.871429 | 288 | 0.711352 | 4.658845 | false | false | false | false |
cho15255/PaintWithMetal
|
PaintWithMetal/JHViewController.swift
|
1
|
3934
|
//
// JHViewController.swift
// PaintWithMetal
//
// Created by Jae Hee Cho on 2015-11-29.
// Copyright © 2015 Jae Hee Cho. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
class JHViewController: UIViewController {
// Metal related fields
var device: MTLDevice! = nil
var metalLayer: CAMetalLayer! = nil
var pipelineState: MTLRenderPipelineState! = nil
var commandQueue: MTLCommandQueue! = nil
var timer: CADisplayLink! = nil
var renderPassDescriptor: MTLRenderPassDescriptor! = nil
var bufferCleared = 0
var didTouchEnded = 0
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var redButton: UIBarButtonItem!
@IBOutlet weak var yellowButton: UIBarButtonItem!
@IBOutlet weak var greenButton: UIBarButtonItem!
@IBOutlet weak var blueButton: UIBarButtonItem!
@IBOutlet weak var blackButton: UIBarButtonItem!
@IBOutlet weak var clearButton: UIBarButtonItem!
// Coordinate constants for z and w axis (used for 3D rendering in Metal)
let metalZCoordinate:Float = 0
let metalWCoordinate:Float = 1
// Stroke(vertex) information
var prevVertex:CGPoint!
var prevRadius:CGFloat!
var vertexData:Array<Float> = []
var vertexBuffer:MTLBuffer!
var colorData:Array<Float> = []
var colorBuffer:MTLBuffer!
var currentColor:UIColor!
override func viewDidLoad() {
super.viewDidLoad()
self.currentColor = UIColor.blackColor()
self.device = MTLCreateSystemDefaultDevice()
self.metalLayer = CAMetalLayer()
self.metalLayer.device = self.device
self.metalLayer.pixelFormat = .BGRA8Unorm
self.metalLayer.framebufferOnly = true
self.metalLayer.frame = self.view.frame
self.view.layer.insertSublayer(self.metalLayer, below: self.toolbar.layer)
self.commandQueue = self.device.newCommandQueue()
let defaultLibrary = self.device.newDefaultLibrary()
let fragmentProgram = defaultLibrary?.newFunctionWithName("basic_fragment")
let vertexProgram = defaultLibrary?.newFunctionWithName("basic_vertex")
let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
pipelineStateDescriptor.vertexFunction = vertexProgram
pipelineStateDescriptor.fragmentFunction = fragmentProgram
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm
do {
try self.pipelineState = self.device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor)
} catch {
if self.pipelineState == nil {
print("Something's wrong with pipelinestate initialization")
}
}
self.timer = CADisplayLink(target: self, selector: Selector("gameLoop"))
self.timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
self.view.multipleTouchEnabled = false
self.view.userInteractionEnabled = true
}
@IBAction func redButtonTapped(sender: AnyObject) {
self.currentColor = UIColor.redColor()
}
@IBAction func yellowButtonTapped(sender: AnyObject) {
self.currentColor = UIColor.yellowColor()
}
@IBAction func greenButtonTapped(sender: AnyObject) {
self.currentColor = UIColor.greenColor()
}
@IBAction func blueButtonTapped(sender: AnyObject) {
self.currentColor = UIColor.blueColor()
}
@IBAction func blackButtonTapped(sender: AnyObject) {
self.currentColor = UIColor.blackColor()
}
@IBAction func clearButtonTapped(sender: AnyObject) {
self.bufferCleared = 0
self.prevVertex = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
2e5694260ea1c2b825c3469312e4a125
| 32.05042 | 110 | 0.676329 | 5.230053 | false | false | false | false |
digiscend/ios-data-app
|
App/DetailViewController.swift
|
1
|
1129
|
//
// DetailViewController.swift
// App
//
// Created by Vikas Yadav on 05/08/16.
// Copyright (c) 2016 Digiscend. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var nameLabel: UITextField!
@IBOutlet weak var introView: UITextView!
var detailItem: Project? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: Project = self.detailItem {
if let label = self.nameLabel {
label.text = detail.name
}
if let notes = self.introView {
notes.text = detail.intro
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
gpl-3.0
|
029a48a5b98a3de2638aa7a00761680a
| 22.520833 | 80 | 0.582817 | 4.804255 | false | true | false | false |
skedgo/tripkit-ios
|
Sources/TripKitUI/cards/TKUITimetableCard+Content.swift
|
1
|
4076
|
//
// TKUITimetableCard+Content.swift
// TripKitUI
//
// Created by Kuan Lun Huang on 28/3/19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import RxSwift
import TripKit
extension TKUIDepartureCellContent {
static func build(embarkation: StopVisits, disembarkation: StopVisits? = nil) -> TKUIDepartureCellContent? {
guard let service = (embarkation.service as Service?) else {
return nil
}
// Note, for DLS entries `disembarkation` will be nil, but the accessibility
// is already handled then under `disembarkation`.
var accessibility = embarkation.wheelchairAccessibility
if let atEnd = disembarkation?.wheelchairAccessibility {
accessibility = accessibility.combine(with: atEnd)
}
let serviceColor = service.color
return TKUIDepartureCellContent(
placeholderImage: service.modeImage(for: .listMainMode),
imageURL: service.modeImageURL(for: .listMainMode),
imageIsTemplate: service.modeImageIsTemplate,
imageTintColor: TKUICustomization.shared.colorCodeTransitIcons ? serviceColor : nil,
modeName: service.modeTitle ?? "",
serviceShortName: service.shortIdentifier,
serviceColor: serviceColor,
serviceIsCanceled: service.isCanceled,
accessibilityLabel: embarkation.accessibilityDescription(includeRealTime: true),
accessibilityTimeText: embarkation.buildTimeText(spacer: ";").string,
timeText: embarkation.buildTimeText(),
lineText: embarkation.buildLineText(),
approximateTimeToDepart: embarkation.countdownDate,
wheelchairAccessibility: accessibility,
alerts: service.allAlerts(),
vehicleComponents: service.vehicle?.rx.components
)
}
}
// MARK: -
extension StopVisits {
/// Time to count down to in a departures timetable. This is `nil` for frequency-based services, or if this is the final arrival at a stop.
var countdownDate: Date? {
service.frequency == nil ? departure : nil
}
fileprivate func buildTimeText(spacer: String = "·") -> NSAttributedString {
var text = realTimeInformation(withOriginalTime: false) + " \(spacer) "
// Frequency based service
switch timing {
case .frequencyBased(let frequency, let start, let end, _):
let freqString = Date.durationString(forMinutes: Int(frequency / 60))
text += Loc.Every(repetition: freqString)
if let start = start, let end = end {
let timeZone = stop.timeZone
text += " \(spacer) "
text += TKStyleManager.timeString(start, for: timeZone)
text += " - "
text += TKStyleManager.timeString(end, for: timeZone)
}
case .timetabled(let arrival, let departure):
let timeZone = stop.timeZone
var departureString = ""
if let departureDate = departure {
departureString = TKStyleManager.timeString(departureDate, for: timeZone)
}
if self is DLSEntry {
// time-table
if !departureString.isEmpty {
text += departureString
}
var arrivalString = ""
if let arrivalDate = arrival {
arrivalString = TKStyleManager.timeString(arrivalDate, for: timeZone)
}
if !arrivalString.isEmpty {
text += String(format: " - %@", arrivalString)
}
} else if !departureString.isEmpty {
text += departureString
}
}
let color = realTimeStatus.color
return NSAttributedString(string: text, attributes: [.foregroundColor: color])
}
fileprivate func buildLineText() -> String? {
var text = ""
// platforms
if let standName = departurePlatform {
if !text.isEmpty {
text += " ⋅ "
}
text += standName
}
// direction
if let direction = service.direction?.trimmingCharacters(in: .whitespaces), !direction.isEmpty {
if !text.isEmpty {
text += " ⋅ "
}
text += direction
}
return text.isEmpty ? nil : text
}
}
|
apache-2.0
|
d96906c9ae4960ac307701ce2abd2db5
| 29.601504 | 141 | 0.652826 | 4.472527 | false | false | false | false |
wangjianquan/wjKeyBoard
|
wjKeyBoard/Emotion/UITextView - Extension.swift
|
1
|
2706
|
//
// UITextView - Extension.swift
// EmotionDemo
//
// Created by landixing on 2017/6/9.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
extension UITextView {
/// 获取textView属性字符串,对应的表情字符串
func getEmoticonString() -> String {
// 1.获取属性字符串
let attrMStr = NSMutableAttributedString(attributedString: attributedText)
// 2.遍历属性字符串
let range = NSRange(location: 0, length: attrMStr.length)
attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) -> Void in
if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
attrMStr.replaceCharacters(in: range, with: attachment.chs!)
}
}
// 3.获取字符串
return attrMStr.string
}
/// 给textView插入表情
func insertEmoticon(_ emoticon : EmotionModel) {
// 1.空白表情
if emoticon.isEmpty {
return
}
// 2.删除按钮
if emoticon.isRemove {
deleteBackward()
return
}
// 3.emoji表情
if emoticon.emojiCode != nil {
// 3.1.获取光标所在的位置:UITextRange
let textRange = selectedTextRange!
// 3.2.替换emoji表情
replace(textRange, withText: emoticon.emojiCode!)
return
}
// 4.普通表情:图文混排
// 4.1.根据图片路径创建属性字符串
let attachment = EmoticonAttachment()
attachment.chs = emoticon.chs
attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
guard let font = self.font else { return }
attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
let attrImageStr = NSAttributedString(attachment: attachment)
// 4.2.创建可变的属性字符串
let attrMStr = NSMutableAttributedString(attributedString: attributedText)
// 4.3.将图片属性字符串,替换到可变属性字符串的某一个位置
// 4.3.1.获取光标所在的位置
let range = selectedRange
// 4.3.2.替换属性字符串
attrMStr.replaceCharacters(in: range, with: attrImageStr)
// 显示属性字符串
attributedText = attrMStr
// 将文字的大小重置
self.font = font
// 将光标设置回原来位置 + 1
selectedRange = NSRange(location: range.location + 1, length: 0)
}
}
|
apache-2.0
|
edeaabf88b6b9eb93b6b64794daafcd6
| 25.820225 | 96 | 0.555509 | 4.363803 | false | false | false | false |
jmgc/swift
|
test/SourceKit/CursorInfo/cursor_stdlib.swift
|
1
|
11307
|
import Foundation
var x = NSUTF8StringEncoding
var d : AnyIterator<Int>
func foo1(_ a : inout [Int]) {
a = a.sorted()
a.append(1)
}
struct S1 {}
func foo2(_ a : inout [S1]) {
a = a.sorted(by: { (a, b) -> Bool in
return false
})
a.append(S1())
}
import Swift
func foo3(a: Float, b: Bool) {}
// REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %sourcekitd-test -req=cursor -pos=3:18 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-OVERLAY %s
// CHECK-OVERLAY: source.lang.swift.ref.var.global
// CHECK-OVERLAY-NEXT: NSUTF8StringEncoding
// CHECK-OVERLAY-NEXT: s:10Foundation20NSUTF8StringEncodingSuv
// CHECK-OVERLAY-NEXT: UInt
// CHECK-OVERLAY-NEXT: $sSuD
// CHECK-OVERLAY-NEXT: Foundation
// CHECK-OVERLAY-NEXT: SYSTEM
// CHECK-OVERLAY-NEXT: <Declaration>let NSUTF8StringEncoding: <Type usr="s:Su">UInt</Type></Declaration>
// RUN: %sourcekitd-test -req=cursor -pos=5:13 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-ITERATOR %s
// CHECK-ITERATOR-NOT: _AnyIteratorBase
// CHECK-ITERATOR: <Group>Collection/Type-erased</Group>
// RUN: %sourcekitd-test -req=cursor -pos=8:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT1 %s
// CHECK-REPLACEMENT1: <Group>Collection/Array</Group>
// CHECK-REPLACEMENT1: <Declaration>{{.*}}func sorted() -> [<Type usr="s:Si">Int</Type>]</Declaration>
// CHECK-REPLACEMENT1: RELATED BEGIN
// CHECK-REPLACEMENT1: sorted(by:)</RelatedName>
// CHECK-REPLACEMENT1: RELATED END
// RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT2 %s
// CHECK-REPLACEMENT2: <Group>Collection/Array</Group>
// CHECK-REPLACEMENT2: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:Si">Int</Type>)</Declaration>
// RUN: %sourcekitd-test -req=cursor -pos=15:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT3 %s
// CHECK-REPLACEMENT3: <Group>Collection/Array</Group>
// CHECK-REPLACEMENT3: func sorted(by areInIncreasingOrder: (<Type usr="s:13cursor_stdlib2S1V">S1</Type>
// CHECK-REPLACEMENT3: sorted()</RelatedName>
// RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=18:8 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT4 %s
// CHECK-REPLACEMENT4: <Group>Collection/Array</Group>
// CHECK-REPLACEMENT4: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:13cursor_stdlib2S1V">S1</Type>)</Declaration>
// CHECK-REPLACEMENT4: SYMBOL GRAPH BEGIN
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "module": {
// CHECK-REPLACEMENT4: "name": "Swift",
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "relationships": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "memberOf",
// CHECK-REPLACEMENT4: "source": "s:Sa6appendyyxnF",
// CHECK-REPLACEMENT4: "target": "s:Sa"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "symbols": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "accessLevel": "public",
// CHECK-REPLACEMENT4: "declarationFragments": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "keyword",
// CHECK-REPLACEMENT4: "spelling": "mutating"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": " "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "keyword",
// CHECK-REPLACEMENT4: "spelling": "func"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": " "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "identifier",
// CHECK-REPLACEMENT4: "spelling": "append"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": "("
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "externalParam",
// CHECK-REPLACEMENT4: "spelling": "_"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": " "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "internalParam",
// CHECK-REPLACEMENT4: "spelling": "newElement"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": ": "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "typeIdentifier",
// CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V",
// CHECK-REPLACEMENT4: "spelling": "S1"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": ")"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "docComment": {
// CHECK-REPLACEMENT4: "lines": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "text": "Adds a new element at the end of the array."
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: ]
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "functionSignature": {
// CHECK-REPLACEMENT4: "parameters": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "declarationFragments": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "identifier",
// CHECK-REPLACEMENT4: "spelling": "newElement"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": ": "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "typeIdentifier",
// CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V",
// CHECK-REPLACEMENT4: "spelling": "S1"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "name": "newElement"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "returns": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": "()"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ]
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "identifier": {
// CHECK-REPLACEMENT4: "interfaceLanguage": "swift",
// CHECK-REPLACEMENT4: "precise": "s:Sa6appendyyxnF"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "kind": {
// CHECK-REPLACEMENT4: "displayName": "Instance Method",
// CHECK-REPLACEMENT4: "identifier": "swift.method"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "names": {
// CHECK-REPLACEMENT4: "navigator": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "keyword",
// CHECK-REPLACEMENT4: "spelling": "func"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": " "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "identifier",
// CHECK-REPLACEMENT4: "spelling": "append"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": "("
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "typeIdentifier",
// CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V",
// CHECK-REPLACEMENT4: "spelling": "S1"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": ")"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "subHeading": [
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "keyword",
// CHECK-REPLACEMENT4: "spelling": "func"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": " "
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "identifier",
// CHECK-REPLACEMENT4: "spelling": "append"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": "("
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "typeIdentifier",
// CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V",
// CHECK-REPLACEMENT4: "spelling": "S1"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: {
// CHECK-REPLACEMENT4: "kind": "text",
// CHECK-REPLACEMENT4: "spelling": ")"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "title": "append(_:)"
// CHECK-REPLACEMENT4: },
// CHECK-REPLACEMENT4: "pathComponents": [
// CHECK-REPLACEMENT4: "Array",
// CHECK-REPLACEMENT4: "append(_:)"
// CHECK-REPLACEMENT4: ],
// CHECK-REPLACEMENT4: "swiftExtension": {
// CHECK-REPLACEMENT4: "extendedModule": "Swift"
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: ]
// CHECK-REPLACEMENT4: }
// CHECK-REPLACEMENT4: SYMBOL GRAPH END
// RUN: %sourcekitd-test -req=cursor -pos=21:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-MODULE-GROUP1 %s
// CHECK-MODULE-GROUP1: MODULE GROUPS BEGIN
// CHECK-MODULE-GROUP1-DAG: Math
// CHECK-MODULE-GROUP1-DAG: Collection
// CHECK-MODULE-GROUP1-DAG: Collection/Array
// CHECK-MODULE-GROUP1: MODULE GROUPS END
// RUN: %sourcekitd-test -req=cursor -pos=22:17 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-FLOAT1 %s
// CHECK-FLOAT1: s:Sf
// RUN: %sourcekitd-test -req=cursor -pos=22:25 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-BOOL1 %s
// CHECK-BOOL1: s:Sb
|
apache-2.0
|
0f81857b7781c629519d67d254d0f3c2
| 44.047809 | 196 | 0.592995 | 3.529026 | false | false | false | false |
shmidt/StyleItTest
|
StyleItTest/FileUploader.swift
|
1
|
3944
|
//
// FileUploader.swift
//
// Copyright (c) 2015 Narciso Cerezo Jiménez. All rights reserved.
// Largely based on this stackoverflow question: http://stackoverflow.com/questions/26121827/uploading-file-with-parameters-using-alamofire/28467829//
import Foundation
import Alamofire
private struct FileUploadInfo {
var name:String
var mimeType:String
var fileName:String
var url:NSURL?
var data:NSData?
init( name: String, withFileURL url: NSURL, withMimeType mimeType: String? = nil ) {
self.name = name
self.url = url
self.fileName = name
self.mimeType = "application/octet-stream"
if mimeType != nil {
self.mimeType = mimeType!
}
if let _name = url.lastPathComponent {
fileName = _name
}
if mimeType == nil, let _extension = url.pathExtension {
switch _extension.lowercaseString {
case "jpeg", "jpg":
self.mimeType = "image/jpeg"
case "png":
self.mimeType = "image/png"
default:
self.mimeType = "application/octet-stream"
}
}
}
init( name: String, withData data: NSData, withMimeType mimeType: String ) {
self.name = name
self.data = data
self.fileName = name
self.mimeType = mimeType
}
}
class FileUploader {
private var parameters = [String:String]()
private var files = [FileUploadInfo]()
private var headers = [String:String]()
func setValue( value: String, forParameter parameter: String ) {
parameters[parameter] = value
}
func setValue( value: String, forHeader header: String ) {
headers[header] = value
}
func addParametersFrom( #map: [String:String] ) {
for (key,value) in map {
parameters[key] = value
}
}
func addHeadersFrom( #map: [String:String] ) {
for (key,value) in map {
headers[key] = value
}
}
func addFileURL( url: NSURL, withName name: String, withMimeType mimeType:String? = nil ) {
files.append( FileUploadInfo( name: name, withFileURL: url, withMimeType: mimeType ) )
}
func addFileData( data: NSData, withName name: String, withMimeType mimeType:String = "application/octet-stream" ) {
files.append( FileUploadInfo( name: name, withData: data, withMimeType: mimeType ) )
}
func uploadFile( request sourceRequest: NSURLRequest ) -> Request? {
var request = sourceRequest.mutableCopy() as! NSMutableURLRequest
let boundary = "FileUploader-boundary-\(arc4random())-\(arc4random())"
request.setValue( "multipart/form-data;boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let data = NSMutableData()
for (name, value) in headers {
request.setValue(value, forHTTPHeaderField: name)
}
// Amazon S3 (probably others) wont take parameters after files, so we put them first
for (key, value) in parameters {
data.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
for fileUploadInfo in files {
data.appendData( "\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)! )
data.appendData( "Content-Disposition: form-data; name=\"\(fileUploadInfo.name)\"; filename=\"\(fileUploadInfo.fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendData( "Content-Type: \(fileUploadInfo.mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
if fileUploadInfo.data != nil {
data.appendData( fileUploadInfo.data! )
}
else if fileUploadInfo.url != nil, let fileData = NSData(contentsOfURL: fileUploadInfo.url!) {
data.appendData( fileData )
}
else { // ToDo: report error
return nil
}
}
data.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return Alamofire.upload( request, data )
}
}
|
mit
|
59a8d42e1435ee4a130712a5f99f521c
| 31.595041 | 175 | 0.667258 | 4.069143 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/Toolbox/Gacha/Detail/View/GachaCardView.swift
|
1
|
1462
|
//
// GachaCardView.swift
// DereGuide
//
// Created by zzk on 2017/7/17.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
class GachaCardView: UIView {
var icon: CGSSCardIconView
var oddsLabel: UILabel
override init(frame: CGRect) {
icon = CGSSCardIconView()
oddsLabel = UILabel()
oddsLabel.adjustsFontSizeToFitWidth = true
oddsLabel.font = UIFont.systemFont(ofSize: 12)
oddsLabel.textColor = Color.vocal
super.init(frame: frame)
addSubview(oddsLabel)
addSubview(icon)
oddsLabel.snp.makeConstraints { (make) in
make.centerX.bottom.equalToSuperview()
make.left.greaterThanOrEqualToSuperview()
make.right.lessThanOrEqualToSuperview()
make.bottom.equalToSuperview()
}
icon.snp.makeConstraints { (make) in
make.right.left.top.equalToSuperview()
make.height.equalTo(snp.width)
make.bottom.equalTo(oddsLabel.snp.top)
}
}
func setupWith(card: CGSSCard, odds: Int?) {
icon.cardID = card.id
if let odds = odds, odds != 0 {
oddsLabel.text = String(format: "%.3f%%", Double(odds / 10) / 1000)
} else {
oddsLabel.text = "n/a"
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
58af359bfa815d832899f91d85bec6b3
| 26.528302 | 79 | 0.585332 | 4.266082 | false | false | false | false |
SmallwolfiOS/ChangingToSwift
|
ChangingToSwift02/ChangingToSwift02/CameraViewController.swift
|
1
|
5065
|
//
// CameraViewController.swift
// ChangingToSwift02
//
// Created by Jason on 16/6/2.
// Copyright © 2016年 Jason. All rights reserved.
//
import UIKit
import MobileCoreServices
class CameraViewController: UIViewController ,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
@IBOutlet weak var cameraBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
var pickerVC:UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
ininPickerViewController()
}
//MARK:点击按钮的事件初始化
@IBAction func cameraAction(sender: UIButton) {
pickerVC.mediaTypes = [kUTTypeImage as String]//设定拍照的媒体类型
pickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo //设置摄像头捕捉模式为捕捉图片
presentViewController(pickerVC, animated: true, completion: nil)
}
@IBAction func vedioBtnAction(sender: UIButton){
pickerVC.mediaTypes = [kUTTypeMovie as String]//设定录像的媒体类型
pickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video //设置摄像头捕捉模式为捕捉图片
pickerVC.videoQuality = UIImagePickerControllerQualityType.TypeHigh //设置视频质量为高清
presentViewController(pickerVC, animated: true, completion: nil)
}
//MARK:初始化拾取控制器
func ininPickerViewController() {
pickerVC = UIImagePickerController.init() //继承自UINavigationController
pickerVC.sourceType = UIImagePickerControllerSourceType.Camera //设置拾取源为摄像头
pickerVC.cameraDevice = UIImagePickerControllerCameraDevice.Rear //设置摄像头为后置
pickerVC.editing = true;//设置运行编辑,即可以点击一些拾取控制器的控件
pickerVC.delegate = self//设置代理、
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:/* 拍照或录像成功,都会调用 */
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as!String//从info取出此时摄像头的媒体类型
if mediaType == kUTTypeImage as String{//如果是拍照
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//保存图像到相簿
UIImageWriteToSavedPhotosAlbum(image, self, #selector(CameraViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}else if mediaType == kUTTypeMovie as String {
let url = info[UIImagePickerControllerMediaURL] as! NSURL
let path = url.path!
//判断能不能保存到相簿
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) {
//保存到相簿
UISaveVideoAtPathToSavedPhotosAlbum(path, self, #selector(CameraViewController.vedio(_:didFinishSavingWithError:contextInfo:)), nil)
}else{
print("无法保存录像到相册")
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>){
if (error as NSError?) != nil {
print(error)
}else{
let ALertVC = UIAlertController.init(title: "保存成功", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
ALertVC.addAction(UIAlertAction.init(title: "确定", style: UIAlertActionStyle.Default, handler:{
action in
print("保存成功了")
self.imageView.image = image
}))
presentViewController(ALertVC, animated: true, completion: nil)
}
}
func vedio(videoPath: String, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>){
if (error as NSError?) != nil {
print(error)
}else{
let ALertVC = UIAlertController.init(title: "保存录像成功", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
ALertVC.addAction(UIAlertAction.init(title: "确定", style: UIAlertActionStyle.Default, handler:{
action in
print("保存录像成功了")
// self.imageView.image = image
}))
presentViewController(ALertVC, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
b21c32152b49355a9043c686861b5c7f
| 40.873874 | 148 | 0.672117 | 4.997849 | false | false | false | false |
billdonner/sheetcheats9
|
sc9/OpeningAnimations/HolderView.swift
|
1
|
5075
|
//
// StartupAnimationView.swift
// SBLoader
//
// Created by Satraj Bambra on 2015-03-17.
// Copyright (c) 2015 Satraj Bambra. All rights reserved.
//
import UIKit
protocol StartupAnimationViewDelegate: class {
func animateLabel(_ completion:@escaping RestoralCompletion)
}
extension UIViewController: StartupAnimationViewDelegate {
func animateLabel(_ completion:@escaping RestoralCompletion) {
// 1
//holderView.removeFromSuperview()
view.backgroundColor = Colors.mainColor()
// 2
//print ("\(self.view.frame)")
let label: UILabel = UILabel(frame: view.frame)
label.textColor = Colors.white
label.font = UIFont(name: "HelveticaNeue-Thin", size: 70.0)
label.adjustsFontSizeToFitWidth = true
label.textAlignment = NSTextAlignment.center
label.text = "SheetCheats"
label.transform = label.transform.scaledBy(x: 0.25, y: 0.25)
view.addSubview(label)
// 3
UIView.animate(withDuration: 2.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: UIViewAnimationOptions(),
animations: ({
label.transform = label.transform.scaledBy(x: 4.0, y: 4.0)
}), completion: { finished in
print("spring animation finished \(finished)")
if finished { completion() }
})
}
}
class StartupAnimationView: UIView {
var finalSignal: RestoralCompletion?
let animationBlue = Colors.mainColor()
let ovalLayer = OvalLayer()
let triangleLayer = TriangleLayer()
let redRectangleLayer = RectangleLayer()
let blueRectangleLayer = RectangleLayer()
let arcLayer = ArcLayer()
var parentFrame :CGRect = CGRect.zero
weak var delegate:StartupAnimationViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Colors.clear
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func addOval() {
layer.addSublayer(ovalLayer)
ovalLayer.expand()
Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(StartupAnimationView.wobbleOval),
userInfo: nil, repeats: false)
}
func wobbleOval() {
ovalLayer.wobble()
// 1
layer.addSublayer(triangleLayer) // Add this line
ovalLayer.wobble()
// 2
// Add the code below
Timer.scheduledTimer(timeInterval: 0.4, target: self,
selector: #selector(StartupAnimationView.drawAnimatedTriangle), userInfo: nil,
repeats: false)
}
func drawAnimatedTriangle() {
triangleLayer.animate()
Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(StartupAnimationView.spinAndTransform),
userInfo: nil, repeats: false)
}
func spinAndTransform() {
// 1
layer.anchorPoint = CGPoint(x: 0.5, y: 0.6)
// 2
let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(M_PI * 2.0)
rotationAnimation.duration = 0.25
rotationAnimation.isRemovedOnCompletion = true
layer.add(rotationAnimation, forKey: nil)
// 3
ovalLayer.contract()
Timer.scheduledTimer(timeInterval: 0.15, target: self,
selector: #selector(StartupAnimationView.drawRedAnimatedRectangle),
userInfo: nil, repeats: false)
Timer.scheduledTimer(timeInterval: 0.35, target: self,
selector: #selector(StartupAnimationView.drawBlueAnimatedRectangle),
userInfo: nil, repeats: false)
}
func drawRedAnimatedRectangle() {
layer.addSublayer(redRectangleLayer)
redRectangleLayer.animateStrokeWithColor(Colors.drawingAlertColor)
}
func drawBlueAnimatedRectangle() {
layer.addSublayer(blueRectangleLayer)
blueRectangleLayer.animateStrokeWithColor(Colors.mainColor())
Timer.scheduledTimer(timeInterval: 0.40, target: self, selector: #selector(StartupAnimationView.drawArc),
userInfo: nil, repeats: false)
}
func drawArc() {
layer.addSublayer(arcLayer)
arcLayer.animate()
Timer.scheduledTimer(timeInterval: 0.60, target: self, selector: #selector(StartupAnimationView.expandView),
userInfo: nil, repeats: false)
}
func expandView() {
backgroundColor = Colors.mainColor()
frame = CGRect(x: frame.origin.x - blueRectangleLayer.lineWidth,
y: frame.origin.y - blueRectangleLayer.lineWidth,
width: frame.size.width + blueRectangleLayer.lineWidth * 2,
height: frame.size.height + blueRectangleLayer.lineWidth * 2)
layer.sublayers = nil
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions(), animations: {
self.frame = self.parentFrame
}, completion: { finished in
self.addLabel()
})
}
func addLabel() {
/// COMES HERE WHEN INITIAL ANIMATION DANCE IS DONE, NOW ANIMATE THE LABEL
delegate?.animateLabel(){
// WHEN THE LABEL IS FINALLY DONE SEND ANOTHER SIGNAL
if self.finalSignal != nil
{
self.finalSignal!()
}
}
}
}
|
apache-2.0
|
d76547a6ea853407b73012de01aabd99
| 30.521739 | 145 | 0.68197 | 4.289941 | false | false | false | false |
tensorflow/examples
|
lite/examples/image_classification/ios/ImageClassification/ViewControllers/ViewController.swift
|
1
|
14829
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AVFoundation
import UIKit
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var bottomSheetView: UIView!
@IBOutlet weak var bottomSheetViewBottomSpace: NSLayoutConstraint!
@IBOutlet weak var bottomSheetStateImageView: UIImageView!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
// MARK: Constants
private let animationDuration = 0.5
private let collapseTransitionThreshold: CGFloat = -40.0
private let expandTransitionThreshold: CGFloat = 40.0
private let delayBetweenInferencesMs = 1000.0
// MARK: Instance Variables
private let inferenceQueue = DispatchQueue(label: "org.tensorflow.lite.inferencequeue")
private var previousInferenceTimeMs = Date.distantPast.timeIntervalSince1970 * 1000
private var isInferenceQueueBusy = false
private var initialBottomSpace: CGFloat = 0.0
private var threadCount = DefaultConstants.threadCount
private var maxResults = DefaultConstants.maxResults {
didSet {
guard let inferenceVC = inferenceViewController else { return }
bottomViewHeightConstraint.constant = inferenceVC.collapsedHeight + 290
view.layoutSubviews()
}
}
private var scoreThreshold = DefaultConstants.scoreThreshold
private var model: ModelType = .efficientnetLite0
// MARK: Controllers that manage functionality
// Handles all the camera related functionality
private lazy var cameraCapture = CameraFeedManager(previewView: previewView)
// Handles all data preprocessing and makes calls to run inference through the
// `ImageClassificationHelper`.
private var imageClassificationHelper: ImageClassificationHelper? =
ImageClassificationHelper(
modelFileInfo: DefaultConstants.model.modelFileInfo,
threadCount: DefaultConstants.threadCount,
resultCount: DefaultConstants.maxResults,
scoreThreshold: DefaultConstants.scoreThreshold)
// Handles the presenting of results on the screen
private var inferenceViewController: InferenceViewController?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
guard imageClassificationHelper != nil else {
fatalError("Model initialization failed.")
}
cameraCapture.delegate = self
addPanGesture()
guard let inferenceVC = inferenceViewController else { return }
bottomViewHeightConstraint.constant = inferenceVC.collapsedHeight + 290
view.layoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
self.changeBottomViewState()
}
#if !targetEnvironment(simulator)
cameraCapture.checkCameraConfigurationAndStartSession()
#endif
}
#if !targetEnvironment(simulator)
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
cameraCapture.stopSession()
}
#endif
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
// MARK: Storyboard Segue Handlers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "EMBED" {
inferenceViewController = segue.destination as? InferenceViewController
inferenceViewController?.maxResults = maxResults
inferenceViewController?.currentThreadCount = threadCount
inferenceViewController?.delegate = self
}
}
}
// MARK: InferenceViewControllerDelegate Methods
extension ViewController: InferenceViewControllerDelegate {
func viewController(
_ viewController: InferenceViewController,
needPerformActions action: InferenceViewController.Action
) {
var isModelNeedsRefresh = false
switch action {
case .changeThreadCount(let threadCount):
if self.threadCount != threadCount {
isModelNeedsRefresh = true
}
self.threadCount = threadCount
case .changeScoreThreshold(let scoreThreshold):
if self.scoreThreshold != scoreThreshold {
isModelNeedsRefresh = true
}
self.scoreThreshold = scoreThreshold
case .changeMaxResults(let maxResults):
if self.maxResults != maxResults {
isModelNeedsRefresh = true
}
self.maxResults = maxResults
case .changeModel(let model):
if self.model != model {
isModelNeedsRefresh = true
}
self.model = model
}
if isModelNeedsRefresh {
imageClassificationHelper = ImageClassificationHelper(
modelFileInfo: model.modelFileInfo,
threadCount: threadCount,
resultCount: maxResults,
scoreThreshold: scoreThreshold
)
}
}
}
// MARK: CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
func didOutput(pixelBuffer: CVPixelBuffer) {
// Make sure the model will not run too often, making the results changing quickly and hard to
// read.
let currentTimeMs = Date().timeIntervalSince1970 * 1000
guard (currentTimeMs - previousInferenceTimeMs) >= delayBetweenInferencesMs else { return }
previousInferenceTimeMs = currentTimeMs
// Drop this frame if the model is still busy classifying a previous frame.
guard !isInferenceQueueBusy else { return }
inferenceQueue.async { [weak self] in
guard let self = self else { return }
self.isInferenceQueueBusy = true
// Pass the pixel buffer to TensorFlow Lite to perform inference.
let result = self.imageClassificationHelper?.classify(frame: pixelBuffer)
self.isInferenceQueueBusy = false
// Display results by handing off to the InferenceViewController.
DispatchQueue.main.async {
let resolution = CGSize(
width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer))
self.inferenceViewController?.inferenceResult = result
self.inferenceViewController?.resolution = resolution
self.inferenceViewController?.tableView.reloadData()
}
}
}
// MARK: Session Handling Alerts
func sessionWasInterrupted(canResumeManually resumeManually: Bool) {
// Updates the UI when session is interupted.
if resumeManually {
self.resumeButton.isHidden = false
} else {
self.cameraUnavailableLabel.isHidden = false
}
}
func sessionInterruptionEnded() {
// Updates UI once session interruption has ended.
if !self.cameraUnavailableLabel.isHidden {
self.cameraUnavailableLabel.isHidden = true
}
if !self.resumeButton.isHidden {
self.resumeButton.isHidden = true
}
}
func sessionRunTimeErrorOccured() {
// Handles session run time error by updating the UI and providing a button if session can be
// manually resumed.
self.resumeButton.isHidden = false
previewView.shouldUseClipboardImage = true
}
func presentCameraPermissionsDeniedAlert() {
let alertController = UIAlertController(
title: "Camera Permissions Denied",
message:
"Camera permissions have been denied for this app. You can change this by going to Settings",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (action) in
UIApplication.shared.open(
URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
previewView.shouldUseClipboardImage = true
}
func presentVideoConfigurationErrorAlert() {
let alert = UIAlertController(
title: "Camera Configuration Failed", message: "There was an error while configuring camera.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
previewView.shouldUseClipboardImage = true
}
}
// MARK: Bottom Sheet Interaction Methods
extension ViewController {
// MARK: Bottom Sheet Interaction Methods
/**
This method adds a pan gesture to make the bottom sheet interactive.
*/
private func addPanGesture() {
let panGesture = UIPanGestureRecognizer(
target: self, action: #selector(ViewController.didPan(panGesture:)))
bottomSheetView.addGestureRecognizer(panGesture)
}
/** Change whether bottom sheet should be in expanded or collapsed state.
*/
private func changeBottomViewState() {
guard let inferenceVC = inferenceViewController else {
return
}
if bottomSheetViewBottomSpace.constant == inferenceVC.collapsedHeight
- bottomSheetView.bounds.size.height
{
bottomSheetViewBottomSpace.constant = 0.0
} else {
bottomSheetViewBottomSpace.constant =
inferenceVC.collapsedHeight - bottomSheetView.bounds.size.height
}
setImageBasedOnBottomViewState()
}
/**
Set image of the bottom sheet icon based on whether it is expanded or collapsed
*/
private func setImageBasedOnBottomViewState() {
if bottomSheetViewBottomSpace.constant == 0.0 {
bottomSheetStateImageView.image = UIImage(named: "down_icon")
} else {
bottomSheetStateImageView.image = UIImage(named: "up_icon")
}
}
/**
This method responds to the user panning on the bottom sheet.
*/
@objc func didPan(panGesture: UIPanGestureRecognizer) {
// Opens or closes the bottom sheet based on the user's interaction with the bottom sheet.
let translation = panGesture.translation(in: view)
switch panGesture.state {
case .began:
initialBottomSpace = bottomSheetViewBottomSpace.constant
translateBottomSheet(withVerticalTranslation: translation.y)
case .changed:
translateBottomSheet(withVerticalTranslation: translation.y)
case .cancelled:
setBottomSheetLayout(withBottomSpace: initialBottomSpace)
case .ended:
translateBottomSheetAtEndOfPan(withVerticalTranslation: translation.y)
setImageBasedOnBottomViewState()
initialBottomSpace = 0.0
default:
break
}
}
/**
This method sets bottom sheet translation while pan gesture state is continuously changing.
*/
private func translateBottomSheet(withVerticalTranslation verticalTranslation: CGFloat) {
let bottomSpace = initialBottomSpace - verticalTranslation
guard
bottomSpace <= 0.0
&& bottomSpace >= inferenceViewController!.collapsedHeight
- bottomSheetView.bounds.size.height
else {
return
}
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
This method changes bottom sheet state to either fully expanded or closed at the end of pan.
*/
private func translateBottomSheetAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat)
{
// Changes bottom sheet state to either fully open or closed at the end of pan.
let bottomSpace = bottomSpaceAtEndOfPan(withVerticalTranslation: verticalTranslation)
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
Return the final state of the bottom sheet view (whether fully collapsed or expanded) that is to
be retained.
*/
private func bottomSpaceAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat)
-> CGFloat
{
// Calculates whether to fully expand or collapse bottom sheet when pan gesture ends.
var bottomSpace = initialBottomSpace - verticalTranslation
var height: CGFloat = 0.0
if initialBottomSpace == 0.0 {
height = bottomSheetView.bounds.size.height
} else {
height = inferenceViewController!.collapsedHeight
}
let currentHeight = bottomSheetView.bounds.size.height + bottomSpace
if currentHeight - height <= collapseTransitionThreshold {
bottomSpace = inferenceViewController!.collapsedHeight - bottomSheetView.bounds.size.height
} else if currentHeight - height >= expandTransitionThreshold {
bottomSpace = 0.0
} else {
bottomSpace = initialBottomSpace
}
return bottomSpace
}
/**
This method layouts the change of the bottom space of bottom sheet with respect to the view
managed by this controller.
*/
func setBottomSheetLayout(withBottomSpace bottomSpace: CGFloat) {
view.setNeedsLayout()
bottomSheetViewBottomSpace.constant = bottomSpace
view.setNeedsLayout()
}
}
// Define default constants
enum DefaultConstants {
static let threadCount = 4
static let maxResults = 3
static let scoreThreshold: Float = 0.2
static let model: ModelType = .efficientnetLite0
}
/// TFLite model types
enum ModelType: CaseIterable {
case efficientnetLite0
case efficientnetLite1
case efficientnetLite2
case efficientnetLite3
case efficientnetLite4
var modelFileInfo: FileInfo {
switch self {
case .efficientnetLite0:
return FileInfo("efficientnet_lite0", "tflite")
case .efficientnetLite1:
return FileInfo("efficientnet_lite1", "tflite")
case .efficientnetLite2:
return FileInfo("efficientnet_lite2", "tflite")
case .efficientnetLite3:
return FileInfo("efficientnet_lite3", "tflite")
case .efficientnetLite4:
return FileInfo("efficientnet_lite4", "tflite")
}
}
var title: String {
switch self {
case .efficientnetLite0:
return "EfficientNet-Lite0"
case .efficientnetLite1:
return "EfficientNet-Lite1"
case .efficientnetLite2:
return "EfficientNet-Lite2"
case .efficientnetLite3:
return "EfficientNet-Lite3"
case .efficientnetLite4:
return "EfficientNet-Lite4"
}
}
}
|
apache-2.0
|
8869c2aa1125b1789375bb328ca1f3ae
| 32.62585 | 101 | 0.731674 | 4.881172 | false | false | false | false |
lizhenning87/SwiftZhiHu
|
SwiftZhiHu/SwiftZhiHu/Haneke/UIImageView+Haneke.swift
|
1
|
5469
|
//
// UIImageView+Haneke.swift
// Haneke
//
// Created by Hermes Pique on 9/17/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension UIImageView {
public var hnk_format : Format<UIImage> {
let viewSize = self.bounds.size
assert(viewSize.width > 0 && viewSize.height > 0, "[\(reflect(self).summary) \(__FUNCTION__)]: UImageView size is zero. Set its frame, call sizeToFit or force layout first.")
let scaleMode = self.hnk_scaleMode
return Haneke.UIKitGlobals.formatWithSize(viewSize, scaleMode: scaleMode)
}
public func hnk_setImageFromURL(URL: NSURL, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(URL: URL)
self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImage(image: @autoclosure () -> UIImage, key : String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setImageFromFile(path : String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setImageFromFetcher(fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImageFromFetcher(fetcher : Fetcher<UIImage>,
placeholder : UIImage? = nil,
format : Format<UIImage>? = nil,
failure fail : ((NSError?) -> ())? = nil,
success succeed : ((UIImage) -> ())? = nil) {
self.hnk_cancelSetImage()
self.hnk_fetcher = fetcher
let didSetImage = self.hnk_fetchImageForFetcher(fetcher, format: format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.image = placeholder
}
}
public func hnk_cancelSetImage() {
if let fetcher = self.hnk_fetcher {
fetcher.cancelFetch()
self.hnk_fetcher = nil
}
}
// MARK: Internal
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_fetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &Haneke.UIKitGlobals.SetImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.value as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &Haneke.UIKitGlobals.SetImageFetcherKey, wrapper, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
public var hnk_scaleMode : ImageResizer.ScaleMode {
switch (self.contentMode) {
case .ScaleToFill:
return .Fill
case .ScaleAspectFit:
return .AspectFit
case .ScaleAspectFill:
return .AspectFill
case .Redraw, .Center, .Top, .Bottom, .Left, .Right, .TopLeft, .TopRight, .BottomLeft, .BottomRight:
return .None
}
}
func hnk_fetchImageForFetcher(fetcher : Fetcher<UIImage>, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let cache = Haneke.sharedImageCache
let format = format ?? self.hnk_format
if cache.formats[format.name] == nil {
cache.addFormat(format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelForKey(fetcher.key) { return }
strongSelf.hnk_fetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelForKey(fetcher.key) { return }
strongSelf.hnk_setImage(image, animated:animated, success:succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setImage(image : UIImage, animated : Bool, success succeed : ((UIImage) -> ())?) {
self.hnk_fetcher = nil
if let succeed = succeed {
succeed(image)
} else {
let duration : NSTimeInterval = animated ? 0.1 : 0
UIView.transitionWithView(self, duration: duration, options: .TransitionCrossDissolve, animations: {
self.image = image
}, completion: nil)
}
}
func hnk_shouldCancelForKey(key:String) -> Bool {
if self.hnk_fetcher?.key == key { return false }
NSLog("Cancelled set image for \(key.lastPathComponent)")
return true
}
}
|
apache-2.0
|
5b55b347be40b3e521bde02c0787e983
| 38.630435 | 202 | 0.590967 | 4.690395 | false | false | false | false |
matthewpalmer/Regift
|
RegiftTests/RegiftTests.swift
|
1
|
3725
|
//
// RegiftTests.swift
// RegiftTests
//
// Created by Matthew Palmer on 27/12/2014.
// Copyright (c) 2014 Matthew Palmer. All rights reserved.
//
#if os(iOS)
import UIKit
import Regift
#elseif os(OSX)
import AppKit
import RegiftOSX
#endif
import XCTest
import ImageIO
class RegiftTests: XCTestCase {
var URL: Foundation.URL!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
let testBundle = Bundle(for: type(of: self))
URL = testBundle.url(forResource: "regift-test-file", withExtension: "mov")
XCTAssertNotNil(URL)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testGIFIsCreated() {
let regift = Regift(sourceFileURL: URL, frameCount: 16, delayTime: 0.2)
let result = regift.createGif()
XCTAssertNotNil(result, "The GIF URL should not be nil")
XCTAssertTrue(FileManager.default.fileExists(atPath: result!.path))
let source = CGImageSourceCreateWithURL(result! as CFURL, nil)
let count = CGImageSourceGetCount(source!)
let type = CGImageSourceGetType(source!)
let properties = CGImageSourceCopyProperties(source!, nil)! as NSDictionary
let fileProperties = properties.object(forKey: kCGImagePropertyGIFDictionary as String) as! NSDictionary
let loopCount = fileProperties.value(forKey: kCGImagePropertyGIFLoopCount as String) as! Int
XCTAssertEqual(count, 16)
XCTAssertEqual(type! as NSString, "com.compuserve.gif")
XCTAssertEqual(loopCount, 0)
(0..<count).forEach { (index) -> () in
let frameProperties = CGImageSourceCopyPropertiesAtIndex(source!, index, nil)! as NSDictionary
let gifFrameProperties = frameProperties.object(forKey: kCGImagePropertyGIFDictionary as String)
print(gifFrameProperties ?? "")
let delayTime = ((gifFrameProperties as! NSDictionary)[kCGImagePropertyGIFDelayTime as String] as! NSNumber).floatValue
XCTAssertEqual(delayTime, 0.2)
}
}
func testGIFIsSaved() {
let savedURL = Foundation.URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("test.gif"))
let regift = Regift(sourceFileURL: URL, destinationFileURL: savedURL, frameCount: 16, delayTime: 0.2, progress: { (progress) in
print(progress)
})
let result = regift.createGif()
XCTAssertNotNil(result, "The GIF URL should not be nil")
XCTAssertTrue(savedURL.absoluteString == result?.absoluteString)
XCTAssertTrue(FileManager.default.fileExists(atPath: result!.path))
}
func testTrimmedGIFIsSaved() {
let savedURL = Foundation.URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("test_trim.gif"))
let regift = Regift(sourceFileURL: URL, destinationFileURL: savedURL, startTime: 1, duration: 2, frameRate: 15)
let result = regift.createGif()
XCTAssertNotNil(result, "The GIF URL should not be nil")
XCTAssertTrue(savedURL.absoluteString == result?.absoluteString)
XCTAssertTrue(FileManager.default.fileExists(atPath: result!.path))
}
func testGIFIsNotCreated() {
let regift = Regift(sourceFileURL: Foundation.URL(fileURLWithPath: ""), frameCount: 10, delayTime: 0.5)
let result = regift.createGif()
XCTAssertNil(result)
}
}
|
mit
|
7402b3adab6e48f0425b78698eca2757
| 39.053763 | 135 | 0.668188 | 4.673777 | false | true | false | false |
chrisjmendez/swift-exercises
|
Social/Facebook/Facebook/ViewController.swift
|
1
|
2487
|
//
// ViewController.swift
// Facebook
//
// Created by tommy trojan on 5/7/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
facebookTokenDidLoad()
}
func facebookTokenDidLoad(){
if (FBSDKAccessToken.currentAccessToken() != nil){
// User is already logged in, do work such as go to next view controller.
} else {
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
}
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
println("User Logged In")
if ((error) != nil){
// Process error
} else if result.isCancelled {
// Handle cancellations
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if result.grantedPermissions.contains("email"){
// Do work
}
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
println("User Logged Out")
}
func returnUserData(){
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil){
// Process error
println("Error: \(error)")
}else{
println("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
println("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
println("User Email is: \(userEmail)")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
1c6b2fd4444f15eb1cb678337df791ac
| 32.16 | 132 | 0.581021 | 5.430131 | false | false | false | false |
mcudich/TemplateKit
|
Source/iOS/DelegateProxy.swift
|
1
|
1507
|
//
// DelegateProxy.swift
// TemplateKit
//
// Created by Matias Cudich on 8/9/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
protocol DelegateProxyProtocol {
init(target: AnyObject?, interceptor: NSObjectProtocol?)
func registerInterceptable(selector: Selector)
}
class DelegateProxy: NSObject, DelegateProxyProtocol {
let target: AnyObject?
let interceptor: NSObjectProtocol?
private lazy var selectors = Set<Selector>()
required init(target: AnyObject?, interceptor: NSObjectProtocol?) {
self.target = target
self.interceptor = interceptor
}
func registerInterceptable(selector: Selector) {
selectors.insert(selector)
}
override func conforms(to aProtocol: Protocol) -> Bool {
return true
}
override func responds(to aSelector: Selector) -> Bool {
if intercepts(selector: aSelector) {
return interceptor?.responds(to: aSelector) ?? false
} else {
return target?.responds(to: aSelector) ?? false
}
}
override func forwardingTarget(for aSelector: Selector) -> Any? {
if intercepts(selector: aSelector) {
return interceptor
} else if let target = target {
return target.responds(to: aSelector) ? target : nil
}
return nil
}
private func intercepts(selector: Selector) -> Bool {
return selectors.contains(selector)
}
}
func ==(lhs: DelegateProxy, rhs: DelegateProxy) -> Bool {
return lhs.target === rhs.target && lhs.interceptor === rhs.interceptor
}
|
mit
|
8051652a5dcb08e61b1e5fbcb7a7d2ad
| 24.965517 | 73 | 0.701195 | 4.352601 | false | false | false | false |
mathewsheets/SwiftLearningExercises
|
Exercise_12.playground/Contents.swift
|
1
|
2116
|
/*:
* callout(Exercise): Build upon your simple bank teller system by using extensions. Examine your solution, identity properties and/or methods that would be good candidates for creating an extension. Did you use inheritance? See where you can use extensions in place of inheritance. Where you are specifying protocol conformance, see if extensions can be leveraged.
**Constraints:**
- Use extensions instead of inheritance
- Use extensions to make types more natural in the system
- Use a protocol extension to provide default implementations
*/
import Foundation
var teller: Teller? = Teller(name: "Annie")
teller?.auditDelegate = AuditDefaultDelegate()
teller?.handle(customer: Customer(name: "Matt"))
do {
try teller?.openCheckingAccount()
let account = teller!.customer!.checking!
try teller?.credit(amount: 100.00, account: account)
print(account.description)
try teller?.debit(amount: 99.00, account: account)
print(account.description)
// try teller?.debit(2.00, account: account)
// print(account.description)
try teller?.done()
} catch TransactionError.NoCustomer {
print("ERROR: teller is not handling a customer")
} catch TransactionError.InsufficientFunds(let balance, let debiting) {
print("ERROR: transaction error: debiting \(debiting), balance = \(balance)")
}
teller?.handle(customer: Customer(name: "Sam"))
do {
try teller?.openSavingsAccount()
let account = teller!.customer!.savings!
try teller?.debit(amount: 100.00, account: account)
print(account.description)
try teller?.credit(amount: 600.00, account: account)
print(account.description)
if let savings = account as? SavingsAccount {
savings.applyInterest()
}
print(account.description)
try teller?.done()
} catch TransactionError.NoCustomer {
print("ERROR: teller is not handling a customer")
} catch TransactionError.InsufficientFunds(let balance, let debiting) {
print("ERROR: transaction error: debiting \(debiting), balance = \(balance)")
}
teller = nil
|
mit
|
9e41dacb5956d17fc6fa13cb721801af
| 32.587302 | 365 | 0.710302 | 4.157171 | false | false | false | false |
TotemTraining/PracticaliOSAppSecurity
|
V6/Keymaster/Keymaster/Keychain/ArchiveKey.swift
|
14
|
1762
|
//
// ArchiveKey.swift
// SwiftKeychain
//
// Created by Yanko Dimitrov on 11/13/14.
// Copyright (c) 2014 Yanko Dimitrov. All rights reserved.
//
import Foundation
public class ArchiveKey: BaseKey {
public var object: NSCoding?
private var secretData: NSData? {
if let objectToArchive = object {
return NSKeyedArchiver.archivedDataWithRootObject(objectToArchive)
}
return nil
}
///////////////////////////////////////////////////////
// MARK: - Initializers
///////////////////////////////////////////////////////
public init(keyName: String, object: NSCoding? = nil) {
self.object = object
super.init(name: keyName)
}
///////////////////////////////////////////////////////
// MARK: - KeychainItem
///////////////////////////////////////////////////////
public override func makeQueryForKeychain(keychain: KeychainService) -> KeychainQuery {
let query = KeychainQuery(keychain: keychain)
query.addField(kSecClass, withValue: kSecClassGenericPassword)
query.addField(kSecAttrService, withValue: keychain.serviceName)
query.addField(kSecAttrAccount, withValue: name)
return query
}
public override func fieldsToLock() -> [NSObject: AnyObject] {
var fields = [NSObject: AnyObject]()
if let data = secretData {
fields[kSecValueData as String] = data
}
return fields
}
public override func unlockData(data: NSData) {
object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSCoding
}
}
|
mit
|
8dc942a2be821e1e28107726a1f1358a
| 25.69697 | 91 | 0.514756 | 5.93266 | false | false | false | false |
nerdyc/Squeal
|
Squeal.playground/Contents.swift
|
1
|
764
|
import Squeal
let db = Database()
// Create:
try db.createTable("contacts", definitions: [
"id INTEGER PRIMARY KEY",
"name TEXT",
"email TEXT NOT NULL"
])
// Insert:
let contactId = try db.insertInto(
"contacts",
values: [
"name": "Amelia Grey",
"email": "[email protected]"
]
)
// Select:
struct Contact {
let id:Int
let name:String?
let email:String
init(row:Statement) throws {
id = row.intValue("id") ?? 0
name = row.stringValue("name")
email = row.stringValue("email") ?? ""
}
}
let contacts:[Contact] = try db.selectFrom(
"contacts",
whereExpr:"name IS NOT NULL",
block: Contact.init
)
// Count:
let numberOfContacts = try db.countFrom("contacts")
|
mit
|
8c244742a7689c1812e3ecc69ddcd73c
| 17.634146 | 51 | 0.596859 | 3.488584 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/NewVersion/Mine/ZSMineViewModel.swift
|
1
|
760
|
//
// ZSMineViewModel.swift
// zhuishushenqi
//
// Created by yung on 2019/7/7.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
class ZSMineViewModel {
var viewDidLoad: ()->() = {}
var reloadBlock: ()->() = {}
var service:ZSMyService = ZSMyService()
var account:ZSAccount?
init() {
viewDidLoad = { [weak self] in
self?.requestAccount()
}
}
func requestAccount() {
requestAccount { [weak self] in
self?.reloadBlock()
}
}
func requestAccount(completion:@escaping()->Void) {
service.fetchAccount(token: ZSLogin.share.token) { (account) in
self.account = account
completion()
}
}
}
|
mit
|
4a1b24add01976ded2e991daa6ac61e2
| 18.973684 | 71 | 0.545455 | 4.102703 | false | false | false | false |
mikelikespie/swiftled
|
src/main/swift/Visualizations/STimeVisualization.swift
|
1
|
3103
|
//
// STimeVisualization.swift
// swiftled-2
//
// Created by Michael Lewis on 8/9/16.
//
//
import Foundation
import RxSwift
import Cleanse
import OPC
/// returns [0,1]
func triangle(x: Float) -> Float {
return x - round(x)
}
func sawtooth(t: Float) -> Float {
let t = t + 0.5
return abs(t - Float(Int(t)) - 0.5)
}
public class STimeVisualization : Visualization {
let ledCount: Int
let segmentLength: Int
let segmentCount: Int
let shapeProvider: Provider<MyShape>
init(
ledCount: TaggedProvider<LedCount>,
segmentLength: TaggedProvider<SegmentLength>,
segmentCount: TaggedProvider<SegmentCount>,
shapeProvider: Provider<MyShape>) {
self.ledCount = ledCount.get()
self.segmentLength = segmentLength.get()
self.segmentCount = segmentCount.get()
self.shapeProvider = shapeProvider
}
public static func configureRoot(binder bind: ReceiptBinder<BaseVisualization>) -> BindingReceipt<BaseVisualization> {
return bind.to(factory: STimeVisualization.init)
}
let lowerHueControl = SliderControl<Float>(bounds: 0..<2, defaultValue: 0, name: "Lower Hue")
let upperHueControl = SliderControl<Float>(bounds: 0..<2, defaultValue: 1.0 / 6.0, name: "Upper Hue")
let speed1 = SliderControl<Float>(bounds: -3..<10, defaultValue: 20, name: "Speed 1")
public var controls: Observable<[Control]> {
return Observable.just(
[
lowerHueControl,
upperHueControl,
speed1,
]
)
}
public let name = "0-SxTime"
public func bind(_ ticker: Observable<WriteContext>) -> Disposable {
let shape = shapeProvider.get()
return ticker.subscribe(onNext: { context in
shape.clear()
let rangeDelta = max(0, self.upperHueControl.value - self.lowerHueControl.value)
let lowerHue = self.lowerHueControl.value
for (vertexIndex, value) in (0..<12).enumerated() {
shape.withEdges(adjacentToVertex: value) { edge, ptr in
let totalLength = self.segmentLength
let timeOffset = context.tickContext.timeOffset * 0.125 * Double(self.speed1.value)
for i in 0..<(ptr.count / 3) {
let tt = (Float(i) / Float(totalLength) + Float(timeOffset) + (Float(vertexIndex) / 3))
let h = (lowerHue + sawtooth(t: tt) * rangeDelta).truncatingRemainder(dividingBy: 1.0)
ptr[i] = HSV(
h: h,
s: 1.0,
v: 1.0
)
.rgbFloat
.with(alpha: 1.0)
}
}
}
shape.copyToBuffer(buffer: context.writeBuffer)
})
}
}
|
mit
|
1afc34bb1c04c07e7abcea146cfe83c6
| 28.552381 | 122 | 0.531743 | 4.471182 | false | false | false | false |
open-telemetry/opentelemetry-swift
|
Sources/OpenTelemetrySdk/Metrics/DoubleObserverMetricHandle.swift
|
1
|
1030
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryApi
class DoubleObserverMetricSdk: DoubleObserverMetric {
public private(set) var observerHandles = [LabelSet: DoubleObserverMetricHandleSdk]()
let metricName: String
var callback: (DoubleObserverMetric) -> Void
init(metricName: String, callback: @escaping (DoubleObserverMetric) -> Void) {
self.metricName = metricName
self.callback = callback
}
func observe(value: Double, labels: [String: String]) {
observe(value: value, labelset: LabelSet(labels: labels))
}
func observe(value: Double, labelset: LabelSet) {
var boundInstrument = observerHandles[labelset]
if boundInstrument == nil {
boundInstrument = DoubleObserverMetricHandleSdk()
observerHandles[labelset] = boundInstrument
}
boundInstrument?.observe(value: value)
}
func invokeCallback() {
callback(self)
}
}
|
apache-2.0
|
bfc904ca2e81a5e86230a95608d448ff
| 28.428571 | 89 | 0.683495 | 4.598214 | false | false | false | false |
qvacua/vimr
|
NvimView/Sources/NvimView/KeyUtils.swift
|
1
|
2562
|
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
final class KeyUtils {
static func isControlCode(key: String) -> Bool {
guard key.count == 1 else {
return false
}
guard let firstChar = key.utf16.first else {
return false
}
return firstChar < 32 && firstChar > 0
}
static func isSpecial(key: String) -> Bool {
guard key.count == 1 else {
return false
}
if let firstChar = key.utf16.first {
return specialKeys.keys.contains(Int(firstChar))
}
return false
}
static func namedKey(from key: String) -> String {
if let firstChar = key.utf16.first, let special = specialKeys[Int(firstChar)] {
return special
}
return key
}
static func isHalfWidth(char: Character) -> Bool {
// https://stackoverflow.com/questions/13505075/analyzing-full-width-or-half-width-character-in-java?noredirect=1&lq=1 // swiftlint:disable:this all
switch char {
case "\u{00}"..."\u{FF}", "\u{FF61}"..."\u{FFDC}", "\u{FFE8}"..."\u{FFEE}":
return true
default: return false
}
}
}
private let specialKeys = [
NSUpArrowFunctionKey: "Up",
NSDownArrowFunctionKey: "Down",
NSLeftArrowFunctionKey: "Left",
NSRightArrowFunctionKey: "Right",
NSInsertFunctionKey: "Insert",
0x7F: "BS", // "delete"-key
NSDeleteFunctionKey: "Del", // "Fn+delete"-key
NSHomeFunctionKey: "Home",
NSBeginFunctionKey: "Begin",
NSEndFunctionKey: "End",
NSPageUpFunctionKey: "PageUp",
NSPageDownFunctionKey: "PageDown",
NSHelpFunctionKey: "Help",
NSF1FunctionKey: "F1",
NSF2FunctionKey: "F2",
NSF3FunctionKey: "F3",
NSF4FunctionKey: "F4",
NSF5FunctionKey: "F5",
NSF6FunctionKey: "F6",
NSF7FunctionKey: "F7",
NSF8FunctionKey: "F8",
NSF9FunctionKey: "F9",
NSF10FunctionKey: "F10",
NSF11FunctionKey: "F11",
NSF12FunctionKey: "F12",
NSF13FunctionKey: "F13",
NSF14FunctionKey: "F14",
NSF15FunctionKey: "F15",
NSF16FunctionKey: "F16",
NSF17FunctionKey: "F17",
NSF18FunctionKey: "F18",
NSF19FunctionKey: "F19",
NSF20FunctionKey: "F20",
NSF21FunctionKey: "F21",
NSF22FunctionKey: "F22",
NSF23FunctionKey: "F23",
NSF24FunctionKey: "F24",
NSF25FunctionKey: "F25",
NSF26FunctionKey: "F26",
NSF27FunctionKey: "F27",
NSF28FunctionKey: "F28",
NSF29FunctionKey: "F29",
NSF30FunctionKey: "F30",
NSF31FunctionKey: "F31",
NSF32FunctionKey: "F32",
NSF33FunctionKey: "F33",
NSF34FunctionKey: "F34",
NSF35FunctionKey: "F35",
0x09: "Tab",
0x19: "Tab",
0xD: "CR",
0x20: "Space",
]
|
mit
|
90481b8fe50611c4b1a80480d4bd3eaf
| 23.873786 | 152 | 0.662373 | 2.95843 | false | false | false | false |
XeresRazor/SwiftRaytracer
|
src/pathtracer/Image.swift
|
1
|
2319
|
//
// Image.swift
// Raytracer
//
// Created by David Green on 4/6/16.
// Copyright © 2016 David Green. All rights reserved.
//
import Foundation
import stbi
public struct RGBA8Pixel {
public var r: UInt8
public var g: UInt8
public var b: UInt8
public var a: UInt8
public init(_ red: UInt8, _ green: UInt8, _ blue: UInt8, _ alpha: UInt8) {
r = red
g = green
b = blue
a = alpha
}
public init(_ red: UInt8, _ green: UInt8, _ blue: UInt8) {
r = red
g = green
b = blue
a = 255
}
}
public class RGBA8Image {
public let width: Int
public let height: Int
public var pixels: [RGBA8Pixel]
public init(width w: Int, height h: Int) {
width = w
height = h
let pixel = RGBA8Pixel(0, 0, 0, 255)
pixels = [RGBA8Pixel](repeating: pixel, count: width * height)
}
public init?(filename:String) {
var w = Int32(0)
var h = Int32(0)
var c = Int32(0)
let imagePixels = stbi_load(filename, &w, &h, &c, 4)
width = Int(w)
height = Int(h)
let pixel = RGBA8Pixel(0,0,0,0)
pixels = [RGBA8Pixel](repeating: pixel, count: width * height)
if imagePixels == nil {
return nil
}
for i in 0 ..< width * height {
let pixOffset = i * 4
let pixel = RGBA8Pixel(imagePixels[pixOffset + 0], imagePixels[pixOffset + 1], imagePixels[pixOffset + 2], imagePixels[pixOffset + 3])
pixels[i] = pixel
}
stbi_image_free(imagePixels)
}
public subscript(index: Int) -> RGBA8Pixel {
get {
assert(index < (width * height))
return pixels[index]
}
set(newValue) {
assert(index < (width * height))
pixels[index] = newValue
}
}
public subscript(x: Int, y: Int) -> RGBA8Pixel {
get {
let index = (x + y * width)
return self[index]
}
set(newValue) {
let index = (x + y * width)
self[index] = newValue
}
}
// MARK: Image file writing
public enum ImageFormat {
case png
case bmp
case tga
}
public func writeTo(file: String, format: ImageFormat) -> Bool {
var result: Bool
switch format {
case .png:
result = stbi_write_png(file, Int32(width), Int32(height), 4, pixels, Int32(width * 4)) != 0
case .bmp:
result = stbi_write_bmp(file, Int32(width), Int32(height), 4, pixels) != 0
case .tga:
result = stbi_write_tga(file, Int32(width), Int32(height), 4, pixels) != 0
}
return result
}
}
|
mit
|
d1c0dbbe3e0302eeb1c147dac271c8d4
| 19.165217 | 137 | 0.624245 | 2.762813 | false | false | false | false |
trident10/TDMediaPicker
|
TDMediaPicker/Classes/Utils/TDMediaUtil/TDMediaUtil+Image.swift
|
1
|
2127
|
//
// File.swift
// Pods
//
// Created by Abhimanu Jindal on 27/07/17.
//
//
import Foundation
extension TDMediaUtil {
static func isImageResolutionValid(_ imageView:UIImageView, image: UIImage)-> Bool{
let heightInPoints = image.size.height
let widthInPoints = image.size.width
return heightInPoints >= imageView.frame.size.height && widthInPoints >= imageView.frame.size.width
}
static func getImagefromColor(color: UIColor)-> UIImage{
let rect = CGRect(x:0.0,y:0.0,width: 1.0,height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
static func resizeImage(_ image: UIImage, newSize: CGSize) -> UIImage {
let horizontalRatio = newSize.width / image.size.width
let verticalRatio = newSize.height / image.size.height
let ratio = max(horizontalRatio, verticalRatio)
let newSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
var newImage: UIImage
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
newImage = renderer.image {
(context) in
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
}
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: newSize.width, height: newSize.height), false, 0)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
}
|
mit
|
403355cc633fef6b10781876fa6fc095
| 35.672414 | 132 | 0.633756 | 4.716186 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/check-if-every-row-and-column-contains-all-numbers.swift
|
1
|
563
|
/**
* https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/
*
*
*/
// Date: Fri Jan 21 19:44:31 PST 2022
class Solution {
func checkValid(_ matrix: [[Int]]) -> Bool {
let n = matrix.count
for x in 0 ..< n {
var rows = Set<Int>()
var cols = Set<Int>()
for y in 0 ..< n {
rows.insert(matrix[x][y])
cols.insert(matrix[y][x])
}
if rows.count != n || cols.count != n { return false }
}
return true
}
}
|
mit
|
2cd314885348ea2db790dd189ed23679
| 25.857143 | 84 | 0.474245 | 3.632258 | false | false | false | false |
ibari/StationToStation
|
Pods/p2.OAuth2/OAuth2/OAuth2ImplicitGrant.swift
|
1
|
2783
|
//
// OAuth2ImplicitGrant.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/9/14.
// Copyright 2014 Pascal Pfiffner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
Class to handle OAuth2 requests for public clients, such as distributed Mac/iOS Apps.
*/
public class OAuth2ImplicitGrant: OAuth2
{
public override func authorizeURLWithRedirect(redirect: String?, scope: String?, params: [String: String]?) -> NSURL {
return authorizeURLWithBase(authURL, redirect: redirect, scope: scope, responseType: "token", params: params)
}
public override func handleRedirectURL(redirect: NSURL) {
logIfVerbose("Handling redirect URL \(redirect.description)")
var error: NSError?
var comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true)
// token should be in the URL fragment
if let fragment = comp?.percentEncodedFragment where count(fragment) > 0 {
let params = OAuth2ImplicitGrant.paramsFromQuery(fragment)
if let token = params["access_token"] where !token.isEmpty {
if let tokType = params["token_type"] {
if "bearer" == tokType.lowercaseString {
// got a "bearer" token, use it if state checks out
if let tokState = params["state"] {
if tokState == state {
accessToken = token
accessTokenExpiry = nil
if let expires = params["expires_in"]?.toInt() {
accessTokenExpiry = NSDate(timeIntervalSinceNow: NSTimeInterval(expires))
}
logIfVerbose("Successfully extracted access token")
didAuthorize(params)
return
}
error = genOAuth2Error("Invalid state \(tokState), will not use the token", .InvalidState)
}
else {
error = genOAuth2Error("No state returned, will not use the token", .InvalidState)
}
}
else {
error = genOAuth2Error("Only \"bearer\" token is supported, but received \"\(tokType)\"", .Unsupported)
}
}
else {
error = genOAuth2Error("No token type received, will not use the token", .PrerequisiteFailed)
}
}
else {
error = errorForErrorResponse(params)
}
}
else {
error = genOAuth2Error("Invalid redirect URL: \(redirect)", .PrerequisiteFailed)
}
didFail(error)
}
}
|
gpl-2.0
|
8d536e1597dcdb5db9789371ed18e90c
| 32.130952 | 119 | 0.681639 | 3.998563 | false | false | false | false |
sendyhalim/Yomu
|
Yomu/Common/Views/SearchTextInput.swift
|
1
|
636
|
//
// TextInput.swift
// Yomu
//
// Created by Sendy Halim on 8/9/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import AppKit
class SearchTextInput: NSSearchField {
override func viewDidMoveToWindow() {
textColor = Config.style.primaryFontColor
focusRingType = NSFocusRingType.none
// Use new layer with background to remove border
// http://stackoverflow.com/questions/38921355/osx-cocoa-nssearchfield-clear-button-not-responding-to-click
let maskLayer = CALayer()
maskLayer.backgroundColor = Config.style.inputBackgroundColor.cgColor
wantsLayer = true
layer = maskLayer
}
}
|
mit
|
3b67283c45a4d45d2f78f071735e5ad6
| 25.458333 | 111 | 0.730709 | 4.096774 | false | true | false | false |
developerY/Swift2_Playgrounds
|
Swift2LangRef.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift
|
1
|
11974
|
//: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * Much of the control flow in Swift is similar to C-like languages, but there are some key
//: differences. For example, switch-case constructs are much more flexible and powerful as well
//: as extensions to break and continue statements.
//: ------------------------------------------------------------------------------------------------
//: ------------------------------------------------------------------------------------------------
//: For loops
//:
//: We can loop through ranges using the closed-range operator ("...").
//:
//: In the loop below, 'index' is a constant that is automatically declared.
for index in 1...5
{
"This will print 5 times"
// Being a constant, the following line won't compile:
//
// index = 99
}
//: The constant 'index' from the previous loop is scoped only to the loop. As a result, you cannot
//: access it beyond the loop. The following line will not compile:
//:
//: index = 0
//: We can loop through ranges using the half-closed range operator ("..<")
//:
//: We can also reuse the name 'index' because of the scoping noted previously.
for index in 1 ..< 5
{
"This will print 4 times"
}
//: Apple's "Swift Programming Language" book states the following, which I find in practice to be
//: incorrect:
//:
//: “The index constant exists only within the scope of the loop. If you want to check the value of
//: index after the loop completes, or if you want to work with its value as a variable rather than
//: a constant, you must declare it yourself before its use in the loop.”
//:
//: In practice, I find that the loop constant overrides any local variable/constant and maintains
//: its scope to the loop and does not alter the locally defined value:
var indx = 3999
for indx in 1...5
{
indx // This ranges from 1 to 5, inclusive
// 'indx' is still acting like a constant, so this line won't compile:
//
// indx++
}
//: After the loop, we find that 'indx' still contains the original value of 3999
indx
//: We can use an underscore if you don't need access to the loop constant:
for _ in 1...10
{
print("do something")
}
//: We can iterate over arrays
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names
{
name
}
//: We can iterate over a Dictionary's key/value pairs
let numberOfLegs = ["Spider":8, "Ant":6, "Cat":4]
for (animalName, legs) in numberOfLegs
{
animalName
legs
}
//: We can iterate over characters in a String
for character in "Hello".characters
{
character
}
//: We can use the For-Condition-Increment loop construct, which resembles the C-like variant
//:
//: Note that the loop value is a variable, not a constant. In fact, they cannot be constant
//: because of the increment statement (++index)
for (var index = 0; index < 3; ++index)
{
index
}
//: The parenthesis are optional for the For-Condition-Increment loop:
for var index = 0; index < 3; ++index
{
index
}
//: Variables are scoped to the For-Condition-Increment construct. To alter this, pre-declare index
var index = 3000
for index = 0; index < 3; ++index
{
index
}
index // Index holds 3 after running through the loop
//: ------------------------------------------------------------------------------------------------
//: While loops
//:
//: While loops resemble other C-like languages. They perform the condition before each iteration
//: through the loop:
while index > 0
{
--index
}
//: *Do-While is now Repeat-While* loops also resemble their C-like language counterparts. They perform the condition
//: after each iteration through the loop. As a result, they always execute the code inside the
//: loop at least once:
repeat
{
++index
} while (index < 3)
//: ------------------------------------------------------------------------------------------------
//: Conditional Statements
//:
//: The if statement is very similar to C-like languages, except that the parenthesis are optional.
//: You can also chain multiple conditions with 'else' and 'else if' statements:
if (index > 0)
{
"Index is positive"
}
else if index == 0
{
"index is zero"
}
else
{
"index is negative"
}
//: Switch statements are more powerful than their C-like counterparts. Here are a few of those
//: differences to get us started:
//:
//: Unlike C-like languages, switch statements do not require a "break" statement to prevent falling
//: through to the next case.
//:
//: Additionally, multiple conditions can be separated by a comma for a single case to match
//: multiple conditions.
//:
//: Switch statements must also be exhaustive and include all possible values, or the compiler will
//: generate an error.
//:
//: There are many more differences, but let's start with a simple switch statement to get our feet
//: wet:
let someCharacter: Character = "e"
switch someCharacter
{
case "a", "e", "i", "o", "u":
"a vowel"
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "u", "z":
"a consonant"
// Necessary because switch statements must be exhaustive in order to capture all Characters
default:
"not a vowel or consonant"
}
//: Each case clause must have a statement of some kind. A comment will not suffice.
//:
//: Otherwise you will get a compilation error. The following won't compile because there is an
//: empty case statement:
//:
//: let anotherCharacter: Character = "a"
//: switch anotherCharacter
//: {
//: case "a":
//: case "A":
//: "the letter a"
//: default:
//: "not the letter a"
//: }
//: We can perform range matching for cases:
let count = 3_000_000_000_000
switch count
{
case 0:
"no"
case 1...3:
"a few"
case 4...9:
"several"
case 10...99:
"tens of"
case 100...999:
"hundreds of"
case 1000...999999:
"thousands of"
default:
"millions and millions of"
}
//: Matching against tuples
//:
//: In addition to matching Tuples, we can also use ranges inside Tuple values and even match
//: against partial Tuple values by using an "_" to ignore matches against a specific value within
//: the Tuple.
let somePoint = (1,1)
switch somePoint
{
case (0,0):
"origin"
// Match only against y=0
case (_, 0):
"On the X axis"
// Match only against x=0
case (0, _):
"On the y axis"
// Match x and y from -2 to +2 (inclusive)
case (-2...2, -2...2):
"On or inside the 2x2 box"
// Everything else
default:
"Outisde the 2x2 box"
}
//: Value bindings in switch statements
//:
var anotherPoint = (2, 8)
switch anotherPoint
{
// Bind 'x' to the first value (matching any x) of the tuple and match on y=0
case (let x, 0):
"On the x axis with an x value of \(x)"
// Bind 'y' to the second value (matching any y) of the tuple and match against x=0
case (0, let y):
"On the y axis with an y value of \(y)"
// Bind both values of the tuple, matching any x or y. Note the shorthand of the 'let'
// outside of the parenthesis. This works with 'var' as well.
//
// Also notice that since this matches any x or y, we fulfill the requirement for an exhaustive
// switch.
case let (x, y):
"Somewhere else on \(x), \(y)"
}
//: We can also mix let/var for case statements. The following code block is the same as the
//: previous except that the final case statement, which mixes variable and constants for the x and
//: y components of the Tuple.
switch anotherPoint
{
case (let x, 0):
"On the x axis with an x value of \(x)"
case (0, let y):
"On the y axis with an y value of \(y)"
case (var x, let y):
++x // We can modify the variable 'x', but not the constant 'y'
"Somewhere else on \(x), \(y)"
}
//: Where clauses allow us to perform more detailed conditions on case conditions. The where clauses
//: work on the values declared on the case line:
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint
{
case let (x, y) where x == y:
"On the line of x == y"
case let (x, y) where x == -y:
"On the line of x == -y"
case let (x, y):
"Just some arbitrary point"
}
//: *Control Transfer Statements*
//:
//: Control transfer statements change the order in which your code is executed, by transferring control from one piece of code to another. Swift has five control transfer statements:
/*:
* continue
* break
* fallthrough
* return
* throw
*/
//: ------------------------------------------------------------------------------------------------
//: Control transfer statements
//:
//: Swift supports extended versions of continue and break as well as an additional 'fallthrough'
//: statement for switch-case constructs.
//:
//: Since swift doesn't require a break statement to avoid falling through to the next case, we can
//: still use them to early-out of the current case without continuing work. The first statement
//: after the 'break' will be the next statement following the entire switch construct.
let someValue = 9000
switch someValue
{
case let x where (x & 1) == 1:
if someValue < 100
{
"Odd number less than 100"
break
}
"Odd number greater or equal to 100"
case let x where (x & 1) == 0:
if someValue < 100
{
"Even number less than 100"
break
}
"Even number greater or equal to 100"
default:
"Unknown value"
}
//: Since each case must have a statement and since we must have an exhaustive switch, we can use
//: the break statement to effectively nullify the use of a case:
switch someValue
{
case Int.min...100:
"Small number"
case 101...1000:
break // We don't care about medium numbers
case 1001...100_00:
"Big number"
default:
break // We don't care about the rest, either
}
//: Since we don't need to break out of cases to avoid falling through automatically, we must
//: specifically express our intention to fall through using the 'fallthrough' keyword
let integerToDescribe = 5
var integerDescription = "\(integerToDescribe) is"
switch integerToDescribe
{
case 2, 3, 5, 7, 11, 13, 17, 19:
integerDescription += " a prime number, and also"
fallthrough
default:
integerDescription += " an integer."
}
//: Continue and Break statements have been extended in Swift to allow each to specify which
//: switch or loop construct to break out of, or continue to.
//:
//: To enable this, labels are used, similar to labels used by C's goto statement.
//:
//: The following will print each name until it reaches the letter 'a' then skip to the next name
var result = ""
nameLoop: for name in names
{
characterLoop: for character in name.characters
{
theSwitch: switch character
{
case "a":
// Break out of the theSwitch and characterLoop
break characterLoop
default:
result += String(character)
}
}
}
result
//: Similarly, this prints all names without the letter 'a' in them:
result = ""
nameLoop: for name in names
{
characterLoop: for character in name.characters
{
theSwitch: switch character
{
case "a":
// Continue directly to the character loop, bypassing this character in this name
continue characterLoop
default:
result += String(character)
}
}
}
result
//: Similarly, this prints all names until the letter 'x' is found, then aborts all processing by
//: breaking out of the outer loop:
result = ""
nameLoop: for name in names
{
characterLoop: for character in name.characters
{
theSwitch: switch character
{
case "x":
// Break completely out of the outer name loop
break nameLoop
default:
result += String(character)
}
}
}
result
//:: [Next](@next)
|
mit
|
49d90607a2666fc80aa3458eb423a573
| 27.032787 | 183 | 0.626065 | 4.016779 | false | false | false | false |
danger/danger-swift
|
Tests/RunnerLibTests/SPMDangerTests.swift
|
1
|
4013
|
@testable import RunnerLib
import XCTest
final class SPMDangerTests: XCTestCase {
var testPackage: String {
"testPackage.swift"
}
func testItReturnsTrueWhenThePackageHasTheDangerLib() throws {
let spmDanger = SPMDanger(packagePath: testPackage, readFile: { _ in ".library(name: \"DangerDeps\"" })
XCTAssertEqual(spmDanger?.depsLibName, "DangerDeps")
}
func testItReturnsTrueWhenThePackageHasTheDangerLibDividedInMultipleLines() throws {
let packageContent = """
.library(
name: "DangerDeps",
type: .dynamic,
targets: ["DangerDependencies"]),
"""
let spmDanger = SPMDanger(packagePath: testPackage, readFile: { _ in packageContent })
XCTAssertEqual(spmDanger?.depsLibName, "DangerDeps")
}
func testItAcceptsAnythingStartsWithDangerDeps() throws {
let spmDanger = SPMDanger(packagePath: testPackage, readFile: { _ in ".library(name: \"DangerDepsEigen\"" })
XCTAssertEqual(spmDanger?.depsLibName, "DangerDepsEigen")
}
func testItAcceptsAnythingStartsWithDangerDepsButIsDividedInMultipleLines() throws {
let packageContent = """
.library(
name: "DangerDepsEigen",
type: .dynamic,
targets: ["DangerDependencies"]),
"""
let spmDanger = SPMDanger(packagePath: testPackage, readFile: { _ in packageContent })
XCTAssertEqual(spmDanger?.depsLibName, "DangerDepsEigen")
}
func testItReturnsFalseWhenThePackageHasNotTheDangerLib() throws {
try "".write(toFile: testPackage, atomically: false, encoding: .utf8)
XCTAssertNil(SPMDanger(packagePath: testPackage))
}
func testItReturnsFalseWhenThereIsNoPackage() {
XCTAssertNil(SPMDanger(packagePath: testPackage))
}
func testItBuildsTheDependencies() throws {
let executor = MockedExecutor()
SPMDanger(
packagePath: testPackage,
readFile: { _ in ".library(name: \"DangerDeps\"" }
)?.buildDependencies(executor: executor)
XCTAssertEqual(executor.receivedCommands, ["swift build --product DangerDeps"])
}
func testItReturnsTheCorrectXcodeDepsFlagsWhenThereIsNoDangerLib() throws {
let fileManager = StubbedFileManager()
fileManager.stubbedFileExists = false
XCTAssertEqual(
SPMDanger(
packagePath: testPackage,
readFile: { _ in ".library(name: \"DangerDepsEigen\"" },
fileManager: fileManager
)?.xcodeImportFlags,
["-l DangerDepsEigen"]
)
}
func testItReturnsTheCorrectXcodeDepsFlagsWhenThereIsTheDangerLib() throws {
let fileManager = StubbedFileManager()
fileManager.stubbedFileExists = true
XCTAssertEqual(
SPMDanger(packagePath: testPackage, readFile: { _ in ".library(name: \"DangerDepsEigen\"" }, fileManager: fileManager)?.xcodeImportFlags,
["-l DangerDepsEigen", "-l Danger"]
)
}
func testItReturnsTheCorrectSwiftcDepsImport() throws {
XCTAssertEqual(
SPMDanger(
packagePath: testPackage,
readFile: { _ in ".library(name: \"DangerDepsEigen\"" }
)?.swiftcLibImport,
"-lDangerDepsEigen"
)
}
func testItReturnsTheCorrectBuildFolder() throws {
XCTAssertEqual(
SPMDanger(
packagePath: testPackage,
readFile: { _ in ".library(name: \"DangerDepsEigen\"" },
fileManager: StubbedFileManager()
)?.buildFolder,
"testPath/.build/debug"
)
}
}
private class StubbedFileManager: FileManager {
fileprivate var stubbedFileExists: Bool = true
override func fileExists(atPath _: String) -> Bool {
stubbedFileExists
}
override var currentDirectoryPath: String {
"testPath"
}
}
|
mit
|
bde7e9dbd9cf093df112eb646f3d62a9
| 31.362903 | 149 | 0.629205 | 4.942118 | false | true | false | false |
pkl728/ZombieInjection
|
ZombieInjectionTests/ZombieDetailViewModelTests.swift
|
1
|
1851
|
//
// ZombieDetailViewModelTests.swift
// ZombieInjection
//
// Created by Patrick Lind on 8/9/16.
// Copyright © 2016 Patrick Lind. All rights reserved.
//
import XCTest
@testable import ZombieInjection
class ZombieDetailViewModelTests: XCTestCase {
var zombieDetailViewModel: ZombieDetailViewModel!
var zombieServiceMock: ZombieServiceMock!
var zombieRepositoryMock: ZombieRepositoryMock!
var zombieSelected: Zombie!
var goBackCallBackCalled = false
override func setUp() {
super.setUp()
zombieSelected = Zombie(id: 0, name: "Selected", imageUrlAddress: nil)
zombieRepositoryMock = ZombieRepositoryMock()
zombieRepositoryMock.deleteAll()
zombieRepositoryMock.insert(zombieSelected)
zombieServiceMock = ZombieServiceMock(zombieRepository: zombieRepositoryMock)
zombieDetailViewModel = ZombieDetailViewModel(zombie: zombieSelected, zombieService: zombieServiceMock, goBackCallBack: { self.goBackCallBackCalled = true })
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
self.zombieRepositoryMock.deleteAll()
self.goBackCallBackCalled = false
}
func testSaveUpdatesZombie() {
// Arrange
self.zombieSelected.name.value = "Updated"
// Act
self.zombieDetailViewModel.save()
// Assert
XCTAssert(self.zombieRepositoryMock.get(0)?.name.value == "Updated")
}
func testSaveExercisesGoBackCallBack() {
// Arrange
self.zombieSelected.name.value = "Updated"
// Act
self.zombieDetailViewModel.save()
// Assert
XCTAssert(self.goBackCallBackCalled)
}
}
|
mit
|
7ea2f1df12d2cc9afb50d137a5fe641d
| 30.355932 | 165 | 0.672432 | 5.138889 | false | true | false | false |
alblue/swift
|
validation-test/compiler_crashers_2_fixed/0090-sr4617.swift
|
54
|
388
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir
extension Dictionary {
init<S: Sequence>(grouping elements: S, by keyForValue: (S.Iterator.Element) -> Key)
where Array<S.Iterator.Element> == Value
{
self = [:]
for value in elements {
var values = self[keyForValue(value)] ?? []
values.append(value)
self[keyForValue(value)] = values
}
}
}
|
apache-2.0
|
23cae39cb5b8a37752e4b4a635cb977a
| 26.714286 | 86 | 0.634021 | 3.464286 | false | false | false | false |
zyphs21/HSStockChart
|
HSStockChart/TimeLineChart/HSTimeLineCoordModel.swift
|
1
|
390
|
//
// HSTimeLineCoordModel.swift
// dingdong
//
// Created by Hanson on 2017/1/19.
// Copyright © 2017年 vanyun. All rights reserved.
//
import UIKit
public struct HSTimeLineCoordModel {
var pricePoint: CGPoint = .zero
var avgPoint: CGPoint = .zero
var volumeHeight: CGFloat = 0
var volumeStartPoint: CGPoint = .zero
var volumeEndPoint: CGPoint = .zero
}
|
mit
|
3e55c3d9fb4e353b30e7e9f5ef5ec17b
| 18.35 | 50 | 0.682171 | 3.486486 | false | false | false | false |
TinyCrayon/TinyCrayon-iOS-SDK
|
TCMask/TCMask.swift
|
1
|
4456
|
//
// TCMask.swift
// TinyCrayon
//
// Created by Xin Zeng on 6/12/16.
//
//
import UIKit
import TCCore
/**
TCMask is the masking result from TCMaskView
*/
@objcMembers
open class TCMask : NSObject {
/// Data of masking result
public let data: [UInt8]
/// Size of mask
public let size: CGSize
/// Initialize a TCMask
public init(data: [UInt8], size: CGSize) {
self.data = data
self.size = size
}
/**
Create a gray scale UIImage from mask
- returns: Gray scale image converted from mask
*/
open func grayScaleImage() -> UIImage {
var maskData = data
let width = Int(size.width)
let height = Int(size.height)
let ctx = CGContext(data: &maskData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)!
return UIImage(cgImage: ctx.makeImage()!)
}
/**
Create a RGBA UIImage from mask
- returns: RGBA image converted from mask, with the alpha info of premultiplied last. If a pixel value of mask is v, the corrosponding pixel value of returned RGBA image is (v, v, v, v)
*/
open func rgbaImage() -> UIImage {
return TCCore.image(fromAlpha: data, size: size)
}
/**
Create a new mask which is the inversion of the original mask
*/
open func inverted() -> TCMask {
var invertedData = [UInt8](repeating: 0, count: data.count)
TCCore.invertAlpha(&invertedData, count: invertedData.count)
return TCMask(data: invertedData, size: size)
}
/**
Cutout a image using mask
- parameter image: Image to cutout
- parameter resize: Specify true to resize the output image to fit the result size
- returns: Nil if resize is set to true and mask only contains 0, otherwise image with cutout
*/
open func cutout(image: UIImage, resize: Bool) -> UIImage? {
var rect = CGRect()
return cutout(image: image, resize: resize, outputRect: &rect)
}
/**
Cutout an image using mask
- parameter image: Image to cutout
- parameter resize: Specify true to resize the output image to fit the result size
- parameter outputRect: OUT parameter, which returns The rect of output image in original image. If the result image is nil, outputRect will be (0, 0, 0, 0); If resize is set to false, outputRect will be (0, 0, image.width, image.height)
- returns: Nil if resize is set to true and mask only contains 0, result image with cutout otherwise
*/
open func cutout(image: UIImage, resize: Bool, outputRect: inout CGRect) -> UIImage? {
assert(image.size == self.size, "image size is not equal to mask size")
var offset = CGPoint()
let retval = TCCore.image(withAlpha: image.normalize(), alpha: data, compact: resize, offset: &offset)
if retval == nil {
outputRect = CGRect()
}
else {
outputRect = CGRect(origin: offset, size: retval!.size)
}
return retval
}
/**
Create an image blended with mask
- parameter foregroundImage: Foregournd image, image size should match mask size
- parameter backgroundImage: Background image, image size should match mask size
- returns: Blended image
*/
open func blend(foregroundImage: UIImage, backgroundImage: UIImage) -> UIImage {
assert(foregroundImage.size == self.size, "foreground image size is not equal to mask size")
assert(backgroundImage.size == self.size, "background image size is not equal to mask size")
let fimage = foregroundImage.normalize()
let bimage = backgroundImage.normalize()
let width = Int(fimage.size.width)
let height = Int(fimage.size.height)
let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.draw(backgroundImage.cgImage!, in: CGRect(origin: CGPoint(), size: bimage.size))
ctx.setBlendMode(.sourceAtop)
ctx.draw(cutout(image: fimage, resize: false)!.cgImage!, in: CGRect(origin: CGPoint(), size: self.size))
return UIImage(cgImage: ctx.makeImage()!)
}
}
|
mit
|
cd21c74562d9dd703f55ed62f8b2dfac
| 36.133333 | 242 | 0.644075 | 4.381514 | false | false | false | false |
AlexRamey/mbird-iOS
|
Pods/Nuke/Sources/Preheater.swift
|
1
|
3271
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Prefetches and caches image in order to eliminate delays when you request
/// individual images later.
///
/// To start preheating call `startPreheating(with:)` method. When you
/// need an individual image just start loading an image using `Loading` object.
/// When preheating is no longer necessary call `stopPreheating(with:)` method.
///
/// All `Preheater` methods are thread-safe.
public final class Preheater {
private let manager: Manager
private let queue = DispatchQueue(label: "com.github.kean.Nuke.Preheater")
private let preheatQueue = OperationQueue()
private var tasks = [AnyHashable: Task]()
/// Initializes the `Preheater` instance.
/// - parameter manager: `Manager.shared` by default.
/// - parameter `maxConcurrentRequestCount`: 2 by default.
public init(manager: Manager = Manager.shared, maxConcurrentRequestCount: Int = 2) {
self.manager = manager
self.preheatQueue.maxConcurrentOperationCount = maxConcurrentRequestCount
}
/// Preheats images for the given requests.
///
/// When you call this method, `Preheater` starts to load and cache images
/// for the given requests. At any time afterward, you can create tasks
/// for individual images with equivalent requests.
public func startPreheating(with requests: [Request]) {
queue.async {
requests.forEach(self._startPreheating)
}
}
private func _startPreheating(with request: Request) {
let key = request.loadKey
guard tasks[key] == nil else { return } // already exists
let task = Task(request: request, key: key)
let token = task.cts.token
let operation = Operation(starter: { [weak self] finish in
self?.manager.loadImage(with: request, token: token) { _ in
self?._remove(task)
finish()
}
token.register(finish)
})
preheatQueue.addOperation(operation)
token.register { [weak operation] in operation?.cancel() }
tasks[key] = task
}
private func _remove(_ task: Task) {
queue.async {
guard self.tasks[task.key] === task else { return }
self.tasks[task.key] = nil
}
}
/// Stops preheating images for the given requests and cancels outstanding
/// requests.
public func stopPreheating(with requests: [Request]) {
queue.async {
requests.forEach(self._stopPreheating)
}
}
private func _stopPreheating(with request: Request) {
if let task = tasks[request.loadKey] {
tasks[task.key] = nil
task.cts.cancel()
}
}
/// Stops all preheating tasks.
public func stopPreheating() {
queue.async {
self.tasks.forEach { $0.1.cts.cancel() }
self.tasks.removeAll()
}
}
private final class Task {
let key: AnyHashable
let request: Request
let cts = CancellationTokenSource()
init(request: Request, key: AnyHashable) {
self.request = request
self.key = key
}
}
}
|
mit
|
a421a197c133c8ebb78761cec7420804
| 31.71 | 88 | 0.623662 | 4.530471 | false | false | false | false |
lukevanin/onthemap
|
OnTheMap/MapViewController.swift
|
1
|
3940
|
//
// MapViewController.swift
// OnTheMap
//
// Created by Luke Van In on 2017/01/12.
// Copyright © 2017 Luke Van In. All rights reserved.
//
// Display locations of students on a zoomable, scrollable map. Tapping a pin shows a callout with the student's name
// and media URL (if present). Tapping the callout opens the media URL in a browser. Delegates data and actions to an
// external object.
//
import UIKit
import MapKit
class MapViewController: StudentsViewController {
//
// Custom MKPointAnnotation class used to associate student information with pin locations on the map.
//
class StudentAnnotation: MKPointAnnotation {
var student: StudentInformation?
}
// MARK: Outlets
@IBOutlet weak var mapView: MKMapView!
// MARK: Pins
//
// Update the annotations on the map. An annotation is created for each student location in the model. The
// annotation contains data for the coordinates of where the pin should appear, as well as the name and URL to
// show when the pin is tapped. The annotation is used to instantiate a view for the pin (see MKMapViewDelegate
// below).
//
override func updateContent() {
mapView.removeAnnotations(mapView.annotations)
if let annotations = makeAnnotations() {
mapView.addAnnotations(annotations)
}
}
//
// Creates any array annotations from the model containing student information entries.
//
private func makeAnnotations() -> [MKAnnotation]? {
return model.students.map(makeAnnotationForStudent)
}
//
// Creates a single annotation for a student information entity.
//
private func makeAnnotationForStudent(info: StudentInformation) -> StudentAnnotation {
let output = StudentAnnotation()
output.student = info
output.coordinate = CLLocationCoordinate2D(latitude: info.location.latitude, longitude: info.location.longitude)
output.title = info.user.firstName + " " + info.user.lastName
output.subtitle = info.location.validURL?.absoluteString ?? nil
return output
}
}
//
// Extension for the MapViewController to control rendering and interactions for map pins.
//
extension MapViewController: MKMapViewDelegate {
//
// Create a view for a given annotation. Uses a recycled view from the pool if available. An info ⓘ button is
// displayed on the annotation if the student information associated with the annotation has a valid URL.
//
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseIdentifier = "StudentAnnotation"
var view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
view?.canShowCallout = true
if let studentAnnotation = annotation as? StudentAnnotation, let info = studentAnnotation.student, info.location.hasValidURL {
let infoButton = UIButton(type: .infoLight)
infoButton.tintColor = UIColor(hue: 30.0 / 360.0, saturation: 1.0, brightness: 1.0, alpha: 1.00)
view?.rightCalloutAccessoryView = infoButton
}
else {
view?.rightCalloutAccessoryView = nil
}
}
return view
}
//
// Handles user tapping on the annotation view. Opens the user's media URL in a browser.
//
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
guard let annotation = view.annotation as? StudentAnnotation, let info = annotation.student else {
return
}
delegate?.showInformationForStudent(info)
}
}
|
mit
|
7a6139a18fd504f08e131a907949f87b
| 37.223301 | 138 | 0.671577 | 5.08 | false | false | false | false |
porkbuns/shmile-ios
|
Pods/Socket.IO-Client-Swift/SocketIOClientSwift/SocketIOClient.swift
|
2
|
16031
|
//
// SocketIOClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 11/23/14.
//
// 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.
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient {
private var anyHandler:((SocketAnyEvent) -> Void)?
private var _closed = false
private var _connected = false
private var _connecting = false
private var currentReconnectAttempt = 0
private var handlers = ContiguousArray<SocketEventHandler>()
private var connectParams:[String: AnyObject]?
private var _secure = false
private var _reconnecting = false
private var reconnectTimer:NSTimer?
let reconnectAttempts:Int!
let logType = "SocketClient"
var ackHandlers = SocketAckManager()
var currentAck = -1
var log = false
var waitingData = ContiguousArray<SocketPacket>()
var sessionDelegate:NSURLSessionDelegate?
public let socketURL:String
public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL)
public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
public var closed:Bool {
return _closed
}
public var connected:Bool {
return _connected
}
public var connecting:Bool {
return _connecting
}
public var engine:SocketEngine?
public var nsp = "/"
public var opts:[String: AnyObject]?
public var reconnects = true
public var reconnecting:Bool {
return _reconnecting
}
public var reconnectWait = 10
public var secure:Bool {
return _secure
}
public var sid:String? {
return engine?.sid
}
/**
Create a new SocketIOClient. opts can be omitted
*/
public init(var socketURL:String, opts:[String: AnyObject]? = nil) {
if socketURL["https://"].matches().count != 0 {
self._secure = true
}
socketURL = socketURL["http://"] ~= ""
socketURL = socketURL["https://"] ~= ""
self.socketURL = socketURL
self.opts = opts
// Set options
if let sessionDelegate = opts?["sessionDelegate"] as? NSURLSessionDelegate {
self.sessionDelegate = sessionDelegate
}
if let connectParams = opts?["connectParams"] as? [String: AnyObject] {
self.connectParams = connectParams
}
if let log = opts?["log"] as? Bool {
self.log = log
}
if var nsp = opts?["nsp"] as? String {
if nsp != "/" && nsp.hasPrefix("/") {
nsp.removeAtIndex(nsp.startIndex)
}
self.nsp = nsp
}
if let reconnects = opts?["reconnects"] as? Bool {
self.reconnects = reconnects
}
if let reconnectAttempts = opts?["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts?["reconnectWait"] as? Int {
self.reconnectWait = abs(reconnectWait)
}
super.init()
}
public convenience init(socketURL:String, options:[String: AnyObject]?) {
self.init(socketURL: socketURL, opts: options)
}
deinit {
SocketLogger.log("Client is being deinit", client: self)
engine?.close(fast: true)
}
private func addEngine() {
SocketLogger.log("Adding engine", client: self)
engine = SocketEngine(client: self, opts: opts)
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close(#fast:Bool) {
SocketLogger.log("Closing socket", client: self)
reconnects = false
_connecting = false
_connected = false
_reconnecting = false
engine?.close(fast: fast)
engine = nil
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
if closed {
SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self)
_closed = false
} else if connected {
return
}
_connecting = true
addEngine()
engine?.open(opts: connectParams)
if timeoutAfter == 0 {
return
}
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
if let this = self where !this.connected {
this._closed = true
this._connecting = false
this.engine?.close(fast: true)
handler?()
}
}
}
private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {[weak this] in
this?._emit(event, items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {[weak this] in
this?.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
SocketLogger.log("Socket connected", client: self)
_closed = false
_connected = true
_connecting = false
_reconnecting = false
currentReconnectAttempt = 0
reconnectTimer?.invalidate()
reconnectTimer = nil
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: nil, isInternalMessage: false)
}
func didDisconnect(reason:String) {
if closed {
return
}
SocketLogger.log("Disconnected: %@", client: self, args: reason)
_closed = true
_connected = false
reconnects = false
_connecting = false
_reconnecting = false
// Make sure the engine is actually dead.
engine?.close(fast: true)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason:AnyObject) {
SocketLogger.err("%@", client: self, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect(#fast:Bool) {
close(fast: fast)
}
/**
Send a message to the server
*/
public func emit(event:String, _ items:AnyObject...) {
if !connected {
return
}
dispatch_async(emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event:String, withItems items:[AnyObject]) {
if !connected {
return
}
dispatch_async(emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
public func emitWithAck(event:String, _ items:AnyObject...) -> OnAckCallback {
if !connected {
return createOnAck(event, items: items)
}
return createOnAck(event, items: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback {
if !connected {
return createOnAck(event, items: items)
}
return createOnAck(event, items: items)
}
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
if !connected {
return
}
let packet = SocketPacket(type: nil, data: args, nsp: nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createMessageForEvent(event)
SocketLogger.log("Emitting: %@", client: self, args: str)
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
engine?.send(str, withData: packet.binary)
} else {
engine?.send(str, withData: nil)
}
}
// If the server wants to know that the client received data
func emitAck(ack:Int, withData args:[AnyObject]) {
dispatch_async(emitQueue) {[weak self] in
if let this = self where this.connected {
let packet = SocketPacket(type: nil, data: args, nsp: this.nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createAck()
SocketLogger.log("Emitting Ack: %@", client: this, args: str)
if packet.type == SocketPacket.PacketType.BINARY_ACK {
this.engine?.send(str, withData: packet.binary)
} else {
this.engine?.send(str, withData: nil)
}
}
}
}
public func engineDidClose(reason:String) {
_connected = false
_connecting = false
if closed || !reconnects {
didDisconnect(reason)
} else if !reconnecting {
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack:Int, data:AnyObject?) {
SocketLogger.log("Handling ack: %@ with data: %@", client: self,
args: ack, data ?? "")
ackHandlers.executeAck(ack,
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil) {
// println("Should do event: \(event) with data: \(data)")
if !connected && !isInternalMessage {
return
}
SocketLogger.log("Handling event: %@ with data: %@", client: self,
args: event, data ?? "")
if anyHandler != nil {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
}
}
for handler in handlers {
if handler.event == event {
if ack != nil {
handler.executeCallback(data, withAck: ack!, withSocket: self)
} else {
handler.executeCallback(data)
}
}
}
}
/**
Leaves nsp and goes back to /
*/
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1/\(nsp)", withData: nil)
nsp = "/"
}
}
/**
Joins nsp if it is not /
*/
public func joinNamespace() {
SocketLogger.log("Joining namespace", client: self)
if nsp != "/" {
engine?.send("0/\(nsp)", withData: nil)
}
}
/**
Removes handler(s)
*/
public func off(event:String) {
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
handlers = handlers.filter {$0.event == event ? false : true}
}
/**
Adds a handler for an event.
*/
public func on(event:String, callback:NormalCallback) {
SocketLogger.log("Adding handler for event: %@", client: self, args: event)
let handler = SocketEventHandler(event: event, callback: callback)
handlers.append(handler)
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler:(SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
public func open() {
connect()
}
public func parseSocketMessage(msg:String) {
SocketParser.parseSocketMessage(msg, socket: self)
}
public func parseBinaryData(data:NSData) {
SocketParser.parseBinaryData(data, socket: self)
}
/**
Trieds to reconnect to the server.
*/
public func reconnect() {
_connected = false
_connecting = false
_reconnecting = false
engine?.stopPolling()
tryReconnect()
}
// We lost connection and should attempt to reestablish
@objc private func tryReconnect() {
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts {
didDisconnect("Reconnect Failed")
return
} else if connected {
_connecting = false
_reconnecting = false
return
}
if reconnectTimer == nil {
SocketLogger.log("Starting reconnect", client: self)
_reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if let this = self {
this.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(this.reconnectWait),
target: this, selector: "tryReconnect", userInfo: nil, repeats: true)
}
}
}
SocketLogger.log("Trying to reconnect", client: self)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt++
connect()
}
}
|
mit
|
07901f52996ca44de55112b1b97a7d38
| 30.249513 | 114 | 0.556609 | 4.862299 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
Foundation/NotificationQueue.swift
|
1
|
7371
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
extension NotificationQueue {
public enum PostingStyle : UInt {
case whenIdle = 1
case asap = 2
case now = 3
}
public struct NotificationCoalescing : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let none = NotificationCoalescing(rawValue: 0)
public static let onName = NotificationCoalescing(rawValue: 1 << 0)
public static let onSender = NotificationCoalescing(rawValue: 1 << 1)
}
}
open class NotificationQueue: NSObject {
internal typealias NotificationQueueList = NSMutableArray
internal typealias NSNotificationListEntry = (Notification, [RunLoopMode]) // Notification ans list of modes the notification may be posted in.
internal typealias NSNotificationList = [NSNotificationListEntry] // The list of notifications to post
internal let notificationCenter: NotificationCenter
internal var asapList = NSNotificationList()
internal var idleList = NSNotificationList()
internal lazy var idleRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeTimers), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.whenIdle)
}
}()
internal lazy var asapRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeWaiting | kCFRunLoopExit), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.asap)
}
}()
// The NSNotificationQueue instance is associated with current thread.
// The _notificationQueueList represents a list of notification queues related to the current thread.
private static var _notificationQueueList = NSThreadSpecific<NSMutableArray>()
internal static var notificationQueueList: NotificationQueueList {
return _notificationQueueList.get() {
return NSMutableArray()
}
}
// The default notification queue for the current thread.
private static var _defaultQueue = NSThreadSpecific<NotificationQueue>()
open class var `default`: NotificationQueue {
return _defaultQueue.get() {
return NotificationQueue(notificationCenter: NotificationCenter.default)
}
}
public init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
NotificationQueue.registerQueue(self)
}
deinit {
NotificationQueue.unregisterQueue(self)
removeRunloopObserver(self.idleRunloopObserver)
removeRunloopObserver(self.asapRunloopObserver)
}
open func enqueue(_ notification: Notification, postingStyle: PostingStyle) {
enqueue(notification, postingStyle: postingStyle, coalesceMask: [.onName, .onSender], forModes: nil)
}
open func enqueue(_ notification: Notification, postingStyle: PostingStyle, coalesceMask: NotificationCoalescing, forModes modes: [RunLoopMode]?) {
var runloopModes: [RunLoopMode] = [.defaultRunLoopMode]
if let modes = modes {
runloopModes = modes
}
if !coalesceMask.isEmpty {
self.dequeueNotifications(matching: notification, coalesceMask: coalesceMask)
}
switch postingStyle {
case .now:
let currentMode = RunLoop.current.currentMode
if currentMode == nil || runloopModes.contains(currentMode!) {
self.notificationCenter.post(notification)
}
case .asap: // post at the end of the current notification callout or timer
addRunloopObserver(self.asapRunloopObserver)
self.asapList.append((notification, runloopModes))
case .whenIdle: // wait until the runloop is idle, then post the notification
addRunloopObserver(self.idleRunloopObserver)
self.idleList.append((notification, runloopModes))
}
}
open func dequeueNotifications(matching notification: Notification, coalesceMask: NotificationCoalescing) {
var predicate: (NSNotificationListEntry) -> Bool
switch coalesceMask {
case [.onName, .onSender]:
predicate = { entry in
return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object) || notification.name != entry.0.name
}
case [.onName]:
predicate = { entry in
return notification.name != entry.0.name
}
case [.onSender]:
predicate = { entry in
return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object)
}
default:
return
}
self.asapList = self.asapList.filter(predicate)
self.idleList = self.idleList.filter(predicate)
}
// MARK: Private
private func addRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private func removeRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private func notify(_ currentMode: RunLoopMode?, notificationList: inout NSNotificationList) {
for (idx, (notification, modes)) in notificationList.enumerated().reversed() {
if currentMode == nil || modes.contains(currentMode!) {
self.notificationCenter.post(notification)
notificationList.remove(at: idx)
}
}
}
/**
Gets queues from the notificationQueueList and posts all notification from the list related to the postingStyle parameter.
*/
private func notifyQueues(_ postingStyle: PostingStyle) {
let currentMode = RunLoop.current.currentMode
for queue in NotificationQueue.notificationQueueList {
let notificationQueue = queue as! NotificationQueue
if postingStyle == .whenIdle {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.idleList)
} else {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.asapList)
}
}
}
private static func registerQueue(_ notificationQueue: NotificationQueue) {
self.notificationQueueList.add(notificationQueue)
}
private static func unregisterQueue(_ notificationQueue: NotificationQueue) {
guard self.notificationQueueList.index(of: notificationQueue) != NSNotFound else {
return
}
self.notificationQueueList.remove(notificationQueue)
}
}
|
apache-2.0
|
43933378d197135f9732b8c79d72d062
| 40.410112 | 171 | 0.685796 | 5.492548 | false | false | false | false |
wangela/wittier
|
wittier/ViewControllers/TweetViewController.swift
|
1
|
10584
|
//
// TweetViewController.swift
// wittier
//
// Created by Angela Yu on 9/26/17.
// Copyright © 2017 Angela Yu. All rights reserved.
//
import UIKit
@objc protocol TweetViewControllerDelegate {
@objc optional func tweetViewController(tweetViewController: TweetViewController, replyToID: Int64, tweeted string: String)
}
class TweetViewController: UIViewController, UITextViewDelegate {
// maintweetView outlets
@IBOutlet weak var scrollframeView: UIScrollView!
@IBOutlet weak var boxView: UIView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var screennameLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var statsLabel: UILabel!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var faveButton: UIButton!
// rewteetView outlets
@IBOutlet weak var retweetView: UIView!
@IBOutlet weak var retweeterLabel: UILabel!
@IBOutlet weak var replytweetView: UIView!
@IBOutlet weak var retweetTopConstraint: NSLayoutConstraint!
@IBOutlet weak var retweeterDisplayConstraint: NSLayoutConstraint!
// replytweetView outlets
@IBOutlet weak var counterLabel: UILabel!
@IBOutlet weak var composeTextView: UITextView!
@IBOutlet weak var contentView: UIView!
@IBOutlet var counterTopContstraint: NSLayoutConstraint!
@IBOutlet var composeCounterConstraint: NSLayoutConstraint!
@IBOutlet var bottomComposeConstraint: NSLayoutConstraint!
weak var delegate: TweetViewControllerDelegate?
var tweet: Tweet!
var retweeter: User?
var replying: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// If this is a retweet, show the retweet view
showOrHideRetweet()
// Populate basic tweet display
guard let user = tweet.user else { return }
displayNameLabel.text = user.name
screennameLabel.text = user.screenname
tweetLabel.text = tweet.text
tweetLabel.sizeToFit()
if let profileURL = user.profileURL {
profileImageView.setImageWith(profileURL)
} else {
profileImageView.image = nil
}
profileImageView.layer.cornerRadius = 5
profileImageView.clipsToBounds = true
// Build formatted date
if let timestamp = tweet.timestamp {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
if let timestampDate = formatter.date(from: timestamp) {
formatter.dateFormat = "EEE MMM d, h:mm a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let detailTimestamp = formatter.string(from: timestampDate)
timestampLabel.text = detailTimestamp
}
}
// Build stats string
updateStats()
// View setup
boxView.layer.cornerRadius = 5
scrollframeView.contentSize = CGSize(width: scrollframeView.frame.size.width, height: boxView.frame.origin.y + boxView.frame.size.height + 20)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// If the user wants to reply
composeTextView.delegate = self
if replying {
onReplyButton(replyButton)
} else {
replytweetView.isHidden = true
NSLayoutConstraint.deactivate([counterTopContstraint, composeCounterConstraint, bottomComposeConstraint])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showOrHideRetweet() {
if let retweetUser = retweeter {
if let retweeterName = retweetUser.name {
retweeterLabel.text = "\(retweeterName) Retweeted"
} else {
retweeterLabel.text = "Somebody Retweeted" // shouldn't happen
}
retweetView.isHidden = false
retweetTopConstraint.isActive = true
retweeterDisplayConstraint.isActive = true
} else {
retweetView.isHidden = true
retweetTopConstraint.isActive = false
retweeterDisplayConstraint.isActive = false
}
}
func updateStats() {
let statsString = "\(tweet.retweetCount) Retweets \(tweet.favoritesCount) Likes"
statsLabel.text = statsString
if tweet.favorited {
faveButton.setImage(#imageLiteral(resourceName: "favorite-blk"), for: .normal)
} else {
faveButton.setImage(#imageLiteral(resourceName: "favorite-aaa"), for: .normal)
}
if tweet.retweeted {
retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: .normal)
} else {
retweetButton.setImage(#imageLiteral(resourceName: "retweet-aaa"), for: .normal)
}
}
// MARK: - Buttons
@IBAction func onReplyButton(_ sender: Any) {
guard let origUser = tweet.user else { return }
var username = "\(origUser.screenname) "
if let rtUser = retweeter {
username.append("\(rtUser.screenname) ")
}
let tweetButton = UIBarButtonItem(title: "Tweet", style: .plain, target: self, action: #selector(tweetReply(_:)))
navigationItem.rightBarButtonItem = tweetButton
replyButton.setImage(#imageLiteral(resourceName: "reply"), for: .normal)
composeTextView.text = "\(username)"
let length = username.count
DispatchQueue.main.async {
self.composeTextView.selectedRange = NSRange(location: length, length: 0)
}
replytweetView.isHidden = false
NSLayoutConstraint.activate([counterTopContstraint, composeCounterConstraint, bottomComposeConstraint])
scrollframeView.contentSize = CGSize(width: scrollframeView.frame.size.width, height: boxView.frame.origin.y + boxView.frame.size.height + 20)
composeTextView.becomeFirstResponder()
}
@IBAction func onRetweetButton(_ sender: Any) {
guard let tweetID = tweet.idNum else {
print("bad tweet ID")
return
}
let rtState = tweet.retweeted
let rtCount = tweet.retweetCount
if rtState {
TwitterClient.sharedInstance.retweet(retweetMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.retweeted = !rtState
self.tweet.retweetCount = rtCount - 1
self.updateStats()
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
} else {
TwitterClient.sharedInstance.retweet(retweetMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.retweeted = !rtState
self.tweet.retweetCount = rtCount + 1
self.updateStats()
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
}
}
@IBAction func onFaveButton(_ sender: Any) {
guard let tweetID = tweet.idNum else {
print("bad tweet ID")
return
}
let faveState = tweet.favorited
let faveCount = tweet.favoritesCount
if faveState {
TwitterClient.sharedInstance.fave(faveMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.favorited = !faveState
self.tweet.favoritesCount = faveCount - 1
self.updateStats()
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
} else {
TwitterClient.sharedInstance.fave(faveMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.favorited = !faveState
self.tweet.favoritesCount = faveCount + 1
self.updateStats()
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
}
}
// MARK: - Composing a reply
func keyboardWillShow(notification: NSNotification) {
print("keyboard will show")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var contentInset: UIEdgeInsets = self.scrollframeView.contentInset
contentInset.bottom = keyboardSize.height
self.scrollframeView.contentInset = contentInset
print ("\(self.contentView.frame.origin.y)")
print("\(keyboardSize.height)")
if self.contentView.frame.origin.y == 0 {
self.contentView.frame.origin.y -= keyboardSize.height
print("made it")
}
}
}
func keyboardWillHide(notification: NSNotification) {
print("keyboard will hide")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let contentInset: UIEdgeInsets = UIEdgeInsets.zero
self.scrollframeView.contentInset = contentInset
if self.contentView.frame.origin.y != 0 {
self.contentView.frame.origin.y += keyboardSize.height
print("exiting keyboard")
}
}
}
// Show countdown from 140 characters
func textViewDidChange(_ textView: UITextView) {
let length = composeTextView.text.count
let charsLeft = 140 - length
counterLabel.text = String(charsLeft)
if charsLeft < 20 {
counterLabel.textColor = UIColor.red
} else {
counterLabel.textColor = UIColor.darkGray
}
}
func tweetReply(_ sender: Any) {
guard let tweetText = composeTextView.text else {
print("nil tweet, canceling")
return
}
delegate?.tweetViewController?(tweetViewController: self, replyToID: tweet.idNum!, tweeted: tweetText)
}
}
|
mit
|
c7a71ac633e4707263e677c285fe5c27
| 38.935849 | 165 | 0.624303 | 5.068487 | false | false | false | false |
elpassion/el-space-ios
|
ELSpaceTests/TestCases/Snapshots/ActivitiesViewTests.swift
|
1
|
3649
|
import Quick
import Nimble
import Nimble_Snapshots
import FBSnapshotTestCase
@testable import ELSpace
class ActivitiesViewTests: QuickSpec {
override func spec() {
describe("ActivitiesViewTests") {
var sut: ActivitiesView!
beforeEach {
sut = ActivitiesView()
sut.frame = UIScreen.main.bounds
}
context("when initalize with coder") {
it("should throw fatal error") {
expect { _ = ReportView(coder: NSCoder()) }.to(throwAssertion())
}
}
describe("6 different ReportView") {
beforeEach {
sut.stackView.addArrangedSubview(self.fakeReportView)
sut.stackView.addArrangedSubview(self.fakeReportViewAllCornersRounded)
sut.stackView.addArrangedSubview(self.fakeReportViewTopCornersRounded)
sut.stackView.addArrangedSubview(self.fakeReportViewBottomCornersRounded)
sut.stackView.addArrangedSubview(self.fakeReportViewWithDetails)
sut.stackView.addArrangedSubview(self.fakeReportViewWithSeparator)
}
xit("should have valid snapshot") {
expect(sut).to(haveValidDeviceAgnosticSnapshot())
}
}
}
}
// MARK: - ReportView fakes
private var fakeReportView: ReportView {
let view = ReportView()
view.dateLabel.text = "fake_date"
view.rightStripeView.backgroundColor = .red
view.contentContainer.backgroundColor = .yellow
view.titleLabel.text = "very very very very very very long title"
view.addIconControl.subviews.forEach {
if let imageView = $0 as? UIImageView {
imageView.image = UIImage.fakeImage(width: 19, height: 19)
}
}
view.separatorView.isHidden = true
return view
}
private var fakeReportViewAllCornersRounded: ReportView {
let view = fakeReportView
view.areBottomCornersRounded = true
view.areTopCornersRounded = true
view.titleLabel.text = "All corners rounded"
return view
}
private var fakeReportViewTopCornersRounded: ReportView {
let view = fakeReportView
view.areTopCornersRounded = true
view.titleLabel.text = "Top corners rounded"
return view
}
private var fakeReportViewBottomCornersRounded: ReportView {
let view = fakeReportView
view.areBottomCornersRounded = true
view.titleLabel.text = "Bottom corners rounded"
return view
}
private var fakeReportViewWithSeparator: ReportView {
let view = fakeReportView
view.separatorView.isHidden = false
view.titleLabel.text = "Separator visible"
return view
}
private var fakeReportViewWithDetails: ReportView {
let view = fakeReportView
view.titleLabel.text = "Report with content"
view.reportDetailsViews = [fakeReportDetailsView, fakeReportDetailsViewWithLongTexts]
return view
}
// MARK: - ReportDetailsView fakse
private var fakeReportDetailsView: ReportDetailsView {
return ReportDetailsView(title: "fake_title", subtitle: "fake_subtitle")
}
private var fakeReportDetailsViewWithLongTexts: ReportDetailsView {
return ReportDetailsView(title: "very vrey very very very very very very very very very long title",
subtitle: "very very very very very very very very long subtitle")
}
}
|
gpl-3.0
|
b76ec371de17d91f2a7bd7f1e9df4212
| 33.102804 | 108 | 0.63168 | 5.096369 | false | false | false | false |
fengzhihao123/FZHSearchBar
|
FZHSearchBar/FZHSearchBar/FZHSearchBar/Base/FZHSearchBarController.swift
|
1
|
4569
|
//
// FZHSearchBarController.swift
// FZHSearchBar
//
// Created by 冯志浩 on 2016/12/9.
// Copyright © 2016年 FZH. All rights reserved.
//
import UIKit
enum SearchType {
case first
case second
}
class FZHSearchBarController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate,FZHBottomViewDelegate {
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
let tableView = UITableView()
let fzhSearchBar = FZHSearchBar()
let fzhSubSearchBar = FZHSearchBar()
let bottomView = FZHBottomView()
var fzhPopView = UIView()
var searchType: SearchType = .first {
didSet {
setupSearchStyle()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupPopView()
}
override func viewWillDisappear(_ animated: Bool) {
fzhSearchBar.isHidden = true
removeBottomView()
}
override func viewWillAppear(_ animated: Bool) {
fzhSearchBar.isHidden = false
}
func setupTableView() -> Void {
tableView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
func setupPopView() -> Void {
fzhPopView.frame = CGRect(x: 0, y: 108, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
fzhPopView.backgroundColor = UIColor.brown
}
func setupSearchStyle() {
switch searchType {
case .first:
setupFirstSearchBar()
case .second:
setupSecondSearchBar()
}
}
func setupFirstSearchBar() {
fzhSearchBar.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44)
fzhSearchBar.delegate = self
fzhSearchBar.placeholder = "搜索"
tableView.tableHeaderView = fzhSearchBar
}
func setupSecondSearchBar() {
fzhSearchBar.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44)
fzhSearchBar.delegate = self
navigationController?.navigationBar.addSubview(fzhSearchBar)
}
//MARK:FZHBottomViewDelegate
func pushNextVC(tag: String) {
}
//MARK:UISearchBarDelegate
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
fzhSearchBar.showsCancelButton = true
if searchType == .first {
searchBarMoveUpAnimation()
}else {
addBottomView()
}
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
fzhSearchBar.endEditing(true)
fzhSearchBar.showsCancelButton = false
if searchType == .first {
searchMoveDownAnimation()
}else {
removeBottomView()
}
}
func addBottomView() {
bottomView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
bottomView.backgroundColor = UIColor.blue
bottomView.fzhBottomViewDelegate = self
view.addSubview(bottomView)
}
func removeBottomView() {
bottomView.removeFromSuperview()
}
//first
func searchBarMoveUpAnimation() {
UIView.animate(withDuration: 0, animations: {
self.view.addSubview(self.fzhPopView)
}, completion: { abc in
UIView.animate(withDuration: 0.37, animations: {
self.navigationController?.navigationBar.transform = .init(translationX: 0, y: -44)
self.tableView.transform = .init(translationX: 0, y: -44)
self.fzhPopView.transform = .init(translationX: 0, y: -44)
})
})
}
//first
func searchMoveDownAnimation() {
UIView.animate(withDuration: 0.37, animations: {
self.navigationController?.navigationBar.transform = .identity
self.tableView.transform = .identity
self.fzhPopView.transform = .identity
self.fzhPopView.removeFromSuperview()
})
}
//MARK:UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "a"
return cell
}
}
|
mit
|
60772ab1baf7675366b4037da1bed164
| 29.373333 | 135 | 0.620281 | 4.682425 | false | false | false | false |
mattermost/ios
|
Mattermost/MattermostApi.swift
|
1
|
8029
|
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import Foundation
import UIKit
protocol MattermostApiProtocol {
func didRecieveResponse(_ result: JSON)
func didRecieveError(_ message: String)
}
open class MattermostApi: NSObject {
static let API_ROUTE_V4 = "/api/v4"
static let API_ROUTE_V3 = "/api/v3"
static let API_ROUTE = API_ROUTE_V4
var baseUrl = ""
var data: NSMutableData = NSMutableData()
var statusCode = 200
var delegate: MattermostApiProtocol?
override init() {
super.init()
self.initBaseUrl()
}
func initBaseUrl() {
let defaults = UserDefaults.standard
let url = defaults.string(forKey: CURRENT_URL)
if (url != nil && (url!).count > 0) {
baseUrl = url!
}
}
func getPing() {
return getPing(versionRoute: MattermostApi.API_ROUTE)
}
func getPing(versionRoute: String) {
var endpoint: String = baseUrl + versionRoute
if (versionRoute == MattermostApi.API_ROUTE_V3) {
endpoint += "/general/ping"
} else {
endpoint += "/system/ping"
}
print(endpoint)
guard let url = URL(string: endpoint) else {
print("Error cannot create URL")
DispatchQueue.main.async {
self.delegate?.didRecieveError("Invalid URL. Please check to make sure the URL is correct.")
}
return
}
let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
var code = 0
if (response as? HTTPURLResponse) != nil {
code = (response as! HTTPURLResponse).statusCode
}
guard error == nil else {
print(error!)
print("Error: statusCode=\(code) data=\(error!.localizedDescription)")
DispatchQueue.main.async {
self.delegate?.didRecieveError("\(error!.localizedDescription) [\(code)]")
}
return
}
guard let responseData = data else {
print("Error: did not receive data")
DispatchQueue.main.async {
self.delegate?.didRecieveError("Did not receive data from the server.")
}
return
}
let json = JSON(data: responseData as Data)
if (code == 200) {
print("Found API version " + versionRoute)
Utils.setProp(API_ROUTE_PROP, value: versionRoute)
DispatchQueue.main.async {
self.delegate?.didRecieveResponse(json)
}
} else if (code == 404) {
print("Couldn't find V4 API falling back to V3")
if (versionRoute != MattermostApi.API_ROUTE_V3) {
return self.getPing(versionRoute: MattermostApi.API_ROUTE_V3)
} else {
DispatchQueue.main.async {
self.delegate?.didRecieveError("Couldn't find the correct Mattermost server version.")
}
}
} else {
let datastring = NSString(data: responseData as Data, encoding: String.Encoding.utf8.rawValue)
print("Error: statusCode=\(code) data=\(datastring!)")
if let message = json["message"].string {
DispatchQueue.main.async {
self.delegate?.didRecieveError(message)
}
} else {
DispatchQueue.main.async {
self.delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured (-1)"))
}
}
}
}
task.resume()
}
func attachDeviceId() {
var endpoint: String = baseUrl + Utils.getProp(API_ROUTE_PROP)
if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) {
endpoint += "/users/attach_device"
} else {
endpoint += "/users/sessions/device"
}
print(endpoint)
guard let url = URL(string: endpoint) else {
print("Error cannot create URL")
return
}
var urlRequest = URLRequest(url: url)
if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) {
urlRequest.httpMethod = "POST"
} else {
urlRequest.httpMethod = "PUT"
}
urlRequest.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With")
urlRequest.httpBody = try! JSON(["device_id": "apple:" + Utils.getProp(DEVICE_TOKEN)]).rawData()
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
var code = 0
if (response as? HTTPURLResponse) != nil {
code = (response as! HTTPURLResponse).statusCode
}
guard error == nil else {
print(error!)
print("Error: statusCode=\(code) data=\(error!.localizedDescription)")
return
}
}
task.resume()
}
func connection(_ connection: NSURLConnection!, didFailWithError error: NSError!) {
statusCode = error.code
print("Error: statusCode=\(statusCode) data=\(error.localizedDescription)")
delegate?.didRecieveError("\(error.localizedDescription) [\(statusCode)]")
}
func connection(_ didReceiveResponse: NSURLConnection!, didReceiveResponse response: URLResponse!) {
statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1
self.data = NSMutableData()
let mmsid = Utils.getCookie(MATTERM_TOKEN)
Utils.setProp(MATTERM_TOKEN, value: mmsid)
print(mmsid)
if (mmsid == "") {
Utils.setProp(CURRENT_USER, value: "")
Utils.setProp(MATTERM_TOKEN, value: "")
}
}
func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace?) -> Bool
{
return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust
}
func connection(_ connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge?)
{
if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
{
let credentials = URLCredential(trust: challenge!.protectionSpace.serverTrust!)
challenge!.sender!.use(credentials, for: challenge!)
}
challenge?.sender!.continueWithoutCredential(for: challenge!)
}
func connection(_ connection: NSURLConnection!, didReceiveData data: Data!) {
self.data.append(data)
}
func connectionDidFinishLoading(_ connection: NSURLConnection!) {
let json = JSON(data: data as Data)
if (statusCode == 200) {
delegate?.didRecieveResponse(json)
} else {
let datastring = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
print("Error: statusCode=\(statusCode) data=\(datastring!)")
if let message = json["message"].string {
delegate?.didRecieveError(message)
} else {
delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured. (-1)"))
}
}
}
}
|
apache-2.0
|
033bc7e9f72274a3fae4223f34a4537b
| 34.061135 | 134 | 0.547266 | 5.146795 | false | false | false | false |
weareyipyip/SwiftStylable
|
Sources/SwiftStylable/Classes/Style/StylableComponents/STTextView.swift
|
1
|
4486
|
//
// STTextView.swift
// Pods
//
// Created by Marcel Bloemendaal on 08/05/2017.
//
//
import UIKit
@IBDesignable open class STTextView : UITextView, UITextViewDelegate, Stylable, BackgroundAndBorderStylable, ForegroundStylable, TextStylable, StyledTextStylable {
private var _stComponentHelper: STComponentHelper!
private var _styledText:String?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Initializers & deinit
//
// -----------------------------------------------------------------------------------------------------------------------
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUpSTComponentHelper()
}
override public init(frame: CGRect, textContainer:NSTextContainer?) {
super.init(frame: frame, textContainer: nil)
self.setUpSTComponentHelper()
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Computed properties
//
// -----------------------------------------------------------------------------------------------------------------------
@IBInspectable open var styleName:String? {
set {
self._stComponentHelper.styleName = newValue
}
get {
return self._stComponentHelper.styleName
}
}
@IBInspectable open var substyleName:String? {
set {
self._stComponentHelper.substyleName = newValue
}
get {
return self._stComponentHelper.substyleName
}
}
open override var text: String? {
didSet {
self._styledText = nil
}
}
open override var attributedText: NSAttributedString? {
didSet {
self._styledText = nil
}
}
open var foregroundColor: UIColor? {
set {
self.textColor = newValue ?? UIColor.black
}
get {
return self.textColor
}
}
open var textFont:UIFont? {
set {
if let font = newValue {
self.font = font
}
}
get {
return self.font
}
}
open var styledTextAttributes:[NSAttributedString.Key:Any]? {
didSet {
if self._styledText != nil {
self.styledText = self._styledText
}
}
}
open var fullUppercaseText = false {
didSet {
if self.fullUppercaseText {
print("WARNING: fullUppercaseText is not supported by STTextView and STTextField!")
}
}
}
@IBInspectable open var styledText:String? {
set {
self._styledText = newValue
if let text = newValue {
super.attributedText = NSAttributedString(string: text, attributes: self.styledTextAttributes ?? [NSAttributedString.Key:Any]())
}
}
get {
return self._styledText
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Public properties
//
// -----------------------------------------------------------------------------------------------------------------------
open func applyStyle(_ style:Style) {
if let font = style.textStyle.font {
self.font = font
}
if let foregroundColor = style.foregroundStyle.foregroundColor {
self.textColor = foregroundColor
}
if let fullUppercaseText = style.textStyle.fullUppercaseText {
self.fullUppercaseText = fullUppercaseText
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Private methods
//
// -----------------------------------------------------------------------------------------------------------------------
private func setUpSTComponentHelper() {
self._stComponentHelper = STComponentHelper(stylable: self, stylePropertySets: [
BackgroundAndBorderStyler(self),
ForegroundStyler(self),
TextStyler(self),
StyledTextStyler(self)
])
}
}
|
mit
|
b3e84ff149d067feca7adbbf915d19da
| 28.12987 | 163 | 0.432234 | 6.336158 | false | false | false | false |
lzpfmh/actor-platform
|
actor-apps/app-ios/ActorApp/View/Managed/ACManagedAlerts.swift
|
1
|
2014
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension UIViewController {
func alertSheet(closure: (a: AlertSetting) -> ()) {
let s = AlertSetting()
closure(a: s)
let controller = UIAlertController(title: localized(s.title), message: localized(s.message), preferredStyle: .ActionSheet)
for i in s.actions {
controller.addAction(UIAlertAction(title: localized(i.title), style: i.isDestructive ? UIAlertActionStyle.Destructive : UIAlertActionStyle.Default, handler: { (c) -> Void in
i.closure()
}))
}
controller.addAction(UIAlertAction(title: localized("AlertCancel"), style: .Cancel, handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
func confirmDestructive(message: String, action: String, yes: ()->()) {
let controller = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: action, style: .Destructive, handler: { (act) -> Void in
yes()
}))
controller.addAction(UIAlertAction(title: localized("AlertCancel"), style: .Cancel, handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
}
class AlertSetting {
var cancel: String!
var title: String!
var message: String!
private var actions = [AlertActions]()
func action(title: String, closure: ()->()) {
let a = AlertActions()
a.title = title
a.closure = closure
actions.append(a)
}
func destructive(title: String, closure: ()->()) {
let a = AlertActions()
a.title = title
a.closure = closure
a.isDestructive = true
actions.append(a)
}
}
class AlertActions {
var isDestructive = false
var title: String!
var closure: (()->())!
}
|
mit
|
899a7a69a43742a74bf583c5e6eccd30
| 29.530303 | 185 | 0.600298 | 4.629885 | false | false | false | false |
GuyKahlon/BackMenu
|
BackMenu/BackMenu/AppDelegate.swift
|
1
|
1426
|
//
// AppDelegate.swift
// BackMenu
//
// Created by Guy Kahlon on 1/25/15.
// Copyright (c) 2015 GuyKahlon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var frontWindow: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let front:UIViewController = storyboard.instantiateViewControllerWithIdentifier("frontViewController") as UIViewController
frontWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
frontWindow?.rootViewController = front;
frontWindow?.windowLevel = UIWindowLevelStatusBar
frontWindow?.startSwipeToOpenMenu()
frontWindow?.makeKeyAndVisible();
// frontWindow?.layer.masksToBounds = true
// let maskPath = UIBezierPath(roundedRect: UIScreen.mainScreen().bounds, byRoundingCorners: (.TopLeft | .TopRight), cornerRadii: CGSizeMake(2.0, 2.0))
// let maskLayer = CAShapeLayer()
// maskLayer.frame = UIScreen.mainScreen().bounds
// maskLayer.path = maskPath.CGPath;
// frontWindow?.layer.mask = maskLayer;
application.setStatusBarStyle(.LightContent, animated:false)
return true
}
}
|
mit
|
6f3b99fcd49f2324734d9f00d5b377d2
| 33.780488 | 158 | 0.681627 | 5.074733 | false | false | false | false |
natecook1000/swift
|
test/IRGen/local_types.swift
|
2
|
2241
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module %S/Inputs/local_types_helper.swift -o %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-objc-interop -emit-ir -parse-as-library %s -I %t | %FileCheck -check-prefix CHECK -check-prefix NEGATIVE %s
import local_types_helper
public func singleFunc() {
// CHECK-DAG: @"$S11local_types10singleFuncyyF06SingleD6StructL_VMf" = internal constant
struct SingleFuncStruct {
let i: Int
}
}
public let singleClosure: () -> () = {
// CHECK-DAG: @"$S11local_types13singleClosureyycvpfiyycfU_06SingleD6StructL_VMf" = internal constant
struct SingleClosureStruct {
let i: Int
}
}
public struct PatternStruct {
public var singlePattern: Int = ({
// CHECK-DAG: @"$S11local_types13PatternStructV06singleC0SivpfiSiyXEfU_06SinglecD0L_VMf" = internal constant
struct SinglePatternStruct {
let i: Int
}
return 1
})()
}
#if COMPILED_OUT
public func topLevelIfConfig() {
class LocalClassDisabled {}
}
#else
public func topLevelIfConfig() {
// CHECK-DAG: @"$S11local_types16topLevelIfConfigyyF17LocalClassEnabledL_CMm" = internal global %objc_class
class LocalClassEnabled {}
}
#endif
public struct NominalIfConfig {
#if COMPILED_OUT
public func method() {
class LocalClassDisabled {}
}
#else
public func method() {
// CHECK-DAG: @"$S11local_types15NominalIfConfigV6methodyyF17LocalClassEnabledL_CMm" = internal global %objc_class
class LocalClassEnabled {}
}
#endif
}
public func innerIfConfig() {
#if COMPILED_OUT
class LocalClassDisabled {}
func inner() {
class LocalClassDisabled {}
}
#else
// CHECK-DAG: @"$S11local_types13innerIfConfigyyF17LocalClassEnabledL_CMm" = internal global %objc_class
class LocalClassEnabled {}
func inner() {
// CHECK-DAG: @"$S11local_types13innerIfConfigyyF0C0L0_yyF17LocalClassEnabledL_CMm" = internal global %objc_class
class LocalClassEnabled {}
}
#endif
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S11local_types8callTestyyF"() {{.*}} {
public func callTest() {
test()
} // CHECK: {{^[}]$}}
// NEGATIVE-NOT: LocalClassDisabled
|
apache-2.0
|
e1b8dea65519cb0a1047e870aff28322
| 28.103896 | 188 | 0.716198 | 3.529134 | false | true | false | false |
GitTennis/SuccessFramework
|
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/Menu/MenuViewController.swift
|
2
|
7143
|
//
// MenuViewController.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 06/11/16.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class MenuViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
var model: MenuModel?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad();
self.tableView.tableFooterView = UIView()
self.initUI()
self.prepareUI()
self.loadModel()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewLoader?.hideNavigationBar(viewController: self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
// MARK: GenericViewControllerProtocol
func initUI() {
// Fix menu screen size: make it full screen for all devices
var rect: CGRect = self.view.frame
rect.size = UIScreen.main.bounds.size
self.view.frame = rect
#if DEBUG
let versionNo = Bundle.plistValue(key: "CFBundleShortVersionString") as! String
let buildNo: String = Bundle.plistValue(key: kCFBundleVersionKey as String) as! String
let versionLabel: UILabel = UILabel()
versionLabel.text = "\(versionNo) [\(buildNo)]"
versionLabel.textColor = UIColor.lightGray
versionLabel.font = versionLabel.font.withSize(12)
self.view.addSubview(versionLabel)
versionLabel.viewAddLeadingSpace(16, containerView: self.view)
versionLabel.viewAddTrailingSpace(0, containerView: self.view)
versionLabel.viewAddBottomSpace(-54, containerView: self.view)
versionLabel.viewAddHeight(40)
#endif
}
override func prepareUI() {
super.prepareUI()
}
override func renderUI() {
super.renderUI()
self.tableView.reloadData()
}
override func loadModel() {
model?.loadData(callback: { [weak self] (success, result, context, error) in
self?.renderUI()
if let model = self?.model {
if (model.isUserLoggedIn) {
self?.showLogoutButton()
} else {
self?.hideLogoutButton()
}
}
})
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let menuItemList = self.model?.menuItemList {
return menuItemList.count
} else {
return 0
}
}
// For hiding separators between empty cell below table view
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view: UIView = UIView()
return view
}
// For hiding separators between empty cell below table view
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// This will create a "invisible" footer
return 0.01
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCellIdentifier")
if let cell = cell {
cell.backgroundColor = UIColor.clear
cell.textLabel?.textColor = UIColor.darkGray
let bgView: UIView = UIView(frame: cell.frame)
bgView.backgroundColor = UIColor.lightGray
cell.selectedBackgroundView = bgView
cell.textLabel?.fontType = kFontNormalType
cell.textLabel?.text = self.titleForMenu(IndexPath: indexPath)
}
return cell!
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let menuItem = self.model?.menuItemList[indexPath.row]
if (menuItem!.isPresentedModally) {
self.presentModal(viewController: menuItem!.viewController, animated: true)
} else {
self.navigationController?.pushViewController(menuItem!.viewController, animated: true)
}
}
// MARK: IBActions
@IBAction func logoutPressed(_ sender: AnyObject) {
self.messageBarManager?.showAlertOkWithTitle(title: nil, description: localizedString(key: kMenuModelMenuItemLogoutConfirmationMessageKey), okTitle: localizedString(key: ConstLangKeys.ok), okCallback: { [weak self] in
self?.logoutAndGoBackToAppStart(error: nil)
}, cancelTitle: localizedString(key: ConstLangKeys.cancel), cancelCallback: nil)
}
// MARK:
// MARK: Internal
// MARK:
func titleForMenu(IndexPath: IndexPath) -> String {
let menuItem = self.model!.menuItemList[IndexPath.row]
return menuItem.menuTitle
}
func showLogoutButton() {
var rect: CGRect = self.view.bounds
rect.size.height = 40.0
let logoutButton: NormalButton = NormalButton(frame: rect)
logoutButton.setTitle(localizedString(key: kMenuModelMenuItemLogoutKey), for: UIControlState.normal)
logoutButton.addTarget(self, action: #selector(logoutPressed), for: UIControlEvents.touchUpInside)
self.tableView.tableFooterView = logoutButton
}
func hideLogoutButton() {
self.tableView.tableFooterView = nil
}
}
|
mit
|
940b81c2f596045cb03c0949bf88a548
| 31.756881 | 225 | 0.61588 | 5.357089 | false | false | false | false |
vectorform/Texty
|
Example/Texty_Example/UIView+Extensions.swift
|
1
|
2597
|
// Copyright (c) 2018 Vectorform, LLC
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
///Users/cbechtel/Desktop/Yarp Repo/Yarp/README.md
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import Foundation
import UIKit
extension UIView {
func constrainEdgesToSuperview() {
guard let superview: UIView = self.superview else {
return
}
let toView: Any
if #available(iOS 11.0, *) {
toView = superview.safeAreaLayoutGuide
} else {
toView = superview
}
NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toView, attribute: .left, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toView, attribute: .right, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toView, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
}
}
|
bsd-3-clause
|
677e982d75ed78a3910038f6c3f7c769
| 52 | 161 | 0.726993 | 4.55614 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode
|
精通Swift设计模式/Chapter 18/Proxy/Proxy/Auth.swift
|
1
|
676
|
class UserAuthentication {
var user:String?;
var authenticated:Bool = false;
private init() {
// do nothing - stops instances being created
}
func authenticate(user:String, pass:String) {
if (pass == "secret") {
self.user = user;
self.authenticated = true;
} else {
self.user = nil;
self.authenticated = false;
}
}
class var sharedInstance:UserAuthentication {
get {
struct singletonWrapper {
static let singleton = UserAuthentication();
}
return singletonWrapper.singleton;
}
}
}
|
mit
|
66940a666a23ab2fbfbbeffc7a98e596
| 24.037037 | 60 | 0.528107 | 5.121212 | false | false | false | false |
HongliYu/DPColorfulTags-Swift
|
DPColorfulTagsDemo/DPLanguageManager.swift
|
1
|
2103
|
//
// DPLanguageManager.swift
// DPColorfulTagsDemo
//
// Created by Hongli Yu on 12/11/2017.
// Copyright © 2017 Hongli Yu. All rights reserved.
//
import Foundation
final class DPLanguageManager {
static let shared = DPLanguageManager()
private let kCurrentLanguageKey = "AppleLanguages"
private var currentBundle = Bundle.main
private(set) var currentLanguage: DPAppLanguage
private func setCurrentLanguage(_ language: DPAppLanguage) {
currentLanguage = language
setLanguageInApp(currentLanguage.code)
NotificationCenter.default.post(name: DPNotification.languageDidChange, object: nil)
}
public func setCurrentLanguage(_ englishName: String) {
for language in languages where language.englishName == englishName {
setCurrentLanguage(language)
}
}
var languages: [DPAppLanguage] {
get {
var array = [DPAppLanguage]()
let codes = Bundle.main.localizations
for code in codes {
let language = DPAppLanguage(code: code)
array.append(language)
}
return array
}
}
init() {
if let currentLanguageCodes = UserDefaults.standard.object(forKey: kCurrentLanguageKey) as? [String],
let currentLanguageCode = currentLanguageCodes.first {
currentLanguage = DPAppLanguage(code: currentLanguageCode)
return
}
currentLanguage = DPAppLanguage(code: "en")
}
public func resetDefaultEnglish() {
setCurrentLanguage(DPAppLanguage(code: "en"))
}
public func localize(_ inputString: String) -> String {
return currentBundle.localizedString(forKey: inputString, value: inputString, table: nil)
}
private func setLanguageInApp(_ code: String) {
UserDefaults.standard.set([code], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
guard let bundlePath = Bundle.main.path(forResource: code, ofType: "lproj"),
let bundle = Bundle(path: bundlePath) else { return }
currentBundle = bundle
}
}
struct DPNotification {
static let languageDidChange = NSNotification.Name(rawValue: "languageDidChange")
}
|
mit
|
6806fbd27127a0659aa4613136eca458
| 28.605634 | 105 | 0.708849 | 4.443975 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios
|
Source/Phone/Device/DeviceClient.swift
|
1
|
2396
|
// Copyright 2016 Cisco Systems Inc
//
// 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.
import Foundation
class DeviceClient: CompletionHandlerType<Device> {
private func requestBuilder() -> ServiceRequest.Builder {
return ServiceRequest.Builder().baseUrl("https://wdm-a.wbx2.com/wdm/api/v1/devices/ios")
}
func create(_ deviceInfo: RequestParameter, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) {
let request = requestBuilder()
.method(.post)
.body(deviceInfo)
.queue(queue)
.build()
request.responseObject(completionHandler)
}
func update(_ deviceUrl: String, deviceInfo: RequestParameter, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) {
let request = requestBuilder()
.method(.put)
.baseUrl(deviceUrl)
.body(deviceInfo)
.queue(queue)
.build()
request.responseObject(completionHandler)
}
func delete(_ deviceUrl: String, queue: DispatchQueue? = nil, completionHandler: @escaping AnyHandler) {
let request = requestBuilder()
.method(.delete)
.baseUrl(deviceUrl)
.queue(queue)
.build()
request.responseJSON(completionHandler)
}
}
|
mit
|
ff501668aba66329e1db6806f581972a
| 40.310345 | 141 | 0.68197 | 4.840404 | false | false | false | false |
timbodeit/SwiftPipes
|
Pod/Classes/Pipes.swift
|
1
|
1916
|
//
// Pipe.swift
// SwiftPipes
//
// Created by Tim Bodeit on 06/10/2015
//
//
import Foundation
import Swift
precedencegroup LeftPipePrecedence {
associativity: right
higherThan: NilCoalescingPrecedence
lowerThan: RangeFormationPrecedence
}
precedencegroup RightPipePrecedence {
associativity: left
higherThan: NilCoalescingPrecedence
lowerThan: RangeFormationPrecedence
}
infix operator .. : LeftPipePrecedence
infix operator <| : LeftPipePrecedence
infix operator |> : RightPipePrecedence
infix operator |?> : RightPipePrecedence
infix operator |??> : RightPipePrecedence
infix operator |? : RightPipePrecedence
/**
Function composition.
For a parameter x:
`lhs(rhs(x))` == `(lhs .. rhs)(x)`
*/
public func .. <A,B,C>(lhs: @escaping (B)->C, rhs: @escaping (A)->B) -> (A)->C {
return { a in
lhs(rhs(a))
}
}
/**
Pipe the input on the right into the function on the left.
Chainable:
`f <| g <| h <| x` == `f(g(h(x)`
*/
public func <| <A, B>(lhs: (A) -> B, rhs: A) -> B {
return lhs(rhs)
}
/**
Pipe the input on the left into the function on the right.
Chainable:
`x |> f |> g |> h` == `h(g(f(x)))`
*/
public func |> <A, B>(lhs: A, rhs: (A) -> B) -> B {
return rhs(lhs)
}
/**
Try piping the optional input into the function on the right.
Result is nil if lhs is nil. Otherwise, same as `|>`
*/
public func |?> <A, B>(lhs: A?, rhs: (A) -> B) -> B? {
return lhs.map(rhs)
}
/**
Try piping the optional input into the function on the right.
Result is nil if lhs is nil. Otherwise, same as `rhs(lhs!)`.
*/
public func |??><A, B>(lhs: A?, rhs: (A) -> B?) -> B? {
return lhs.flatMap(rhs)
}
/**
Try piping the optional input into the side-effecting function on the right.
Result is the input value.
Equivalence: `a |? f` === `a |?> { a in f(a); return a }`
*/
public func |?<A>(lhs: A?, rhs: (A) -> ()) -> A? {
return lhs |?> { a in rhs(a); return a }
}
|
mit
|
8fad789a8072bf4796a6b6576537c623
| 20.288889 | 80 | 0.628914 | 3.105348 | false | false | false | false |
JimCampagno/Marvel-iOS
|
Marvel/CharacterDetailView.swift
|
1
|
3752
|
//
// CharacterDetailView.swift
// Marvel
//
// Created by Jim Campagno on 12/5/16.
// Copyright © 2016 Jim Campagno. All rights reserved.
//
import UIKit
class CharacterDetailView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var marvelNameLabel: UILabel!
@IBOutlet weak var marvelImageView: UIImageView!
@IBOutlet weak var marvelTextView: UITextView!
@IBOutlet weak var marvelLogoImageView: UIImageView!
// UIColor(red:0.16, green:0.16, blue:0.16, alpha:1.00)
var marvelCharacter: MarvelCharacter! {
didSet {
basicSetup()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
Bundle.main.loadNibNamed("CharacterDetailView", owner: self, options: nil)
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
contentView.constrainEdges(to: self)
backgroundColor = UIColor.clear
layer.cornerRadius = 15.0
layer.masksToBounds = true
marvelImageView.layer.cornerRadius = 10.0
marvelImageView.layer.masksToBounds = true
marvelImageView.layer.borderWidth = 2.0
marvelImageView.layer.borderColor = UIColor.black.cgColor
marvelTextView.layer.cornerRadius = 15.0
marvelTextView.layer.masksToBounds = true
marvelTextView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10)
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = 1.0
}
}
// MARK: - Setup Functions
extension CharacterDetailView {
func basicSetup() {
marvelNameLabel.alpha = 0.0
marvelImageView.alpha = 0.0
marvelTextView.alpha = 0.0
marvelLogoImageView.alpha = 0.0
marvelTextView.text = marvelCharacter.heroDescription
marvelNameLabel.text = marvelCharacter.name
marvelImageView.image = marvelCharacter.image
marvelLogoImageView.image = marvelCharacter.isAvenger ? #imageLiteral(resourceName: "AvengersBlueLogo") : #imageLiteral(resourceName: "MarvelLogo")
UIView.animate(withDuration: 0.8, delay: 0.0, options: .transitionCrossDissolve, animations: {
self.marvelNameLabel.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.8, delay: 0.1, options: .transitionCrossDissolve, animations: {
self.marvelImageView.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.8, delay: 0.2, options: .transitionCrossDissolve, animations: {
self.marvelLogoImageView.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.8, delay: 0.3, options: .transitionCrossDissolve, animations: {
self.marvelTextView.alpha = 1.0
}, completion: nil)
}
func scrollTextViewToTop() {
marvelTextView.scrollsToTop = true
let contentHeight = marvelTextView.contentSize.height
let offSet = marvelTextView.contentOffset.x
let contentOffset = contentHeight - offSet
marvelTextView.contentOffset = CGPoint(x: 0, y: -contentOffset)
}
}
// MARK: - UIView Extension
extension UIView {
func constrainEdges(to view: UIView) {
leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}
}
|
mit
|
27645a32622f3eb435666ed6b3d1f95c
| 32.792793 | 155 | 0.659024 | 4.465476 | false | false | false | false |
ktmswzw/FeelingClientBySwift
|
Pods/IBAnimatable/IBAnimatable/UIColorExtension.swift
|
1
|
854
|
//
// Created by Tom Baranes on 09/02/16.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3:
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6:
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8:
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
|
mit
|
3c5a3d8b9e81a2c6214b1b44d73e00b7
| 29.5 | 110 | 0.568581 | 2.941379 | false | false | false | false |
luyi326/SwiftIO
|
Sources/AddressScanner.swift
|
1
|
7233
|
//
// AddressScanner.swift
// Addresses
//
// Created by Jonathan Wight on 5/16/16.
// Copyright © 2016 schwa.io. All rights reserved.
//
import Foundation
// MARK: -
internal func + (lhs: NSCharacterSet, rhs: NSCharacterSet) -> NSCharacterSet {
let scratch = lhs.mutableCopy() as! NSMutableCharacterSet
scratch.formUnionWithCharacterSet(rhs)
return scratch
}
internal extension NSCharacterSet {
class func asciiLetterCharacterSet() -> NSCharacterSet {
return asciiLowercaseLetterCharacterSet() + asciiUppercaseLetterCharacterSet()
}
class func asciiLowercaseLetterCharacterSet() -> NSCharacterSet {
return NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz")
}
class func asciiUppercaseLetterCharacterSet() -> NSCharacterSet {
return NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
}
class func asciiDecimalDigitsCharacterSet() -> NSCharacterSet {
return NSCharacterSet(charactersInString: "0123456789")
}
class func asciiAlphanumericCharacterSet() -> NSCharacterSet {
return asciiLetterCharacterSet() + asciiDecimalDigitsCharacterSet()
}
class func asciiHexDigitsCharacterSet() -> NSCharacterSet {
return asciiDecimalDigitsCharacterSet() + NSCharacterSet(charactersInString: "ABCDEFabcdef")
}
}
// MARK: -
internal extension NSScanner {
var remaining: String {
return (string as NSString).substringFromIndex(scanLocation)
}
func with(@noescape closure: () -> Bool) -> Bool {
let savedCharactersToBeSkipped = charactersToBeSkipped
let savedLocation = scanLocation
let result = closure()
if result == false {
scanLocation = savedLocation
}
charactersToBeSkipped = savedCharactersToBeSkipped
return result
}
func scanString(string: String) -> Bool {
return scanString(string, intoString: nil)
}
func scanBracketedString(openBracket: String, closeBracket: String, inout intoString: String?) -> Bool {
return with() {
if scanString(openBracket) == false {
return false
}
var temp: NSString?
if scanUpToString(closeBracket, intoString: &temp) == false {
return false
}
if scanString(closeBracket) == false {
return false
}
intoString = temp! as String
return true
}
}
func scan(inout intoString: String?, @noescape closure: () -> Bool) -> Bool {
let savedCharactersToBeSkipped = charactersToBeSkipped
defer {
charactersToBeSkipped = savedCharactersToBeSkipped
}
let savedLocation = scanLocation
if closure() == false {
scanLocation = savedLocation
return false
}
let range = NSRange(location: savedLocation, length: scanLocation - savedLocation)
intoString = (string as NSString).substringWithRange(range)
return true
}
}
// MARK: -
internal extension NSScanner {
func scanIPV6Address(inout intoString: String?) -> Bool {
return with() {
charactersToBeSkipped = nil
let characterSet = NSCharacterSet.asciiHexDigitsCharacterSet() + NSCharacterSet(charactersInString: ":.")
var temp: NSString?
if scanCharactersFromSet(characterSet, intoString: &temp) == false {
return false
}
intoString = temp! as String
return true
}
}
func scanIPV4Address(inout intoString: String?) -> Bool {
return with() {
charactersToBeSkipped = nil
let characterSet = NSCharacterSet.asciiDecimalDigitsCharacterSet() + NSCharacterSet(charactersInString: ".")
var temp: NSString?
if scanCharactersFromSet(characterSet, intoString: &temp) == false {
return false
}
intoString = temp! as String
return true
}
}
/// Scan a "domain". Domain is considered a sequence of hostnames seperated by dots.
func scanDomain(inout intoString: String?) -> Bool {
let savedLocation = scanLocation
while true {
var hostname: String?
if scanHostname(&hostname) == false {
break
}
if scanString(".") == false {
break
}
}
let range = NSRange(location: savedLocation, length: scanLocation - savedLocation)
if range.length == 0 {
return false
}
intoString = (string as NSString).substringWithRange(range)
return true
}
/// Scan a "hostname".
func scanHostname(inout intoString: String?) -> Bool {
return with() {
var output = ""
var temp: NSString?
if scanCharactersFromSet(NSCharacterSet.asciiAlphanumericCharacterSet(), intoString: &temp) == false {
return false
}
output += temp! as String
if scanCharactersFromSet(NSCharacterSet.asciiAlphanumericCharacterSet() + NSCharacterSet(charactersInString: "-"), intoString: &temp) == true {
output += temp! as String
}
intoString = output
return true
}
}
/// Scan a port/service name. For purposes of this we consider this any alphanumeric sequence and rely on getaddrinfo
func scanPort(inout intoString: String?) -> Bool {
let characterSet = NSCharacterSet.asciiAlphanumericCharacterSet() + NSCharacterSet(charactersInString: "-")
var temp: NSString?
if scanCharactersFromSet(characterSet, intoString: &temp) == false {
return false
}
intoString = temp! as String
return true
}
/// Scan an address into a hostname and a port. Very crude. Rely on getaddrinfo.
func scanAddress(inout address: String?, inout port: String?) -> Bool {
var string: String?
if scanBracketedString("[", closeBracket: "]", intoString: &string) == true {
let scanner = NSScanner(string: string!)
if scanner.scanIPV6Address(&address) == false {
return false
}
if scanner.atEnd == false {
return false
}
}
else if scanIPV4Address(&address) == true {
// Nothing to do here
}
else if scanDomain(&address) == true {
// Nothing to do here
}
if scanString(":") {
scanPort(&port)
}
return true
}
}
// MARK: -
public func scanAddress(string: String, inout address: String?, inout port: String?) -> Bool {
let scanner = NSScanner(string: string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
scanner.charactersToBeSkipped = nil
var result = scanner.scanAddress(&address, port: &port)
if scanner.atEnd == false {
result = false
}
if result == false {
address = nil
port = nil
}
return result
}
|
mit
|
e3fc61bf0e103768adea6606f67ddaad
| 31.576577 | 155 | 0.608407 | 5.487102 | false | false | false | false |
coderMONSTER/iosstar
|
iOSStar/Scenes/User/Controller/AccountInfoVC.swift
|
4
|
2226
|
//
// AccountInfoVC.swift
// iOSStar
//
// Created by sum on 2017/4/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class AccountInfoVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
4bf66741a5c5a3fd004d12968cd38c7e
| 28.25 | 136 | 0.653171 | 5.018059 | false | false | false | false |
austinzheng/swift
|
test/Constraints/rdar39209245.swift
|
40
|
170
|
// RUN: %target-typecheck-verify-swift
struct S: Hashable {
let e: E?
}
enum E: Hashable {
case foo
case bar
}
let a = S(e: .foo)
let b = S(e: .bar)
_ = a == b
|
apache-2.0
|
0a54cdcf873d26e8b2871b1d3d421b59
| 10.333333 | 38 | 0.564706 | 2.361111 | false | false | false | false |
ysnrkdm/Graphene
|
Sources/Graphene/BoardRepresentation.swift
|
1
|
2680
|
//
// BoardRepresentation.swift
// MyFirstSpriteKit
//
// Created by Kodama Yoshinori on 10/17/14.
// Copyright (c) 2014 Yoshinori Kodama. All rights reserved.
//
import Foundation
open class BoardRepresentation {
open var boardMediator: BoardMediator
public init(boardMediator: BoardMediator) {
self.boardMediator = boardMediator
}
open func height() -> Int {
return self.boardMediator.height()
}
open func width() -> Int {
return self.boardMediator.width()
}
open func withinBoard(_ x: Int, y: Int) -> Bool {
return self.boardMediator.withinBoard(x, y: y)
}
open func get(_ x: Int, y: Int) -> Pieces {
return self.boardMediator.get(x, y: y)
}
open func isPieceAt(_ piece: Pieces, x: Int, y: Int) -> Bool {
return self.boardMediator.isPieceAt(piece, x: x, y: y)
}
open func isEmpty(_ x: Int, y: Int) -> Bool {
return self.boardMediator.isEmpty(x, y: y)
}
open func canPut(_ color: Pieces, x: Int, y: Int) -> Bool {
return (get(x, y: y) != .white && get(x, y: y) != .black) && getReversible(color, x: x, y: y).count > 0;
}
open func getPuttables(_ color: Pieces) -> [(Int, Int)] {
return self.boardMediator.getPuttables(color)
}
// Only diag or horizontal/vertical lines can change by putting piece at x,y
open func getReversible(_ color: Pieces, x: Int, y: Int) -> [(Int, Int)] {
return boardMediator.getReversible(color, x: x, y: y)
}
open func isAnyPuttable(_ color: Pieces) -> Bool {
return boardMediator.isAnyPuttable(color)
}
open func getNumBlack() -> Int {
return boardMediator.getNumBlack()
}
open func getNumWhite() -> Int {
return boardMediator.getNumWhite()
}
open func getNumVacant() -> Int {
return 64 - getNumBlack() - getNumWhite()
}
open func isTerminal() -> Bool {
if getNumVacant() == 0 {
return true
}
if isAnyPuttable(.black) {
return false
}
if isAnyPuttable(.white) {
return false
}
return true
}
open func numPeripherals(_ color: Pieces, x: Int, y: Int) -> Int {
return self.boardMediator.numPeripherals(color, x: x, y: y)
}
open func hashValue() -> Int {
return self.boardMediator.hashValue()
}
open func toString() -> String {
return self.boardMediator.toString()
}
open func clone() -> BoardRepresentation {
let bm = self.boardMediator.clone()
let newBR = BoardRepresentation(boardMediator: bm)
return newBR
}
}
|
mit
|
2b8766965024fd95771e48008678b2cb
| 24.52381 | 112 | 0.592164 | 3.737796 | false | false | false | false |
twtstudio/WePeiYang-iOS
|
WePeiYang/Account/BindTjuViewController.swift
|
1
|
5358
|
//
// BindTjuViewController.swift
// WePeiYang
//
// Created by Qin Yubo on 16/1/30.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import FXForms
import BlocksKit
let NOTIFICATION_BINDTJU_SUCCESSED = "NOTIFICATION_BINDTJU_SUCCESSED"
let NOTIFICATION_BINDTJU_CANCELLED = "NOTIFICATION_BINDTJU_CANCELLED"
class BindTjuViewController: UITableViewController, FXFormControllerDelegate {
var formController: FXFormController!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.title = "绑定办公网"
formController = FXFormController()
formController.tableView = self.tableView
formController.delegate = self
formController.form = BindTjuForm()
let cancelBtn = UIBarButtonItem().bk_initWithBarButtonSystemItem(.Cancel, handler: {sender in
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_BINDTJU_CANCELLED, object: nil)
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}) as! UIBarButtonItem
self.navigationItem.leftBarButtonItem = cancelBtn
let doneBtn = UIBarButtonItem().bk_initWithBarButtonSystemItem(.Done, handler: {sender in
let form = self.formController.form as! BindTjuForm
let username = form.username
let password = form.password
if username != nil && password != nil && username != "" && password != "" {
MsgDisplay.showLoading()
AccountManager.bindTjuAccountWithTjuUserName(username, password: password, success: {
MsgDisplay.showSuccessMsg("办公网账号绑定成功!")
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_BINDTJU_SUCCESSED, object: nil)
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}, failure: {errorMsg in
MsgDisplay.showErrorMsg(errorMsg)
})
} else {
MsgDisplay.showErrorMsg("账号或密码不能为空")
}
}) as! UIBarButtonItem
self.navigationItem.rightBarButtonItem = doneBtn
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
// // MARK: - Table view data source
//
// override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 0
// }
//
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
// return 0
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
198eefd54cf205732714a8f33d5f01d6
| 37.737226 | 157 | 0.67345 | 5.393293 | false | false | false | false |
contentful/ManagedObjectModelSerializer
|
Code/EntitySerializer.swift
|
1
|
4607
|
//
// EntitySerializer.swift
// ManagedObjectModelSerializer
//
// Created by Boris Bügling on 31/10/14.
// Copyright (c) 2014 Boris Bügling. All rights reserved.
//
import CoreData
func attributeTypeToString(type : NSAttributeType) -> String {
switch(type) {
case .BinaryDataAttributeType:
return "Binary"
case .BooleanAttributeType:
return "Boolean"
case .DateAttributeType:
return "Date"
case .DecimalAttributeType:
return "Decimal"
case .DoubleAttributeType:
return "Double"
case .FloatAttributeType:
return "Float"
case .Integer16AttributeType:
return "Integer 16"
case .Integer32AttributeType:
return "Integer 32"
case .Integer64AttributeType:
return "Integer 64"
case .StringAttributeType:
return "String"
case .TransformableAttributeType:
return "Transformable"
default:
return ""
}
}
class EntitySerializer: NSObject {
let entity : NSEntityDescription
init(entity : NSEntityDescription) {
self.entity = entity
}
func attributes() -> [XMLNode] {
let attributes = ((entity.attributesByName as NSDictionary).allValues as! [NSAttributeDescription]).sort({ (attr1 : NSAttributeDescription, attr2 : NSAttributeDescription) -> Bool in
return attr1.name < attr2.name
})
return attributes.map({
let attribute = $0 as NSAttributeDescription
var result = </"attribute" | ["name": attribute.name] | ["optional": "YES"] | ["attributeType": attributeTypeToString(attribute.attributeType)]
if let defaultValue = attribute.defaultValue as? NSObject {
var value = defaultValue.description
switch(attribute.attributeType) {
case .DoubleAttributeType, .FloatAttributeType, .DecimalAttributeType:
if !value.characters.contains(".") {
value += ".0"
}
break
default:
break
}
result = result | ["defaultValueString": value]
}
result = result | ["syncable": "YES"]
return result
})
}
// TODO: Support delete rules
func relationships() -> [XMLNode] {
let relationships = ((entity.relationshipsByName as NSDictionary).allValues as! [NSRelationshipDescription]).sort { (rel1 : NSRelationshipDescription, rel2 : NSRelationshipDescription) -> Bool in
return rel1.name < rel2.name
}
return relationships.map({
let relationship = $0 as NSRelationshipDescription
var result = </"relationship" | ["name": relationship.name] | ["optional": "YES"]
if relationship.maxCount > 0 {
result = result | ["maxCount": String(relationship.maxCount)]
}
if relationship.minCount > 0 {
result = result | ["maxCount": String(relationship.minCount)]
}
if relationship.toMany {
result = result | ["toMany": "YES"]
}
result = result | ["deletionRule": "Nullify"]
if relationship.ordered {
result = result | ["ordered": "YES"]
}
if relationship.destinationEntity != nil {
let destination = relationship.destinationEntity!.name! as String
result = result | ["destinationEntity": destination]
}
if relationship.inverseRelationship != nil {
let inverseRelationship = relationship.inverseRelationship!
let inverse = inverseRelationship.name as String
result = result | ["inverseName": inverse]
/*if inverseRelationship.destinationEntity != nil {
let destination = inverseRelationship.destinationEntity!.name! as String
result = result | ["inverseEntity": destination]
}*/
if relationship.destinationEntity != nil {
let destination = relationship.destinationEntity!.name! as String
result = result | ["inverseEntity": destination]
}
}
result = result | ["syncable": "YES"]
return result
})
}
func generate() -> XMLElement {
return </"entity" | ["name": entity.name!] | ["representedClassName": entity.name!] | ["syncable": "YES"] | attributes() | relationships()
}
}
|
mit
|
656bf4fcae765c926882a0f9f816482e
| 33.62406 | 203 | 0.57785 | 5.430425 | false | false | false | false |
catloafsoft/AudioKit
|
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Modal Resonance Filter.xcplaygroundpage/Contents.swift
|
1
|
663
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Modal Resonance Filter
//:
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var filter = AKModalResonanceFilter(player)
filter.frequency = 300 // Hz
filter.qualityFactor = 50
let loweredVolume = AKBooster(filter, gain: 0.2)
AudioKit.output = loweredVolume
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
mit
|
6032375d442d7938ad17efe873f71cc3
| 22.678571 | 72 | 0.722474 | 3.642857 | false | false | false | false |
marcdown/SayWhat
|
SayWhat/Views/SpeechRecognitionViewController.swift
|
1
|
3836
|
//
// SpeechRecognitionViewController.swift
// SayWhat
//
// Created by Marc Brown on 8/29/16.
// Copyright © 2016 creative mess. All rights reserved.
//
import Speech
import UIKit
protocol SpeechRecognitionDelegate: class {
func speechRecognitionComplete(query: String?)
func speechRecognitionCancelled()
}
class SpeechRecognitionViewController: UIViewController, SFSpeechRecognizerDelegate {
@IBOutlet var textView: UITextView!
private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
private let audioEngine = AVAudioEngine()
private var query: String?
weak var delegate: SpeechRecognitionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
speechRecognizer?.delegate = self
startListening()
}
func startListening() {
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let recognitionRequest = recognitionRequest else {
return
}
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
var isFinal = false
if result != nil {
self.query = result?.bestTranscription.formattedString
self.textView.text = self.query
isFinal = (result?.isFinal)!
}
if error != nil || isFinal {
self.stopListening()
}
})
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
} catch {
print("Audio session isn't configured correctly")
}
let recordingFormat = audioEngine.inputNode?.outputFormat(forBus: 0)
audioEngine.inputNode?.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, time) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
textView.text = "Listening..."
} catch {
print("Audio engine failed to start")
}
}
func stopListening() {
audioEngine.stop()
audioEngine.inputNode?.removeTap(onBus: 0)
recognitionRequest = nil
recognitionTask = nil
}
@IBAction func doneButtonTapped() {
stopListening()
delegate?.speechRecognitionComplete(query: query)
}
@IBAction func cancelButtonTapped() {
stopListening()
delegate?.speechRecognitionCancelled()
}
// MARK: SFSpeechRecognizerDelegate
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
if !available {
let alertController = UIAlertController(title: nil,
message: "Speech Recognition is currently unavailable.",
preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default) { (alertAction) in
self.cancelButtonTapped()
}
alertController.addAction(alertAction)
present(alertController, animated: true)
}
}
}
|
mit
|
c74fcf47e6bb9f5680a334f517e8dca5
| 32.347826 | 121 | 0.618514 | 6.106688 | false | false | false | false |
KTMarc/Marvel-Heroes
|
Marvel Heroes/Services/apiClient.swift
|
1
|
4600
|
//
// apiClient.swift
// Marvel Heroes
//
// Created by Marc Humet on 11/4/16.
// Copyright © 2016 SPM. All rights reserved.
//
import Foundation
import UIKit
/**
Using the FAÇADE DESIGN PATTERN, which provides a single interface to a complex subsystem. Instead of exposing the user to a set of classes and their APIs, only one simple unified API is exposed
*/
// MARK: - Types
/**
Select different ways of doing tasks.
It enforces thinking in a modular way to exchange the logic when necessary
So, we can have at some point different implementations of:
-Parser: with legacy JSON Serializer, SwiftyJSON, Gloss, etc..
-Storage Manager: Legacy NSCache, Haneke, Core Data, Realm, etc..
*/
enum ParseType {
case swifty
case functional
}
enum StorageArchitecture {
case haneke
case other
}
enum Result<Value> {
case success(Value)
case fail(Error)
}
class apiClient: NSObject {
// MARK: - Properties
private let _persistencyManager: PersistencyManager
private let _isOnline: Bool
private let _parseType: ParseType
private let _storageArchitecture : StorageArchitecture
//Singleton definition:
//supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let
static let manager = apiClient(parseType: .functional, storageArchitecture: .other)
init(parseType: ParseType, storageArchitecture: StorageArchitecture) {
_parseType = parseType
_storageArchitecture = storageArchitecture
_persistencyManager = PersistencyManager(parseType: _parseType, storageArchitecture: _storageArchitecture)
_isOnline = false
super.init()
}
//MARK: - IMAGES
func getImage(link: String, completion: ImageCacheCompletion){
return _persistencyManager.getImage(link: link, completion: { (image) in
print("imagen bajada")
})
}
func getCache() -> NSCache<NSString,UIImage>{
return _persistencyManager.getCache()
}
//MARK: - HEROES
/**
Example API Call:
http://gateway.marvel.com/v1/public/characters/1010870/comics?offset=0&ts=1&apikey=c88613ef9c4edc6dee9b496c6f0d0a93&hash=27861456bf9a405a5e8320359485b698
- parameter heroId: The Id of the Hero to get the comics from
*/
func fetchHeroes() {
_persistencyManager.fetchHeroes()
}
/**
Given a given ID we seach a Hero
- returns: A Hero or Nil
*/
func getHero(id: Int) -> Hero?{
return _persistencyManager.getHero(id: id)
}
/**
Returns the list of previously fetched elements
- returns: An array of heroes
*/
func getHeroes() -> [Hero]{
return _persistencyManager.getHeroes()
}
/**
Returns a specific Hero
- returns: A Hero or Nil if we didn´t find it
*/
// func getHero(id: Int) -> Hero{
// return persistencyManager.getHero(id: id)!
// }
//
/**
Fetches more elements with a given offset
- parameter offset: An int representing the next batch start: 0, 20, 40
- returns: An array of comics
*/
func moreHeroes(_ offset: Int, prefetchingImages: Bool){
_persistencyManager.getMoreHeroes(offset, prefetchingImages: prefetchingImages)
}
//MARK: - SUGGESTIONS
/**
Finds characters matching name
- parameter keystrokes: The text that user introduced in the searchBar
*/
func searchHeroes(_ keystrokes: String){
return _persistencyManager.searchHeroes(keystrokes)
}
/**
Returns the list of previously fetched Heroes
- returns: An array of characters
*/
func getHeroSuggestions() -> [Hero]{
return _persistencyManager.getHeroSuggestions()
}
/**
Cleans the Suggestions View Controller and leaves it ready for the next keystroke or deletion
*/
func resetHeroSuggestions(){
return _persistencyManager.resetHeroSuggestions()
}
//MARK: - COMICS
/**
Starts the loading process for a particular Character Comic list
- parameter heroId: The Id of the Hero to get the comics from
*/
func fetchComics(_ heroId: Int){
_persistencyManager.fetchComics(heroId)
}
/**
Returns the list of previously fetched elements
- returns: An array of comics
*/
func getComics() -> [Comic]{
return _persistencyManager.getComics()
}
}
|
mit
|
ebe2e5738f333e4050ee20e8296c5a0c
| 25.726744 | 196 | 0.650424 | 4.411708 | false | false | false | false |
Coderian/SwiftedKML
|
SwiftedKML/Elements/Delete.swift
|
1
|
1301
|
//
// Delete.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML Delete
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="Delete" type="kml:DeleteType"/>
public class Delete :SPXMLElement, HasXMLElementValue {
public static var elementName: String = "Delete"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Update: v.value.createOrDeleteOrChange.append(self)
default: break
}
}
}
}
public var value : DeleteType = DeleteType()
}
/// KML DeleteType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="DeleteType">
/// <sequence>
/// <element ref="kml:AbstractFeatureGroup" minOccurs="0" maxOccurs="unbounded"/>
/// </sequence>
/// </complexType>
public class DeleteType {
public var abstractFeatureGroup: [AbstractFeatureGroup] = []
}
|
mit
|
f2137ce17d8ed3ffbfe3f354130b33bf
| 27.930233 | 85 | 0.607717 | 3.585014 | false | false | false | false |
CD1212/Doughnut
|
Pods/GRDB.swift/GRDB/Record/FetchedRecordsController.swift
|
1
|
44648
|
import Foundation
#if os(iOS)
import UIKit
#endif
/// You use FetchedRecordsController to track changes in the results of an
/// SQLite request.
///
/// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for
/// more information.
public final class FetchedRecordsController<Record: RowConvertible> {
// MARK: - Initialization
/// Creates a fetched records controller initialized from a SQL query and
/// its eventual arguments.
///
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
/// arguments: [Color.red],
/// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
///
/// - parameters:
/// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool)
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - queue: A serial dispatch queue (defaults to the main queue)
///
/// The fetched records controller tracking callbacks will be
/// notified of changes in this queue. The controller itself must be
/// used from this queue.
///
/// - isSameRecord: Optional function that compares two records.
///
/// This function should return true if the two records have the
/// same identity. For example, they have the same id.
public convenience init(
_ databaseWriter: DatabaseWriter,
sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
queue: DispatchQueue = .main,
isSameRecord: ((Record, Record) -> Bool)? = nil) throws
{
try self.init(
databaseWriter,
request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self),
queue: queue,
isSameRecord: isSameRecord)
}
/// Creates a fetched records controller initialized from a fetch request
/// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface).
///
/// let request = Wine.order(Column("name"))
/// let controller = FetchedRecordsController(
/// dbQueue,
/// request: request,
/// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
///
/// - parameters:
/// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool)
/// - request: A fetch request.
/// - queue: A serial dispatch queue (defaults to the main queue)
///
/// The fetched records controller tracking callbacks will be
/// notified of changes in this queue. The controller itself must be
/// used from this queue.
///
/// - isSameRecord: Optional function that compares two records.
///
/// This function should return true if the two records have the
/// same identity. For example, they have the same id.
public convenience init<Request>(
_ databaseWriter: DatabaseWriter,
request: Request,
queue: DispatchQueue = .main,
isSameRecord: ((Record, Record) -> Bool)? = nil) throws
where Request: TypedRequest, Request.RowDecoder == Record
{
let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
if let isSameRecord = isSameRecord {
itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } }
} else {
itemsAreIdenticalFactory = { _ in { _,_ in false } }
}
try self.init(
databaseWriter,
request: request,
queue: queue,
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
private init<Request>(
_ databaseWriter: DatabaseWriter,
request: Request,
queue: DispatchQueue,
itemsAreIdenticalFactory: @escaping ItemComparatorFactory<Record>) throws
where Request: TypedRequest, Request.RowDecoder == Record
{
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
self.databaseWriter = databaseWriter
self.queue = queue
}
/// Executes the controller's fetch request.
///
/// After executing this method, you can access the the fetched objects with
/// the `fetchedRecords` property.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
public func performFetch() throws {
// If some changes are currently processed, make sure they are
// discarded. But preserve eventual changes processing for future
// changes.
let fetchAndNotifyChanges = observer?.fetchAndNotifyChanges
observer?.invalidate()
observer = nil
// Fetch items on the writing dispatch queue, so that the transaction
// observer is added on the same serialized queue as transaction
// callbacks.
try databaseWriter.write { db in
let initialItems = try Item<Record>.fetchAll(db, request)
fetchedItems = initialItems
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
}
}
}
// MARK: - Configuration
/// The database writer used to fetch records.
///
/// The controller registers as a transaction observer in order to respond
/// to changes.
public let databaseWriter: DatabaseWriter
/// The dispatch queue on which the controller must be used.
///
/// Unless specified otherwise at initialization time, it is the main queue.
public let queue: DispatchQueue
/// Updates the fetch request, and eventually notifies the tracking
/// callbacks if performFetch() has been called.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
// No observer: don't look for changes
guard let observer = observer else { return }
// If some changes are currently processed, make sure they are
// discarded. But preserve eventual changes processing.
let fetchAndNotifyChanges = observer.fetchAndNotifyChanges
observer.invalidate()
self.observer = nil
// Replace observer so that it tracks a new set of columns,
// and notify eventual changes
let initialItems = fetchedItems
databaseWriter.write { db in
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
observer.fetchAndNotifyChanges(observer)
}
}
/// Updates the fetch request, and eventually notifies the tracking
/// callbacks if performFetch() has been called.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self))
}
/// Registers changes notification callbacks.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
///
/// - parameters:
/// - willChange: Invoked before records are updated.
/// - onChange: Invoked for each record that has been added,
/// removed, moved, or updated.
/// - didChange: Invoked after records have been updated.
public func trackChanges(
willChange: ((FetchedRecordsController<Record>) -> ())? = nil,
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
{
// I hate you SE-0110.
let wrappedWillChange: ((FetchedRecordsController<Record>, Void) -> ())?
if let willChange = willChange {
wrappedWillChange = { (controller, _) in willChange(controller) }
} else {
wrappedWillChange = nil
}
let wrappedDidChange: ((FetchedRecordsController<Record>, Void) -> ())?
if let didChange = didChange {
wrappedDidChange = { (controller, _) in didChange(controller) }
} else {
wrappedDidChange = nil
}
trackChanges(
fetchAlongside: { _ in },
willChange: wrappedWillChange,
onChange: onChange,
didChange: wrappedDidChange)
// Without bloody SE-0110:
// trackChanges(
// fetchAlongside: { _ in },
// willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
// onChange: onChange,
// didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
}
/// Registers changes notification callbacks.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
///
/// - parameters:
/// - fetchAlongside: The value returned from this closure is given to
/// willChange and didChange callbacks, as their
/// `fetchedAlongside` argument. The closure is guaranteed to see the
/// database in the state it has just after eventual changes to the
/// fetched records have been performed. Use it in order to fetch
/// values that must be consistent with the fetched records.
/// - willChange: Invoked before records are updated.
/// - onChange: Invoked for each record that has been added,
/// removed, moved, or updated.
/// - didChange: Invoked after records have been updated.
public func trackChanges<T>(
fetchAlongside: @escaping (Database) throws -> T,
willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil,
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil)
{
// If some changes are currently processed, make sure they are
// discarded because they would trigger previously set callbacks.
observer?.invalidate()
observer = nil
guard (willChange != nil) || (onChange != nil) || (didChange != nil) else {
// Stop tracking
return
}
var willProcessTransaction: () -> () = { }
var didProcessTransaction: () -> () = { }
#if os(iOS)
if let application = application {
var backgroundTaskID: UIBackgroundTaskIdentifier! = nil
willProcessTransaction = {
backgroundTaskID = application.beginBackgroundTask {
application.endBackgroundTask(backgroundTaskID)
}
}
didProcessTransaction = {
application.endBackgroundTask(backgroundTaskID)
}
}
#endif
let initialItems = fetchedItems
databaseWriter.write { db in
let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction(
controller: self,
fetchAlongside: fetchAlongside,
itemsAreIdentical: itemsAreIdentical,
willProcessTransaction: willProcessTransaction,
willChange: willChange,
onChange: onChange,
didChange: didChange,
didProcessTransaction: didProcessTransaction)
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
if let initialItems = initialItems {
observer.items = initialItems
db.add(transactionObserver: observer)
observer.fetchAndNotifyChanges(observer)
}
}
}
/// Registers an error callback.
///
/// Whenever the controller could not look for changes after a transaction
/// has potentially modified the tracked request, this error handler is
/// called.
///
/// The request observation is not stopped, though: future transactions may
/// successfully be handled, and the notified changes will then be based on
/// the last successful fetch.
///
/// This method must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController<Record>, Error) -> ()) {
self.errorHandler = errorHandler
}
#if os(iOS)
/// Call this method when changes performed while the application is
/// in the background should be processed before the application enters the
/// suspended state.
///
/// Whenever the tracked request is changed, the fetched records controller
/// sets up a background task using
/// `UIApplication.beginBackgroundTask(expirationHandler:)` which is ended
/// after the `didChange` callback has completed.
public func allowBackgroundChangesTracking(in application: UIApplication) {
self.application = application
}
#endif
// MARK: - Accessing Records
/// The fetched records.
///
/// The value of this property is nil until performFetch() has been called.
///
/// The records reflect the state of the database after the initial
/// call to performFetch, and after each database transaction that affects
/// the results of the fetch request.
///
/// This property must be used from the controller's dispatch queue (the
/// main queue unless stated otherwise in the controller's initializer).
public var fetchedRecords: [Record] {
guard let fetchedItems = fetchedItems else {
fatalError("the performFetch() method must be called before accessing fetched records")
}
return fetchedItems.map { $0.record }
}
// MARK: - Not public
#if os(iOS)
/// Support for allowBackgroundChangeTracking(in:)
var application: UIApplication?
#endif
/// The items
fileprivate var fetchedItems: [Item<Record>]?
/// The record comparator
private var itemsAreIdentical: ItemComparator<Record>
/// The record comparator factory (support for request change)
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
/// The request
fileprivate var request: Request
/// The observed selection info
private var selectionInfo : SelectStatement.SelectionInfo
/// The eventual current database observer
private var observer: FetchedRecordsObserver<Record>?
/// The eventual error handler
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
private static func fetchSelectionInfoAndComparator(
_ db: Database,
request: Request,
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
{
let (statement, _) = try request.prepare(db)
let selectionInfo = statement.selectionInfo
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
return (selectionInfo, itemsAreIdentical)
}
}
extension FetchedRecordsController where Record: TableMapping {
// MARK: - Initialization
/// Creates a fetched records controller initialized from a SQL query and
/// its eventual arguments.
///
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
/// arguments: [Color.red])
///
/// The records are compared by primary key (single-column primary key,
/// compound primary key, or implicit rowid). For a database table which
/// has an `id` primary key, this initializer is equivalent to:
///
/// // Assuming the wines table has an `id` primary key:
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
/// arguments: [Color.red],
/// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
///
/// - parameters:
/// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool)
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - queue: A serial dispatch queue (defaults to the main queue)
///
/// The fetched records controller tracking callbacks will be
/// notified of changes in this queue. The controller itself must be
/// used from this queue.
public convenience init(
_ databaseWriter: DatabaseWriter,
sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
queue: DispatchQueue = .main) throws
{
try self.init(
databaseWriter,
request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self),
queue: queue)
}
/// Creates a fetched records controller initialized from a fetch request
/// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface).
///
/// let request = Wine.order(Column("name"))
/// let controller = FetchedRecordsController(
/// dbQueue,
/// request: request)
///
/// The records are compared by primary key (single-column primary key,
/// compound primary key, or implicit rowid). For a database table which
/// has an `id` primary key, this initializer is equivalent to:
///
/// // Assuming the wines table has an `id` primary key:
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// request: request,
/// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
///
/// - parameters:
/// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool)
/// - request: A fetch request.
/// - queue: A serial dispatch queue (defaults to the main queue)
///
/// The fetched records controller tracking callbacks will be
/// notified of changes in this queue. The controller itself must be
/// used from this queue.
public convenience init<Request>(
_ databaseWriter: DatabaseWriter,
request: Request,
queue: DispatchQueue = .main) throws
where Request: TypedRequest, Request.RowDecoder == Record
{
// Builds a function that returns true if and only if two items
// have the same primary key and primary keys contain at least one
// non-null value.
let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in
// Extract primary key columns from database table
let columns = try db.primaryKey(Record.databaseTableName).columns
// Compare primary keys
assert(!columns.isEmpty)
return { (lItem, rItem) in
var notNullValue = false
for column in columns {
let lValue: DatabaseValue = lItem.row[column]
let rValue: DatabaseValue = rItem.row[column]
if lValue != rValue {
// different primary keys
return false
}
if !lValue.isNull || !rValue.isNull {
notNullValue = true
}
}
// identical primary keys iff at least one value is not null
return notNullValue
}
}
try self.init(
databaseWriter,
request: request,
queue: queue,
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
}
// MARK: - FetchedRecordsObserver
/// FetchedRecordsController adopts TransactionObserverType so that it can
/// monitor changes to its fetched records.
private final class FetchedRecordsObserver<Record: RowConvertible> : TransactionObserver {
var isValid: Bool
var needsComputeChanges: Bool
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
let queue: DispatchQueue // protects items
let selectionInfo: SelectStatement.SelectionInfo
var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> ()
init(selectionInfo: SelectStatement.SelectionInfo, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
self.isValid = true
self.items = nil
self.needsComputeChanges = false
self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver")
self.selectionInfo = selectionInfo
self.fetchAndNotifyChanges = fetchAndNotifyChanges
}
func invalidate() {
isValid = false
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return eventKind.impacts(selectionInfo)
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Part of the TransactionObserverType protocol
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// Part of the TransactionObserverType protocol
func databaseDidChange(with event: DatabaseEvent) {
needsComputeChanges = true
}
/// Part of the TransactionObserverType protocol
func databaseWillCommit() throws { }
/// Part of the TransactionObserverType protocol
func databaseDidRollback(_ db: Database) {
needsComputeChanges = false
}
/// Part of the TransactionObserverType protocol
func databaseDidCommit(_ db: Database) {
// The databaseDidCommit callback is called in the database writer
// dispatch queue, which is serialized: it is guaranteed to process the
// last database transaction.
// Were observed tables modified?
guard needsComputeChanges else { return }
needsComputeChanges = false
fetchAndNotifyChanges(self)
}
}
// MARK: - Changes
private func makeFetchFunction<Record, T>(
controller: FetchedRecordsController<Record>,
fetchAlongside: @escaping (Database) throws -> T,
willProcessTransaction: @escaping () -> (),
completion: @escaping (Result<(fetchedItems: [Item<Record>], fetchedAlongside: T, observer: FetchedRecordsObserver<Record>)>) -> ()
) -> (FetchedRecordsObserver<Record>) -> ()
{
// Make sure we keep a weak reference to the fetched records controller,
// so that the user can use unowned references in callbacks:
//
// controller.trackChanges { [unowned self] ... }
//
// Should controller become strong at any point before callbacks are
// called, such unowned reference would have an opportunity to crash.
return { [weak controller] observer in
// Return if observer has been invalidated
guard observer.isValid else { return }
// Return if fetched records controller has been deallocated
guard let request = controller?.request, let databaseWriter = controller?.databaseWriter else { return }
willProcessTransaction()
// Fetch items.
//
// This method is called from the database writer's serialized
// queue, so that we can fetch items before other writes have the
// opportunity to modify the database.
//
// However, we don't have to block the writer queue for all the
// duration of the fetch. We just need to block the writer queue
// until we can perform a fetch in isolation. This is the role of
// the readFromCurrentState method (see below).
//
// However, our fetch will last for an unknown duration. And since
// we release the writer queue early, the next database modification
// will triggers this callback while our fetch is, maybe, still
// running. This next callback will also perform its own fetch, that
// will maybe end before our own fetch.
//
// We have to make sure that our fetch is processed *before* the
// next fetch: let's immediately dispatch the processing task in our
// serialized FIFO queue, but have it wait for our fetch to
// complete, with a semaphore:
let semaphore = DispatchSemaphore(value: 0)
var result: Result<(fetchedItems: [Item<Record>], fetchedAlongside: T)>? = nil
do {
try databaseWriter.readFromCurrentState { db in
result = Result { try (
fetchedItems: Item<Record>.fetchAll(db, request),
fetchedAlongside: fetchAlongside(db)) }
semaphore.signal()
}
} catch {
result = .failure(error)
semaphore.signal()
}
// Process the fetched items
observer.queue.async { [weak observer] in
// Wait for the fetch to complete:
_ = semaphore.wait(timeout: .distantFuture)
// Return if observer has been invalidated
guard let strongObserver = observer else { return }
guard strongObserver.isValid else { return }
completion(result!.map { (fetchedItems, fetchedAlongside) in
(fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: strongObserver)
})
}
}
}
private func makeFetchAndNotifyChangesFunction<Record, T>(
controller: FetchedRecordsController<Record>,
fetchAlongside: @escaping (Database) throws -> T,
itemsAreIdentical: @escaping ItemComparator<Record>,
willProcessTransaction: @escaping () -> (),
willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())?,
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())?,
didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())?,
didProcessTransaction: @escaping () -> ()
) -> (FetchedRecordsObserver<Record>) -> ()
{
// Make sure we keep a weak reference to the fetched records controller,
// so that the user can use unowned references in callbacks:
//
// controller.trackChanges { [unowned self] ... }
//
// Should controller become strong at any point before callbacks are
// called, such unowned reference would have an opportunity to crash.
return makeFetchFunction(controller: controller, fetchAlongside: fetchAlongside, willProcessTransaction: willProcessTransaction) { [weak controller] result in
// Return if fetched records controller has been deallocated
guard let callbackQueue = controller?.queue else { return }
switch result {
case .failure(let error):
callbackQueue.async {
// Now we can retain controller
guard let strongController = controller else { return }
strongController.errorHandler?(strongController, error)
didProcessTransaction()
}
case .success((fetchedItems: let fetchedItems, fetchedAlongside: let fetchedAlongside, observer: let observer)):
// Return if there is no change
let changes: [ItemChange<Record>]
if onChange != nil {
// Compute table view changes
changes = computeChanges(from: observer.items, to: fetchedItems, itemsAreIdentical: itemsAreIdentical)
if changes.isEmpty { return }
} else {
// Don't compute changes: just look for a row difference:
if identicalItemArrays(fetchedItems, observer.items) { return }
changes = []
}
// Ready for next check
observer.items = fetchedItems
callbackQueue.async { [weak observer] in
// Return if observer has been invalidated
guard let strongObserver = observer else { return }
guard strongObserver.isValid else { return }
// Now we can retain controller
guard let strongController = controller else { return }
// Notify changes
willChange?(strongController, fetchedAlongside)
strongController.fetchedItems = fetchedItems
if let onChange = onChange {
for change in changes {
onChange(strongController, change.record, change.fetchedRecordChange)
}
}
didChange?(strongController, fetchedAlongside)
didProcessTransaction()
}
}
}
}
private func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
let m = s.count
let n = t.count
// Fill first row and column of insertions and deletions.
var d: [[[ItemChange<Record>]]] = Array(repeating: Array(repeating: [], count: n + 1), count: m + 1)
var changes = [ItemChange<Record>]()
for (row, item) in s.enumerated() {
let deletion = ItemChange.deletion(item: item, indexPath: IndexPath(indexes: [0, row]))
changes.append(deletion)
d[row + 1][0] = changes
}
changes.removeAll()
for (col, item) in t.enumerated() {
let insertion = ItemChange.insertion(item: item, indexPath: IndexPath(indexes: [0, col]))
changes.append(insertion)
d[0][col + 1] = changes
}
if m == 0 || n == 0 {
// Pure deletions or insertions
return d[m][n]
}
// Fill body of matrix.
for tx in 0..<n {
for sx in 0..<m {
if s[sx] == t[tx] {
d[sx+1][tx+1] = d[sx][tx] // no operation
} else {
var del = d[sx][tx+1] // a deletion
var ins = d[sx+1][tx] // an insertion
var sub = d[sx][tx] // a substitution
// Record operation.
let minimumCount = min(del.count, ins.count, sub.count)
if del.count == minimumCount {
let deletion = ItemChange.deletion(item: s[sx], indexPath: IndexPath(indexes: [0, sx]))
del.append(deletion)
d[sx+1][tx+1] = del
} else if ins.count == minimumCount {
let insertion = ItemChange.insertion(item: t[tx], indexPath: IndexPath(indexes: [0, tx]))
ins.append(insertion)
d[sx+1][tx+1] = ins
} else {
let deletion = ItemChange.deletion(item: s[sx], indexPath: IndexPath(indexes: [0, sx]))
let insertion = ItemChange.insertion(item: t[tx], indexPath: IndexPath(indexes: [0, tx]))
sub.append(deletion)
sub.append(insertion)
d[sx+1][tx+1] = sub
}
}
}
}
/// Returns an array where deletion/insertion pairs of the same element are replaced by `.move` change.
func standardize(changes: [ItemChange<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
/// Returns a potential .move or .update if *change* has a matching change in *changes*:
/// If *change* is a deletion or an insertion, and there is a matching inverse
/// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned.
/// As a convenience, the index of the matched change is returned as well.
func merge(change: ItemChange<Record>, in changes: [ItemChange<Record>], itemsAreIdentical: ItemComparator<Record>) -> (mergedChange: ItemChange<Record>, mergedIndex: Int)? {
/// Returns the changes between two rows: a dictionary [key: oldValue]
/// Precondition: both rows have the same columns
func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] {
var changedValues: [String: DatabaseValue] = [:]
for (column, newValue) in newRow {
let oldValue: DatabaseValue? = oldRow[column]
if newValue != oldValue {
changedValues[column] = oldValue
}
}
return changedValues
}
switch change {
case .insertion(let newItem, let newIndexPath):
// Look for a matching deletion
for (index, otherChange) in changes.enumerated() {
guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue }
guard itemsAreIdentical(oldItem, newItem) else { continue }
let rowChanges = changedValues(from: oldItem.row, to: newItem.row)
if oldIndexPath == newIndexPath {
return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
} else {
return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
}
}
return nil
case .deletion(let oldItem, let oldIndexPath):
// Look for a matching insertion
for (index, otherChange) in changes.enumerated() {
guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue }
guard itemsAreIdentical(oldItem, newItem) else { continue }
let rowChanges = changedValues(from: oldItem.row, to: newItem.row)
if oldIndexPath == newIndexPath {
return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
} else {
return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
}
}
return nil
default:
return nil
}
}
// Updates must be pushed at the end
var mergedChanges: [ItemChange<Record>] = []
var updateChanges: [ItemChange<Record>] = []
for change in changes {
if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) {
mergedChanges.remove(at: mergedIndex)
switch mergedChange {
case .update:
updateChanges.append(mergedChange)
default:
mergedChanges.append(mergedChange)
}
} else {
mergedChanges.append(change)
}
}
return mergedChanges + updateChanges
}
return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical)
}
private func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
for (lhs, rhs) in zip(lhs, rhs) {
if lhs.row != rhs.row {
return false
}
}
return true
}
// MARK: - UITableView Support
private typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
private typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
extension FetchedRecordsController {
// MARK: - Accessing Records
/// Returns the object at the given index path.
///
/// - parameter indexPath: An index path in the fetched records.
///
/// If indexPath does not describe a valid index path in the fetched
/// records, a fatal error is raised.
public func record(at indexPath: IndexPath) -> Record {
guard let fetchedItems = fetchedItems else {
// Programmer error
fatalError("performFetch() has not been called.")
}
return fetchedItems[indexPath[1]].record
}
// MARK: - Querying Sections Information
/// The sections for the fetched records.
///
/// You typically use the sections array when implementing
/// UITableViewDataSource methods, such as `numberOfSectionsInTableView`.
///
/// The sections array is never empty, even when there are no fetched
/// records. In this case, there is a single empty section.
public var sections: [FetchedRecordsSectionInfo<Record>] {
// We only support a single section so far.
// We also return a single section when there are no fetched
// records, just like NSFetchedResultsController.
return [FetchedRecordsSectionInfo(controller: self)]
}
}
extension FetchedRecordsController where Record: MutablePersistable {
/// Returns the indexPath of a given record.
///
/// - returns: The index path of *record* in the fetched records, or nil
/// if record could not be found.
public func indexPath(for record: Record) -> IndexPath? {
let item = Item<Record>(row: Row(record))
guard let fetchedItems = fetchedItems, let index = fetchedItems.index(where: { itemsAreIdentical($0, item) }) else {
return nil
}
return IndexPath(indexes: [0, index])
}
}
private enum ItemChange<T: RowConvertible> {
case insertion(item: Item<T>, indexPath: IndexPath)
case deletion(item: Item<T>, indexPath: IndexPath)
case move(item: Item<T>, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue])
case update(item: Item<T>, indexPath: IndexPath, changes: [String: DatabaseValue])
}
extension ItemChange {
var record: T {
switch self {
case .insertion(item: let item, indexPath: _):
return item.record
case .deletion(item: let item, indexPath: _):
return item.record
case .move(item: let item, indexPath: _, newIndexPath: _, changes: _):
return item.record
case .update(item: let item, indexPath: _, changes: _):
return item.record
}
}
var fetchedRecordChange: FetchedRecordChange {
switch self {
case .insertion(item: _, indexPath: let indexPath):
return .insertion(indexPath: indexPath)
case .deletion(item: _, indexPath: let indexPath):
return .deletion(indexPath: indexPath)
case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes):
return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes)
case .update(item: _, indexPath: let indexPath, changes: let changes):
return .update(indexPath: indexPath, changes: changes)
}
}
}
extension ItemChange: CustomStringConvertible {
var description: String {
switch self {
case .insertion(let item, let indexPath):
return "Insert \(item) at \(indexPath)"
case .deletion(let item, let indexPath):
return "Delete \(item) from \(indexPath)"
case .move(let item, let indexPath, let newIndexPath, changes: let changes):
return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)"
case .update(let item, let indexPath, let changes):
return "Update \(item) at \(indexPath) with changes: \(changes)"
}
}
}
/// A record change, given by a FetchedRecordsController to its change callback.
///
/// The move and update events hold a *changes* dictionary, whose keys are
/// column names, and values the old values that have been changed.
public enum FetchedRecordChange {
/// An insertion event, at given indexPath.
case insertion(indexPath: IndexPath)
/// A deletion event, at given indexPath.
case deletion(indexPath: IndexPath)
/// A move event, from indexPath to newIndexPath. The *changes* are a
/// dictionary whose keys are column names, and values the old values that
/// have been changed.
case move(indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue])
/// An update event, at given indexPath. The *changes* are a dictionary
/// whose keys are column names, and values the old values that have
/// been changed.
case update(indexPath: IndexPath, changes: [String: DatabaseValue])
}
extension FetchedRecordChange: CustomStringConvertible {
public var description: String {
switch self {
case .insertion(let indexPath):
return "Insertion at \(indexPath)"
case .deletion(let indexPath):
return "Deletion from \(indexPath)"
case .move(let indexPath, let newIndexPath, changes: let changes):
return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)"
case .update(let indexPath, let changes):
return "Update at \(indexPath) with changes: \(changes)"
}
}
}
/// A section given by a FetchedRecordsController.
public struct FetchedRecordsSectionInfo<Record: RowConvertible> {
fileprivate let controller: FetchedRecordsController<Record>
/// The number of records (rows) in the section.
public var numberOfRecords: Int {
guard let items = controller.fetchedItems else {
// Programmer error
fatalError("the performFetch() method must be called before accessing section contents")
}
return items.count
}
/// The array of records in the section.
public var records: [Record] {
guard let items = controller.fetchedItems else {
// Programmer error
fatalError("the performFetch() method must be called before accessing section contents")
}
return items.map { $0.record }
}
}
// MARK: - Item
private final class Item<T: RowConvertible> : RowConvertible, Equatable {
let row: Row
// Records are lazily loaded
lazy var record: T = T(row: self.row)
init(row: Row) {
self.row = row.copy()
}
}
private func ==<T> (lhs: Item<T>, rhs: Item<T>) -> Bool {
return lhs.row == rhs.row
}
|
gpl-3.0
|
4ebeda9b70ed9d6656727f128893da59
| 41.001881 | 182 | 0.613913 | 5.319037 | false | false | false | false |
dopcn/DroppingBall
|
DroppingBall/AppDelegate.swift
|
1
|
731
|
//
// AppDelegate.swift
// DroppingBall
//
// Created by weizhou on 7/18/15.
// Copyright (c) 2015 weizhou. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if UIDevice.current.userInterfaceIdiom == .phone {
window!.rootViewController = ViewController()
} else {
window!.rootViewController = ViewControllerHD()
}
window!.makeKeyAndVisible()
return true
}
}
|
mit
|
3f3ad5442fa022f5c7d1bdaa5c7e4392
| 26.074074 | 144 | 0.671683 | 5.006849 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift
|
1
|
2235
|
//
// SchedulerServices+Emulation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
enum SchedulePeriodicRecursiveCommand {
case tick
case dispatchStart
}
final class SchedulePeriodicRecursive<State> {
typealias RecursiveAction = (State) -> State
typealias RecursiveScheduler = AnyRecursiveScheduler<SchedulePeriodicRecursiveCommand>
private let _scheduler: SchedulerType
private let _startAfter: RxTimeInterval
private let _period: RxTimeInterval
private let _action: RecursiveAction
private var _state: State
private var _pendingTickCount: AtomicInt = 0
init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) {
_scheduler = scheduler
_startAfter = startAfter
_period = period
_action = action
_state = state
}
func start() -> Disposable {
return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: _startAfter, action: tick)
}
func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) {
// Tries to emulate periodic scheduling as best as possible.
// The problem that could arise is if handling periodic ticks take too long, or
// tick interval is short.
switch command {
case .tick:
scheduler.schedule(.tick, dueTime: _period)
// The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediatelly.
// Else work will be scheduled after previous enqueued work completes.
if AtomicIncrement(&_pendingTickCount) == 1 {
tick(.dispatchStart, scheduler: scheduler)
}
case .dispatchStart:
_state = _action(_state)
// Start work and schedule check is this last batch of work
if AtomicDecrement(&_pendingTickCount) > 0 {
// This gives priority to scheduler emulation, it's not perfect, but helps
scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart)
}
}
}
}
|
mit
|
29b39dcccaae87567248d7c4c4548678
| 35.622951 | 137 | 0.671441 | 5.020225 | false | false | false | false |
PavelGnatyuk/SimplePurchase
|
SimplePurchase/SimplePurchase/in-app purchase/AppPurchaseController.swift
|
1
|
7033
|
//
// AppPurchaseController.swift
//
// Note:
// On the simulator the purchase does not happen by intention.
//
// Created by Pavel Gnatyuk on 29/04/2017.
//
//
import StoreKit
@objc
class AppPurchaseController: NSObject, PurchaseController {
/// Initial set of product identifiers for the controller works with.
/// It is a constant, making it variable will cause a lot of problems to worry about.
let identifiers: Set<String>
/// Price converter: convert number and locale to a string
var converter: PriceConverter?
/// Payment transaction observer
var observer: PaymentTransactionObserver?
/// Store of the products: product information retrieved from the App Store of for all products
/// (defined by the initial set of the identifiers)
var products: ProductStore?
/// Function that will be called in the end of the buying procedure or in the end of the
/// restore purchases process (for each product).
var onComplete: ((String, Bool, String) -> Void)?
/// Request product information from the App Store
var requester: ProductRequester?
/// Flag that a request was sent and no response has been received yet.
var requestSent: Bool = false
/// The property is `true` when the instance is ready to request the product information:
/// - the instance was initialized correctly with a non-empty set of identifiers.
/// - the requester is not nil
var isReadyToRequest: Bool {
return identifiers.count > 0 && requester != nil
}
/// The property is `true` when the instance is ready to perform an in-app purchase operation:
/// - the product information has been retrieved from the App Store
/// - the payment queue observer is not nil.
var isReadyToPurchase: Bool {
guard let info = products else {
return false
}
return info.count > 0 && observer != nil
}
/// The product information has been retrieved successfully.
var containsProducts: Bool {
guard let info = products else {
return false
}
return info.count > 0
}
required init(identifiers: Set<String>) {
precondition(identifiers.count > 0, "No identifiers and so nothing to do.")
self.identifiers = identifiers
}
// MARK: - Request products
func requestProducts() -> Bool {
guard requestSent == false else {
assertionFailure("The previous request is still alive. No need to send one more.")
return false
}
guard let checkedRequester = requester else {
assertionFailure("The requester was not set")
return false
}
// There is an assert in the ProductRequester initializer about the identifiers parameter.
requestSent = checkedRequester.request(identifiers: identifiers) { [weak self] receivedProducts, invalid in
if let controller = self {
controller.products?.assignTo(store: receivedProducts)
controller.requestSent = false
}
}
return requestSent
}
// MARK: - Price converter
func price(identifier: String) -> String {
guard let priceConverter = converter else {
assertionFailure("Price converter is nil")
return ""
}
guard !identifier.isEmpty else {
assertionFailure("The identifier is required")
return ""
}
guard let store = products else {
assertionFailure("The products should be requested first. No price available")
return ""
}
guard store.count > 0 else {
assertionFailure("The products should be requested first. No price available")
return ""
}
guard let product = store[identifier] else {
assertionFailure("Product with \(identifier) is not found")
return ""
}
return priceConverter.convert(product.price, locale: product.priceLocale)
}
// MARK: - Purchase
/**
Note:
The payment will not be added to the payment queue under the simulator. The callback closure will be called
immediatelly.
*/
func buy(identifier: String) -> Bool {
assert(!identifier.isEmpty, "Empty identifier")
assert(products != nil, "Product store is nil")
//assert((products?.count)! > 0, "No products")
assert(observer != nil, "Transaction observer is nil")
guard !identifier.isEmpty, let transactions = observer, let product = products?[identifier] else {
return false
}
// The real device and the real purchase.
let payment = SKPayment(product: product)
transactions.add(payment)
return true
}
func start() {
observer?.start()
}
func restore() {
observer?.restoreTransactions()
}
}
extension AppPurchaseController: PaymentTransactionObserverDelegate {
/**
The function bellow is called when the payment transaction completed successfully.
In this function the product identifier taken from the succefull transaction is saved in a local store of
already bought product identifiers. Than the transaction is finished.
- Note:
Let's re-consider it. For example, let's finish the transaction after downloading the product.
*/
func onPurchased(_ transaction: SKPaymentTransaction) {
let identifier = transaction.payment.productIdentifier
self.finish(identifier: identifier, transaction: transaction)
}
/**
The transaction failed. The user could cancel the purchase operation and in this case the error text
should be empty (Apple gives "Could not connect to iTunes" or something like that).
*/
func onFailed(_ transaction: SKPaymentTransaction) {
// Let's finish the transaction anyway.
self.observer?.finish(transaction)
// Detect the error description
var errorDescription = ""
if let error = transaction.error as? SKError, error.code != SKError.paymentCancelled {
errorDescription = error.localizedDescription
}
self.onComplete?(transaction.payment.productIdentifier, false, errorDescription)
}
/**
Restore transaction operation succeeded
*/
func onRestored(_ transaction: SKPaymentTransaction) {
guard let identifier = transaction.original?.payment.productIdentifier else {
return
}
self.finish(identifier: identifier, transaction: transaction)
}
/**
Finish the payment transaction and call the complete callback.
*/
private func finish(identifier: String, transaction: SKPaymentTransaction) {
self.onComplete?(identifier, true, "")
self.observer?.finish(transaction)
}
}
|
apache-2.0
|
f8309a4dcd9360f46ebdf8f365d1e3e3
| 33.47549 | 115 | 0.637992 | 5.283997 | false | false | false | false |
GitOyoung/LibraryManagement
|
LibraryManagement/LocalUser.swift
|
1
|
2189
|
//
// LocalUser.swift
// LibraryManagement
//
// Created by Oyoung on 15/11/29.
// Copyright © 2015年 Oyoung. All rights reserved.
//
import UIKit
class LocalUser: NSObject {
static func isLogged() ->Bool
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let loginInfo:NSDictionary? = userDefaults.objectForKey("Local") as? NSDictionary
return (loginInfo != nil) && ((loginInfo?.objectForKey("LOGIN")?.isEqualToString("TRUE"))!)
}
static func isAdmin() -> Bool
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let loginInfo:NSDictionary? = userDefaults.objectForKey("Local") as? NSDictionary
return (loginInfo != nil) && ((loginInfo?.objectForKey("Type")?.isEqualToString("ADMIN"))!)
}
static func Login(name: String?, passwd: String?, type: String?) ->Void
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let loginInfo:NSDictionary? = (userDefaults.objectForKey("Local") as? NSDictionary)
let newInfo: NSMutableDictionary!
if loginInfo == nil
{
newInfo = NSMutableDictionary(capacity: 1)
}
else
{
newInfo = NSMutableDictionary(dictionary: loginInfo!)
}
newInfo.setObject(name!, forKey: "Name")
newInfo.setObject(passwd!, forKey: "Password")
newInfo.setObject("TRUE", forKey: "LOGIN")
newInfo.setObject(type!, forKey: "Type")
userDefaults.setObject(newInfo, forKey: "Local")
userDefaults.synchronize()
}
static func Logout() ->Void
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let loginInfo:NSDictionary? = userDefaults.objectForKey("Local") as? NSDictionary
if loginInfo == nil
{
return
}
let newInfo:NSMutableDictionary! = NSMutableDictionary(dictionary: loginInfo!)
newInfo.setObject("FALSE", forKey: "LOGIN")
userDefaults.setObject(newInfo, forKey: "Local")
userDefaults.synchronize()
}
}
|
gpl-3.0
|
8bb2ef421a1e8164a8689824d5db0096
| 28.945205 | 99 | 0.60613 | 5.143529 | false | false | false | false |
xeecos/motionmaker
|
GIFMaker/ModeSettingCell.swift
|
1
|
931
|
//
// ModeSettingCell.swift
// GIFMaker
//
// Created by indream on 15/9/20.
// Copyright © 2015年 indream. All rights reserved.
//
import UIKit
class ModeSettingCell: UITableViewCell {
@IBOutlet weak var modeSeg: UISegmentedControl!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let setting:SettingModel = DataManager.sharedManager().setting(0)!
modeSeg.selectedSegmentIndex = Int(setting.mode)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func modeChanged(_ sender: AnyObject) {
let sw:UISegmentedControl = sender as! UISegmentedControl
let setting:SettingModel = DataManager.sharedManager().setting(0)!
setting.mode = Int16(sw.selectedSegmentIndex)
}
}
|
mit
|
b6d49b79c5ffc8acd8bc66e9e2661216
| 26.294118 | 74 | 0.678879 | 4.616915 | false | false | false | false |
yuwang17/WYExtensionUtil
|
WYExtensionUtil/WYExtensionUIImageView.swift
|
1
|
817
|
//
// WYExtensionUIImageView.swift
// WYExtensionUtil
//
// Created by Wang Yu on 11/9/15.
// Copyright © 2015 Wang Yu. All rights reserved.
//
import UIKit
extension UIImageView {
public func setURL(url: NSURL?, placeholderImage: UIImage?) {
if let placeholder = placeholderImage {
self.image = placeholder
}
if let urlString = url?.absoluteString {
ImageLoader.sharedInstance.imageForUrl(urlString) { [weak self] image, url in
if let strongSelf = self {
dispatch_async(dispatch_get_main_queue()) {
if urlString == url {
strongSelf.image = image ?? placeholderImage
}
}
}
}
}
}
}
|
mit
|
2315820468c293a7fc2936d8c1852edc
| 27.137931 | 89 | 0.522059 | 5.068323 | false | false | false | false |
takayoshiotake/BBBUSBKit
|
Sources/BBBUSBEndpoint.swift
|
1
|
1521
|
//
// BBBUSBEndpoint.swift
// BBBUSBKit
//
// Created by OTAKE Takayoshi on 2016/12/03.
//
//
import Cocoa
public class BBBUSBEndpoint {
public enum Direction {
case out
case `in`
init(bEndpointAddressBit7: UInt8) {
switch bEndpointAddressBit7 {
case 0b0:
self = .out
case 0b1:
self = .in
default:
fatalError()
}
}
}
public enum TransferType {
case control
case isochronous
case bulk
case interrupt
init(bmAttributesBits1_0: UInt8) {
switch bmAttributesBits1_0 {
case 0b00:
self = .control
case 0b01:
self = .isochronous
case 0b10:
self = .bulk
case 0b11:
self = .interrupt
default:
fatalError()
}
}
}
public let descriptor: BBBUSBEndpointDescriptor
public let direction: Direction
public let transferType: TransferType
weak var interface: BBBUSBInterface!
init(interface: BBBUSBInterface, descriptor: BBBUSBEndpointDescriptor) {
self.interface = interface
self.descriptor = descriptor
direction = Direction(bEndpointAddressBit7: descriptor.bEndpointAddress >> 7)
transferType = TransferType(bmAttributesBits1_0: descriptor.bmAttributes & 0x03)
}
}
|
mit
|
df2b20fab4c996b3ace72f324fc643e3
| 23.142857 | 88 | 0.538462 | 4.581325 | false | false | false | false |
gdelarosa/Safe-Reach
|
Safe Reach/AboutVC.swift
|
1
|
1857
|
//
// AboutVC.swift
// Safe Reach
//
// Created by Gina De La Rosa on 11/20/16.
// Copyright © 2016 Gina De La Rosa. All rights reserved.
//
import UIKit
import MessageUI
class AboutVC: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Navigation Controller UI
let imageView = UIImageView(image: UIImage(named: "Triangle"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}
@IBAction func website(_ sender: AnyObject) {
if let url = URL(string: "http://www.safereachapp.com/") {
UIApplication.shared.open(url, options: [:])
}
}
@IBAction func email(_ sender: AnyObject) {
let toRecipients = ["[email protected]"]
let mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setToRecipients(toRecipients)
mc.setSubject("Safe Reach App Inquiry")
self.present(mc, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result.rawValue {
case MFMailComposeResult.cancelled.rawValue:
print("Cancelled")
case MFMailComposeResult.failed.rawValue:
print("Failed")
case MFMailComposeResult.saved.rawValue:
print("Saved")
case MFMailComposeResult.sent.rawValue:
print("Sent")
default:
break
}
self.dismiss(animated: true, completion: nil)
}
}
|
mit
|
a16a35fde807c702d8f13ffe739f2d47
| 31 | 133 | 0.650323 | 4.833333 | false | false | false | false |
pietrorea/UniqueConstraintsSample
|
UniqueConstraintsSample/UniqueConstraintsSample/ViewController.swift
|
1
|
1429
|
//
// ViewController.swift
// UniqueConstraintsSample
//
// Created by Pietro Rea on 11/15/15.
// Copyright © 2015 Pietro Rea. All rights reserved.
//
import UIKit
import CoreData
private let SampletEntityName = "SampleEntity"
class ViewController: UIViewController {
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func saveJohn(sender: AnyObject) {
let sampleEntity = NSEntityDescription.insertNewObjectForEntityForName(SampletEntityName,
inManagedObjectContext: context) as! SampleEntity
sampleEntity.name = "John"
do {
try context.save()
printAllSampleEntities()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
func printAllSampleEntities() {
let fetchRequest = NSFetchRequest(entityName: SampletEntityName)
do {
let results =
try context.executeFetchRequest(fetchRequest) as! [SampleEntity]
for sampleEntity in results {
print("name: \(sampleEntity.name!)")
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
}
|
mit
|
f3f0ff13af30920de8c29d35a8682df2
| 25.444444 | 97 | 0.605042 | 5.028169 | false | false | false | false |
ryan-blunden/ga-mobile
|
ToDo - completed/ToDo/AuthDataManager.swift
|
2
|
1394
|
//
// AuthDataManager.swift
// ToDo
//
// Created by Ryan Blunden on 28/04/2015.
// Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved.
//
import Foundation
struct Login {
let email:String
let password:String
}
var LOGINS:[Login] = []
class AuthDataManager {
init() {
loadAuthorisedUsers()
}
func loadAuthorisedUsers() {
LOGINS.append(Login(email: "[email protected]", password: "applecar"))
}
func processLogin(email: String, password:String, completion:(result: Bool) -> Void) {
// TODO: Move the username and password matching to a data manager, this is not the controller's job!
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
var authResult = false
// See if user matches supplied credentials
for user in LOGINS {
if user.email == email && user.password == password {
authResult = true
break
}
}
// Simulate delay
let delayInSeconds = 2.0
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion(result:authResult)
}
}
}
}
|
gpl-3.0
|
5618c989e67c994551ae2c8d8e9a1d07
| 27.469388 | 109 | 0.566714 | 4.342679 | false | false | false | false |
bcylin/QuickTableViewController
|
Example-iOS/SwiftUI/DynamicViewController.swift
|
1
|
3564
|
//
// DynamicViewController.swift
// Example-iOS
//
// Created by Ben on 13/08/2022.
// Copyright © 2022 bcylin.
//
// 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.
//
import SwiftUI
@available(iOS 13.0, *)
final class DynamicViewController: UIHostingController<DynamicTableView> {
init() {
super.init(rootView: DynamicTableView())
title = "Dynamic"
}
required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - ViewModel
@available(iOS 13.0, *)
private final class ViewModel: ObservableObject {
@Published var items: [Item] = []
struct Item: Hashable, Identifiable {
let id = UUID()
let title: String
let number: Int
}
func addItem() {
let newItem = Item(title: "UITableViewCell", number: items.count + 1)
items.append(newItem)
}
}
// MARK: - View
@available(iOS 13.0, *)
struct DynamicTableView: View {
@ObservedObject private var viewModel = ViewModel()
@State private var editMode: EditMode = .inactive
var body: some View {
List {
Section(header: Text("SwiftUI Example")) {
addButton
list(of: viewModel.items)
}
}
.withEditButton()
.environment(\.editMode, $editMode)
}
private var addButton: some View {
Button {
withAnimation { viewModel.addItem() }
} label: {
Text("Add")
.frame(maxWidth: .infinity)
.foregroundColor(editMode == .active ? .gray : .blue)
}
}
private func list(of items: [ViewModel.Item]) -> some View {
ForEach(Array(items.enumerated()), id: \.element) { _, item in
HStack {
Text(item.title)
Spacer()
Text("\(item.number)")
}
}
.onDelete { indexSet in
viewModel.items.remove(atOffsets: indexSet)
}
.onMove { indexSet, newOffset in
viewModel.items.move(fromOffsets: indexSet, toOffset: newOffset)
}
}
}
@available(iOS 13.0, *)
private extension View {
@ViewBuilder
func withEditButton() -> some View {
if #available(iOS 14.0, *) {
self.toolbar { EditButton() }
} else {
self
}
}
}
@available(iOS 13.0, *)
struct TableView_Previews: PreviewProvider {
static var previews: some View {
DynamicTableView()
}
}
|
mit
|
d605757025323651043bef301f19be9b
| 28.204918 | 82 | 0.621106 | 4.345122 | false | false | false | false |
PatrickSCLin/PLTimeSlider
|
PLTimeSliderDemo/ViewController.swift
|
1
|
1741
|
//
// ViewController.swift
// PLTimeSliderDemo
//
// Created by Patrick Lin on 09/12/2016.
// Copyright © 2016 Patrick Lin. All rights reserved.
//
import UIKit
import PLTimeSlider
class ViewController: UIViewController, PLTimeSliderDelegate {
@IBOutlet var slider: PLTimeSlider!
@IBOutlet var startLable: UILabel!
@IBOutlet var endLable: UILabel!
@IBOutlet var totalLabel: UILabel!
// MARK: Time Slider Methods
func slider(slider: PLTimeSlider, valueDidChanged value: UInt, type: PLTimeSliderValueType) {
if type == .start {
self.startLable.text = String(format: "%02d:00", value)
self.monoFont(label: self.startLable, weight: UIFontWeightBold)
}
else if type == .end {
self.endLable.text = String(format: "%02d:00", value)
self.monoFont(label: self.endLable, weight: UIFontWeightBold)
}
let total = slider.endHour - slider.startHour
self.totalLabel.text = "\(total) Hours"
self.monoFont(label: self.totalLabel, weight: UIFontWeightBold)
}
// MARK: Interal Methods
func monoFont(label: UILabel, weight: CGFloat) {
label.font = UIFont.monospacedDigitSystemFont(ofSize: label.font.pointSize, weight: weight)
}
// MARK: Init Methods
override func viewDidLoad() {
super.viewDidLoad()
self.slider.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
e1a360ed1d933dcc282e6ea6646931ab
| 22.2 | 99 | 0.568966 | 4.833333 | false | false | false | false |
akrio714/Wbm
|
Wbm/Component/Button/NumButton.swift
|
1
|
1472
|
//
// NumButton.swift
// Wbm
//
// Created by akrio on 2017/7/16.
// Copyright © 2017年 akrio. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
@IBDesignable
class NumButton: UIButton {
override func draw(_ rect: CGRect) {
guard self.num != 0 else {
return
}
let buttonWidth = self.frame.width
let buttonHeight = self.frame.height
//获取上下文对象
let context = UIGraphicsGetCurrentContext()
//绘制数字所需图形
context?.setFillColor(UIColor.Theme.red.color.cgColor)
context?.fillEllipse(in: CGRect(x: buttonWidth-buttonHeight, y: 0, width: buttonHeight, height: buttonHeight))
//绘制数字
let font = UIFont.systemFont(ofSize: self.titleLabel?.font.pointSize ?? 16)
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let numReact = CGRect(x: buttonWidth-buttonHeight, y: 0, width: buttonHeight, height: buttonHeight)
let numColor = UIColor.white
("\(num)" as NSString).draw(in: numReact, withAttributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:numColor,NSParagraphStyleAttributeName:style])
context?.strokePath()
}
@IBInspectable public var num:Int = 0 {
didSet {
guard self.num != 0 else {
return
}
self.contentEdgeInsets.right = 25
}
}
}
|
apache-2.0
|
f94c4c3634d79f6db3039944ce3ba717
| 31.522727 | 169 | 0.635919 | 4.528481 | false | false | false | false |
honghaoz/RRNCollapsableSectionTableViewSwift
|
RRNCollapsableTableScene.swift
|
1
|
6031
|
//
// RRNCollapsableTableScene.swift
// Example-Swift
//
// Created by Robert Nash on 22/09/2015.
// Copyright © 2015 Robert Nash. All rights reserved.
//
import UIKit
class RRNCollapsableTableViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let
tableView = self.collapsableTableView(),
nibName = self.sectionHeaderNibName(),
reuseID = self.sectionHeaderReuseIdentifier()
{
let nib = UINib(nibName: nibName, bundle: nil)
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: reuseID)
}
}
func collapsableTableView() -> UITableView? {
return nil
}
func model() -> [RRNCollapsableSectionItemProtocol]? {
return nil
}
func singleOpenSelectionOnly() -> Bool {
return false
}
func sectionHeaderNibName() -> String? {
return nil
}
func sectionHeaderReuseIdentifier() -> String? {
return self.sectionHeaderNibName()?.stringByAppendingString("ID")
}
}
extension RRNCollapsableTableViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return (self.model() ?? []).count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let menuSection = self.model()?[section]
return (menuSection?.isVisible ?? false) ? menuSection!.items.count : 0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var view: RRNCollapsableSectionHeaderProtocol?
if let reuseID = self.sectionHeaderReuseIdentifier() {
view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(reuseID) as? RRNCollapsableSectionHeaderProtocol
}
view?.tag = section
let menuSection = self.model()?[section]
view?.sectionTitleLabel.text = (menuSection?.title ?? "")
view?.interactionDelegate = self
return view as? UIView
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
extension RRNCollapsableTableViewController: UITableViewDelegate {
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? RRNCollapsableSectionHeaderProtocol {
let menuSection = self.model()?[section]
if (menuSection?.isVisible ?? false) {
view.open(false)
} else {
view.close(false)
}
}
}
}
extension RRNCollapsableTableViewController: RRNCollapsableSectionHeaderReactiveProtocol {
func userTapped(view: RRNCollapsableSectionHeaderProtocol) {
if let tableView = self.collapsableTableView() {
let section = view.tag
tableView.beginUpdates()
var foundOpenUnchosenMenuSection = false
let menu = self.model()
if let menu = menu {
var count = 0
for var menuSection in menu {
let chosenMenuSection = (section == count)
let isVisible = menuSection.isVisible
if isVisible && chosenMenuSection {
menuSection.isVisible = false
view.close(true)
let indexPaths = self.indexPaths(section, menuSection: menuSection)
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: (foundOpenUnchosenMenuSection) ? .Bottom : .Top)
} else if !isVisible && chosenMenuSection {
menuSection.isVisible = true
view.open(true)
let indexPaths = self.indexPaths(section, menuSection: menuSection)
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: (foundOpenUnchosenMenuSection) ? .Bottom : .Top)
} else if isVisible && !chosenMenuSection && self.singleOpenSelectionOnly() {
foundOpenUnchosenMenuSection = true
menuSection.isVisible = false
let headerView = tableView.headerViewForSection(count)
if let headerView = headerView as? RRNCollapsableSectionHeaderProtocol {
headerView.close(true)
}
let indexPaths = self.indexPaths(count, menuSection: menuSection)
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: (view.tag > count) ? .Top : .Bottom)
}
count++
}
}
tableView.endUpdates()
}
}
func indexPaths(section: Int, menuSection: RRNCollapsableSectionItemProtocol) -> [NSIndexPath] {
var collector = [NSIndexPath]()
var indexPath: NSIndexPath
for var i = 0; i < menuSection.items.count; i++ {
indexPath = NSIndexPath(forRow: i, inSection: section)
collector.append(indexPath)
}
return collector
}
}
|
mit
|
e4b2fb1cb115453c150f9f446087ca1f
| 33.073446 | 135 | 0.531509 | 6.190965 | false | false | false | false |
ishitaswarup/RWPickFlavor2
|
RWPickFlavor2/IceCreamView.swift
|
21
|
14512
|
//
// IceCreamView.swift
// IceCreamShop
//
// Created by Joshua Greene on 2/8/15.
// Copyright (c) 2015 Razeware, LLC. All rights reserved.
//
import UIKit
@IBDesignable
class IceCreamView: UIView {
// MARK: Variables
@IBInspectable var iceCreamTopColor: UIColor = Flavor.vanilla().topColor {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var iceCreamBottomColor: UIColor = Flavor.vanilla().topColor {
didSet {
setNeedsDisplay()
}
}
private let coneOuterColor = RGB(184, 104, 50)
private let coneInnerColor = RGB(209, 160, 102)
private let coneLaticeColor = RGB(235, 183, 131)
// MARK: View Lifecycle
override func drawRect(frame: CGRect) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Gradient Declarations
let iceCreamGradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [iceCreamTopColor.CGColor, iceCreamBottomColor.CGColor], [0, 1])
//// Shadow Declarations
let coneInnerShadow = coneOuterColor
let coneInnerShadowOffset = CGSizeMake(0.1, -0.1)
let coneInnerShadowBlurRadius: CGFloat = 35
let scoopShadow = UIColor.blackColor().colorWithAlphaComponent(0.25)
let scoopShadowOffset = CGSizeMake(0.1, 3.1)
let scoopShadowBlurRadius: CGFloat = 2
let coneOuterShadow = UIColor.blackColor().colorWithAlphaComponent(0.35)
let coneOuterShadowOffset = CGSizeMake(0.1, 3.1)
let coneOuterShadowBlurRadius: CGFloat = 3
//// Cone Drawing
var conePath = UIBezierPath()
conePath.moveToPoint(CGPointMake(frame.minX + 0.98284 * frame.width, frame.minY + 0.29579 * frame.height))
conePath.addCurveToPoint(CGPointMake(frame.minX + 0.49020 * frame.width, frame.minY + 0.35519 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.98284 * frame.width, frame.minY + 0.29579 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.72844 * frame.width, frame.minY + 0.35519 * frame.height))
conePath.addCurveToPoint(CGPointMake(frame.minX + 0.01225 * frame.width, frame.minY + 0.29579 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.25196 * frame.width, frame.minY + 0.35519 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.01225 * frame.width, frame.minY + 0.29579 * frame.height))
conePath.addLineToPoint(CGPointMake(frame.minX + 0.49265 * frame.width, frame.minY + 0.98886 * frame.height))
conePath.addLineToPoint(CGPointMake(frame.minX + 0.98284 * frame.width, frame.minY + 0.29579 * frame.height))
conePath.closePath()
conePath.lineJoinStyle = kCGLineJoinRound;
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, coneOuterShadowOffset, coneOuterShadowBlurRadius, (coneOuterShadow as UIColor).CGColor)
coneInnerColor.setFill()
conePath.fill()
////// Cone Inner Shadow
CGContextSaveGState(context)
CGContextClipToRect(context, conePath.bounds)
CGContextSetShadow(context, CGSizeMake(0, 0), 0)
CGContextSetAlpha(context, CGColorGetAlpha((coneInnerShadow as UIColor).CGColor))
CGContextBeginTransparencyLayer(context, nil)
let coneOpaqueShadow = (coneInnerShadow as UIColor).colorWithAlphaComponent(1)
CGContextSetShadowWithColor(context, coneInnerShadowOffset, coneInnerShadowBlurRadius, (coneOpaqueShadow as UIColor).CGColor)
CGContextSetBlendMode(context, kCGBlendModeSourceOut)
CGContextBeginTransparencyLayer(context, nil)
coneOpaqueShadow.setFill()
conePath.fill()
CGContextEndTransparencyLayer(context)
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
coneOuterColor.setStroke()
conePath.lineWidth = 0.5
conePath.stroke()
//// Lattice 1 Drawing
var lattice1Path = UIBezierPath()
lattice1Path.moveToPoint(CGPointMake(frame.minX + 0.41667 * frame.width, frame.minY + 0.86881 * frame.height))
lattice1Path.addLineToPoint(CGPointMake(frame.minX + 0.62255 * frame.width, frame.minY + 0.79950 * frame.height))
coneLaticeColor.setStroke()
lattice1Path.lineWidth = 1
lattice1Path.stroke()
//// Lattice 2 Drawing
var lattice2Path = UIBezierPath()
lattice2Path.moveToPoint(CGPointMake(frame.minX + 0.34804 * frame.width, frame.minY + 0.76980 * frame.height))
lattice2Path.addLineToPoint(CGPointMake(frame.minX + 0.73039 * frame.width, frame.minY + 0.64604 * frame.height))
coneLaticeColor.setStroke()
lattice2Path.lineWidth = 1
lattice2Path.stroke()
//// Lattice 3 Drawing
var lattice3Path = UIBezierPath()
lattice3Path.moveToPoint(CGPointMake(frame.minX + 0.27941 * frame.width, frame.minY + 0.67079 * frame.height))
lattice3Path.addLineToPoint(CGPointMake(frame.minX + 0.82843 * frame.width, frame.minY + 0.50743 * frame.height))
coneLaticeColor.setStroke()
lattice3Path.lineWidth = 1
lattice3Path.stroke()
//// Lattice 4 Drawing
var lattice4Path = UIBezierPath()
lattice4Path.moveToPoint(CGPointMake(frame.minX + 0.21078 * frame.width, frame.minY + 0.57178 * frame.height))
lattice4Path.addLineToPoint(CGPointMake(frame.minX + 0.92647 * frame.width, frame.minY + 0.36881 * frame.height))
coneLaticeColor.setStroke()
lattice4Path.lineWidth = 1
lattice4Path.stroke()
//// Lattice 5 Drawing
var lattice5Path = UIBezierPath()
lattice5Path.moveToPoint(CGPointMake(frame.minX + 0.14216 * frame.width, frame.minY + 0.47277 * frame.height))
lattice5Path.addLineToPoint(CGPointMake(frame.minX + 0.53431 * frame.width, frame.minY + 0.35891 * frame.height))
coneLaticeColor.setStroke()
lattice5Path.lineWidth = 1
lattice5Path.stroke()
//// Lattice 6 Drawing
var lattice6Path = UIBezierPath()
lattice6Path.moveToPoint(CGPointMake(frame.minX + 0.07353 * frame.width, frame.minY + 0.37376 * frame.height))
lattice6Path.addLineToPoint(CGPointMake(frame.minX + 0.20098 * frame.width, frame.minY + 0.33416 * frame.height))
coneLaticeColor.setStroke()
lattice6Path.lineWidth = 1
lattice6Path.stroke()
//// Lattice 7 Drawing
var lattice7Path = UIBezierPath()
coneLaticeColor.setStroke()
lattice7Path.lineWidth = 1
lattice7Path.stroke()
//// Lattice 8 Drawing
var lattice8Path = UIBezierPath()
UIColor.blackColor().setStroke()
lattice8Path.lineWidth = 1
lattice8Path.stroke()
//// Lattice 9 Drawing
var lattice9Path = UIBezierPath()
lattice9Path.moveToPoint(CGPointMake(frame.minX + 0.64706 * frame.width, frame.minY + 0.76733 * frame.height))
lattice9Path.addLineToPoint(CGPointMake(frame.minX + 0.25490 * frame.width, frame.minY + 0.64356 * frame.height))
coneLaticeColor.setStroke()
lattice9Path.lineWidth = 1
lattice9Path.stroke()
//// Lattice 10 Drawing
var lattice10Path = UIBezierPath()
lattice10Path.moveToPoint(CGPointMake(frame.minX + 0.71569 * frame.width, frame.minY + 0.66832 * frame.height))
lattice10Path.addLineToPoint(CGPointMake(frame.minX + 0.16176 * frame.width, frame.minY + 0.50248 * frame.height))
coneLaticeColor.setStroke()
lattice10Path.lineWidth = 1
lattice10Path.stroke()
//// Lattice 11 Drawing
var lattice11Path = UIBezierPath()
lattice11Path.moveToPoint(CGPointMake(frame.minX + 0.78922 * frame.width, frame.minY + 0.56683 * frame.height))
lattice11Path.addLineToPoint(CGPointMake(frame.minX + 0.06373 * frame.width, frame.minY + 0.35891 * frame.height))
coneLaticeColor.setStroke()
lattice11Path.lineWidth = 1
lattice11Path.stroke()
//// Lattice 12 Drawing
var lattice12Path = UIBezierPath()
lattice12Path.moveToPoint(CGPointMake(frame.minX + 0.85294 * frame.width, frame.minY + 0.46535 * frame.height))
lattice12Path.addLineToPoint(CGPointMake(frame.minX + 0.46078 * frame.width, frame.minY + 0.35644 * frame.height))
coneLaticeColor.setStroke()
lattice12Path.lineWidth = 1
lattice12Path.stroke()
//// Lattice 13 Drawing
var lattice13Path = UIBezierPath()
lattice13Path.moveToPoint(CGPointMake(frame.minX + 0.92157 * frame.width, frame.minY + 0.37129 * frame.height))
lattice13Path.addLineToPoint(CGPointMake(frame.minX + 0.79412 * frame.width, frame.minY + 0.33168 * frame.height))
coneLaticeColor.setStroke()
lattice13Path.lineWidth = 1
lattice13Path.stroke()
//// Lattice 14 Drawing
var lattice14Path = UIBezierPath()
lattice14Path.moveToPoint(CGPointMake(frame.minX + 0.58333 * frame.width, frame.minY + 0.85891 * frame.height))
lattice14Path.addCurveToPoint(CGPointMake(frame.minX + 0.35784 * frame.width, frame.minY + 0.78465 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.36765 * frame.width, frame.minY + 0.78465 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.35784 * frame.width, frame.minY + 0.78465 * frame.height))
coneLaticeColor.setStroke()
lattice14Path.lineWidth = 1
lattice14Path.stroke()
//// Scoop Drawing
var scoopPath = UIBezierPath()
scoopPath.moveToPoint(CGPointMake(frame.minX + 0.39216 * frame.width, frame.minY + 0.35149 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.50000 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.43137 * frame.width, frame.minY + 0.35149 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.43137 * frame.width, frame.minY + 0.40099 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.58824 * frame.width, frame.minY + 0.35149 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.56863 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.54902 * frame.width, frame.minY + 0.35149 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.68627 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.62745 * frame.width, frame.minY + 0.35149 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.62745 * frame.width, frame.minY + 0.40099 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.78431 * frame.width, frame.minY + 0.33663 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.74510 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.74510 * frame.width, frame.minY + 0.33663 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.88235 * frame.width, frame.minY + 0.37129 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.82353 * frame.width, frame.minY + 0.33663 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.82353 * frame.width, frame.minY + 0.37129 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.30198 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.94118 * frame.width, frame.minY + 0.37129 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.31683 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.25248 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.28713 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.26967 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.50000 * frame.width, frame.minY + 0.00495 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.99020 * frame.width, frame.minY + 0.11577 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.77073 * frame.width, frame.minY + 0.00495 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.25248 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.22927 * frame.width, frame.minY + 0.00495 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.11577 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.30198 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.27047 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.28713 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.10784 * frame.width, frame.minY + 0.37624 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.00980 * frame.width, frame.minY + 0.31683 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.04902 * frame.width, frame.minY + 0.37624 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.19608 * frame.width, frame.minY + 0.33663 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.16667 * frame.width, frame.minY + 0.37624 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.15686 * frame.width, frame.minY + 0.33663 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.29412 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.23529 * frame.width, frame.minY + 0.33663 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.22549 * frame.width, frame.minY + 0.40099 * frame.height))
scoopPath.addCurveToPoint(CGPointMake(frame.minX + 0.39216 * frame.width, frame.minY + 0.35149 * frame.height), controlPoint1: CGPointMake(frame.minX + 0.36275 * frame.width, frame.minY + 0.40099 * frame.height), controlPoint2: CGPointMake(frame.minX + 0.35294 * frame.width, frame.minY + 0.35149 * frame.height))
scoopPath.closePath()
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, scoopShadowOffset, scoopShadowBlurRadius, (scoopShadow as UIColor).CGColor)
CGContextBeginTransparencyLayer(context, nil)
scoopPath.addClip()
let scoopBounds = CGPathGetPathBoundingBox(scoopPath.CGPath)
CGContextDrawLinearGradient(context, iceCreamGradient,
CGPointMake(scoopBounds.midX, scoopBounds.minY),
CGPointMake(scoopBounds.midX, scoopBounds.maxY),
0)
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
}
}
extension IceCreamView: FlavorAdapter {
func updateWithFlavor(flavor: Flavor) {
self.iceCreamTopColor = flavor.topColor
self.iceCreamBottomColor = flavor.bottomColor
setNeedsDisplay()
}
}
|
mit
|
56e7abd95296ac34659a6d4b56475b9f
| 55.6875 | 321 | 0.725469 | 3.563851 | false | false | false | false |
danielsaidi/KeyboardKit
|
Demo/Keyboard/KeyboardViewController.swift
|
1
|
3054
|
//
// KeyboardViewController.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
import KeyboardKit
import SwiftUI
import Combine
/**
This SwiftUI-based demo keyboard demonstrates how to create
a keyboard extension using `KeyboardKit` and `SwiftUI`.
This keyboard sends text and emoji inputs to the text proxy,
copies tapped images to the device's pasteboard, saves long
pressed images to photos etc. It also adds an auto complete
toolbar that provides fake suggestions for the current word.
`IMPORTANT` To use this keyboard, you must enable it in the
system keyboard settings ("Settings/General/Keyboards"). It
needs full access for haptic and audio feedback, for access
to the user's photos etc.
If you want to use these features in your own app, you must
add `RequestsOpenAccess` to the extension's `Info.plist` to
make it possible to enable full access. To access the photo
album, you have to add a `NSPhotoLibraryAddUsageDescription`
key to the `host` application's `Info.plist`.
*/
class KeyboardViewController: KeyboardInputViewController {
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
// Change this if you want to try some other locales
keyboardContext.locale = LocaleKey.english.locale
// Setup a custom action handler to handle images
keyboardActionHandler = DemoKeyboardActionHandler(
inputViewController: self,
toastContext: toastContext)
// Setup a layout with .emojis instead of .dictation
keyboardLayoutProvider = StandardKeyboardLayoutProvider(
inputSetProvider: keyboardInputSetProvider,
dictationReplacement: .keyboardType(.emojis))
// Setup the extension to use the keyboardView below
setup(with: keyboardView)
// Setup the rest of the extension
super.viewDidLoad()
}
// MARK: - Properties
private lazy var toastContext = KeyboardToastContext()
private var keyboardView: some View {
KeyboardView(
actionHandler: keyboardActionHandler,
appearance: keyboardAppearance,
layoutProvider: keyboardLayoutProvider)
.environmentObject(toastContext)
}
// MARK: - Autocomplete
private lazy var autocompleteProvider = DemoAutocompleteSuggestionProvider()
override func performAutocomplete() {
guard let word = textDocumentProxy.currentWord else { return resetAutocomplete() }
autocompleteProvider.autocompleteSuggestions(for: word) { [weak self] result in
switch result {
case .failure(let error): print(error.localizedDescription)
case .success(let result): self?.autocompleteContext.suggestions = result
}
}
}
override func resetAutocomplete() {
autocompleteContext.suggestions = []
}
}
|
mit
|
fde8733a8122eb942203836741f6ec6a
| 32.184783 | 90 | 0.685555 | 5.318815 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.