repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MyAppConverter/HTMLtoPDF-Demo-Swift | NDHTMLtoPDF.swift | 1 | 8732 | //
// NDHTMLtoPDF.m
// Nurves
//
// Created by Clement Wehrung on 31/10/12.
// Copyright (c) 2012-2014 Clement Wehrung. All rights reserved.
//
// Released under the MIT license
//
// Contact [email protected] for any question.
//
// Sources : http://www.labs.saachitech.com/2012/10/23/pdf-generation-using-uiprintpagerenderer/
// Addons : http://developer.apple.com/library/ios/#samplecode/PrintWebView/Listings/MyPrintPageRenderer_m.html#//apple_ref/doc/uid/DTS40010311-MyPrintPageRenderer_m-DontLinkElementID_7
// *******************************************************************************************
// * *
// **This code has been automaticaly ported to Swift language1.2 using MyAppConverter.com **
// * 11/06/2015 *
// *******************************************************************************************
import UIKit
typealias NDHTMLtoPDFCompletionBlock = (htmlToPDF:NDHTMLtoPDF) -> Void
protocol NDHTMLtoPDFDelegate{
func HTMLtoPDFDidSucceed( htmlToPDF:NDHTMLtoPDF )
func HTMLtoPDFDidFail( htmlToPDF:NDHTMLtoPDF )
}
class NDHTMLtoPDF :UIViewController,UIWebViewDelegate
{
var PDFpath:NSString?
var successBlock:NDHTMLtoPDFCompletionBlock?
var delegate:AnyObject?/////////NDHTMLtoPDFDelegate?
var PDFdata:NSData?
var errorBlock:NDHTMLtoPDFCompletionBlock?
var URL:NSURL?
var HTML:NSString?
var webview:UIWebView?
var pageSize:CGSize?
var pageMargins:UIEdgeInsets?
func createPDFWithURL( URL:NSURL ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(URL:URL , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
func createPDFWithHTML( HTML:NSString ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: nil , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
func createPDFWithHTML( HTML:NSString ,baseURL:NSURL ,pathForPDF PDFpath:NSString ,delegate:AnyObject ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: baseURL , delegate: delegate , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
return creator
}
func createPDFWithURL( URL:NSURL ,pathForPDF PDFpath:NSString ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(URL:URL , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
func createPDFWithHTML( HTML:NSString ,pathForPDF PDFpath:NSString ,pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML:HTML , baseURL: nil , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
func createPDFWithHTML( HTML:NSString ,baseURL:NSURL ,pathForPDF PDFpath:NSString , pageSize:CGSize ,margins pageMargins:UIEdgeInsets ,successBlock:NDHTMLtoPDFCompletionBlock ,errorBlock:NDHTMLtoPDFCompletionBlock )->AnyObject{
var creator:NDHTMLtoPDF = NDHTMLtoPDF(HTML: HTML , baseURL: baseURL , delegate: nil , pathForPDF: PDFpath , pageSize: pageSize , margins: pageMargins )
creator.successBlock = successBlock
creator.errorBlock = errorBlock
return creator
}
init(){
super.init(nibName: nil, bundle: nil)
self.PDFdata = nil
}
init( URL:NSURL? ,delegate:AnyObject? ,pathForPDF PDFpath:NSString? ,pageSize:CGSize? ,margins pageMargins:UIEdgeInsets? ){
super.init(nibName:nil, bundle:nil)
self.URL = URL!
self.delegate = delegate
self.PDFpath = PDFpath!
self.pageMargins = pageMargins!
self.pageSize = pageSize!
self.forceLoadView()
}
init( HTML:NSString ,baseURL:NSURL? ,delegate:AnyObject? ,pathForPDF PDFpath:NSString? ,pageSize:CGSize? ,margins pageMargins:UIEdgeInsets? ){
super.init(nibName:nil, bundle:nil)
self.HTML = HTML
self.URL = baseURL!
self.delegate = delegate
self.PDFpath = PDFpath!
self.pageMargins = pageMargins!
self.pageSize = pageSize!
self.forceLoadView()
}
func forceLoadView(){
UIApplication.sharedApplication().delegate!.window!!.addSubview(self.view )
self.view.frame = CGRectMake( 0 , 0 , 1 , 1 )
self.view.alpha = 0.000000
}
override func viewDidLoad(){
super.viewDidLoad()
self.webview = UIWebView(frame: self.view.frame )
webview!.delegate = self
self.view.addSubview(webview! )
if self.HTML == nil {
webview!.loadRequest(NSURLRequest(URL:self.URL! ) )
}else {
webview!.loadHTMLString(self.HTML as! String , baseURL:self.URL)
}
}
func webViewDidFinishLoad( webView:UIWebView ){
if webView.loading {
return
}
var render:UIPrintPageRenderer = UIPrintPageRenderer()
render.addPrintFormatter(webView.viewPrintFormatter() , startingAtPageAtIndex: 0 )
var printableRect:CGRect = CGRectMake(self.pageMargins!.left , self.pageMargins!.top , self.pageSize!.width - self.pageMargins!.left - self.pageMargins!.right , self.pageSize!.height - self.pageMargins!.top - self.pageMargins!.bottom )
var paperRect:CGRect = CGRectMake( 0 , 0 , self.pageSize!.width , self.pageSize!.height )
render.setValue(NSValue(CGRect: paperRect ) , forKey:"paperRect" )
render.setValue(NSValue(CGRect: printableRect ) , forKey:"printableRect" )
self.PDFdata = render.printToPDF()
if (self.PDFpath != nil) {
self.PDFdata?.writeToFile(self.PDFpath as! String , atomically:true )
}
self.terminateWebTask()
if (self.delegate != nil) && (self.delegate! as! UIViewController).respondsToSelector(Selector("HTMLtoPDFDidSucceed:") ) {
(self.delegate! as! NDHTMLtoPDFDelegate).HTMLtoPDFDidSucceed(self )
}
if (self.successBlock != nil) {
self.successBlock!(htmlToPDF: self);
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func webView(webView: UIWebView, didFailLoadWithError error:NSError)
{
if webView.loading {
return
}
self.terminateWebTask()
if self.delegate != nil && self.delegate!.respondsToSelector(Selector("HTMLtoPDFDidFail"))
{
(self.delegate! as! NDHTMLtoPDFDelegate).HTMLtoPDFDidFail(self)
}
if (self.errorBlock != nil) {
self.errorBlock!(htmlToPDF: self)
}
}
func terminateWebTask()
{
self.webview!.stopLoading()
self.webview!.delegate = nil
self.webview!.removeFromSuperview()
self.view.removeFromSuperview()
self.webview = nil
}
}
extension UIPrintPageRenderer
{
func printToPDF()->NSData
{
var pdfData:NSMutableData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, self.paperRect,nil )
self.prepareForDrawingPages(NSMakeRange(0, self.numberOfPages()))
var bounds:CGRect = UIGraphicsGetPDFContextBounds()
for var i:Int = 0 ; i < self.numberOfPages() ; i++
{
UIGraphicsBeginPDFPage()
self.drawPageAtIndex(i, inRect:bounds)
}
UIGraphicsEndPDFContext()
return pdfData
}
} | mit | 80e503bdbc390f44477928a079552e1c | 36.642241 | 247 | 0.617728 | 5.056167 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/ExecutionContext/ExecutionContext/ImmediateExecutionContext.swift | 111 | 1628 | //===--- ImmediateExecutionContext.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
import Boilerplate
class ImmediateExecutionContext : ExecutionContextBase, ExecutionContextType {
func async(task:SafeTask) {
let context = currentContext.value
defer {
currentContext.value = context
}
currentContext.value = self
task()
}
func async(after:Timeout, task:SafeTask) {
async {
Thread.sleep(after)
task()
}
}
func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType {
let context = currentContext.value
defer {
currentContext.value = context
}
currentContext.value = self
return try task()
}
func isEqualTo(other:NonStrictEquatable) -> Bool {
return other is ImmediateExecutionContext
}
} | mit | 811c45266a2628d98be28f455d7b4026 | 30.941176 | 100 | 0.601351 | 5.285714 | false | false | false | false |
NikoYuwono/Genetic-Swift | Hello Swift/Hello Swift/HelloPlayground.playground/section-1.swift | 2 | 562 | // Playground - noun: a place where people can play
import UIKit
var gene = "Holla"
var mutatedIndex = arc4random_uniform(UInt32(countElements(gene)))
var newGene = ""
var index = 0
for oldCharacter in gene {
var newCharacter = oldCharacter
if index == Int(mutatedIndex) {
newCharacter = Character(UnicodeScalar((arc4random_uniform(26) + 65)))
}
var willLower = arc4random_uniform(2)
if willLower == 1 {
newCharacter = Character(String(newCharacter).lowercaseString)
}
newGene += newCharacter
index++
}
newGene | gpl-2.0 | 9457d31902576ca88d1e9c2cee92f6ed | 23.478261 | 78 | 0.688612 | 3.721854 | false | false | false | false |
didisouzacosta/ASAlertViewController | ASAlertViewController/Classes/ASAlertMultiselect/ASAlertMultiselectController.swift | 1 | 1187 | //
// ASAlertMultiselectController.swift
// Pods
//
// Created by Adriano Souza Costa on 19/04/17.
//
//
import Foundation
public class ASAlertMultiselectController: ASAlertSelectController {
// MARK: - Variables
public var onSelectedOptions: ((_ options: [ASAlertSelectOption]?) -> Void)?
override internal var customHandlers: [ASAlertHandler] {
let cancelHandler = ASAlertAction("Cancelar", type: .cancel, handler: {
self.dismiss()
})
let selectHandler = ASAlertAction("Selecionar", type: .default, handler: {
let options = self.selectedOptions
options.forEach { option in option.onAction?() }
self.onSelectedOptions?(options)
self.dismiss()
})
return [cancelHandler, selectHandler]
}
private var selectedOptions: [ASAlertSelectOption] = []
// MARK: - Public Functions
override internal func setupSelectedOption() {
alertSelectView.allowsMultiselection = true
alertSelectView.onSelectedOptions = { options in
self.selectedOptions = options
}
}
}
| mit | 8f7e1b29115ec1112a49ca69be9aa830 | 25.977273 | 82 | 0.615838 | 4.884774 | false | false | false | false |
a497500306/yijia_kuanjia | 医家/医家/其他/AppDelegate.swift | 1 | 14731 | //
// AppDelegate.swift
// 医家
//
// Created by 洛耳 on 15/12/10.
// Copyright © 2015年 workorz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
/// 判断是否修改了字体
var isHomeXgzt: Bool! = false
var isForumXgzt: Bool! = false
var isNewsXgzt: Bool! = false
var isTestXgzt: Bool! = false
var isXgzt: Bool! = false
//是否清除数据,用户注册到选择身份界面退出时
var isUp:NSString! = "是"
//地理位子
var locManager : CLLocationManager!
var mgr : CLLocationManager!
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//设置状态栏颜色
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
// Override point for customization after application launch.
//高德地图APPKey
// MAMapServices.sharedServices().apiKey = "64c89bfdec78b2ae4b174d3cbe5c6c4a"
//IOS8,如果想要追踪,要主动请求隐私权限
self.locManager = CLLocationManager()
locManager.startUpdatingLocation()
self.mgr = CLLocationManager()
if #available(iOS 8.0, *) {
self.mgr.requestAlwaysAuthorization()
} else {
// Fallback on earlier versions
}
//百度地图APPKey
let mapManager = BMKMapManager()
let ret = mapManager.start("wLlRKjYu9AOGQnwtfUglkdug", generalDelegate: nil)
if (!ret) {
}
//MOBSDK
//启动应用
ShareSDK.registerApp("ef49d7d88590")
//启动短信
SMSSDK.registerApp("eb9a469cc5fd", withSecret: "9f58d435401b8cdeb1f9abb29da382c0")
//极光推送
if #available(iOS 8.0, *) {
//可以添加自定义categories
JPUSHService.registerForRemoteNotificationTypes(UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Alert.rawValue, categories: nil)
} else {
// Fallback on earlier versions
//categories 必须为nil
JPUSHService.registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge.rawValue | UIRemoteNotificationType.Badge.rawValue | UIRemoteNotificationType.Alert.rawValue, categories: nil)
}
JPUSHService.setupWithOption(launchOptions, appKey: "86535e95726d0de2ea1d204d", channel: "Publish channel", apsForProduction: true)
//环信注册
//这里需要推送证书
// EaseMob.sharedInstance().registerSDKWithAppKey("13055031#yijia", apnsCertName: nil)
// EaseMobUIClient.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
// EaseMobUIClient.sharedInstance().registerForRemoteNotificationsWithApplication(application)//你也可以自己注册APNS
// EaseMobUIClient.sharedInstance().userDelegate = self //EM_ChatUserDelegate
// EaseMobUIClient.sharedInstance().oppositeDelegate = self //EM_ChatOppositeDelegate
// EaseMobUIClient.sharedInstance().notificationDelegate = self//EM_ChatNotificationDelegate
//判断是否设置自动登陆
// let isAutoLogin : Bool = EaseMob.sharedInstance().chatManager.isAutoLoginEnabled!
// if !isAutoLogin {
// EaseMob.sharedInstance().chatManager.asyncLoginWithUsername("ml", password: "123", completion: { (loginInfo, error ) -> Void in
// if error == nil {
// print("登陆成功")
// //开启自动登.想知道什么意思,进去看注释
// MLJson.fuckSetIsAutoLoginEnabled()
// }else{
// print("登陆错误\(error.errorCode)")
// }
// }, onQueue: nil)
// }
//友盟统计
MobClick.startWithAppkey("568dbbd5e0f55a94a000084b", reportPolicy: BATCH, channelId: nil)
//显示登陆
MLUserInfo.sharedMLUserInfo().loadUserInfoFromSanbox()
if MLUserInfo.sharedMLUserInfo().token == nil{
let storayobard = UIStoryboard(name: "logIn", bundle: nil)
self.window?.rootViewController = storayobard.instantiateInitialViewController()
}else{
//判断是否有密码
//计算字符串长度
let str = PCCircleViewConst.getGestureWithKey(gestureFinalSaveKey)
if str == nil {//没有密码
}else{//跳转
let gestureVc :GestureViewController = GestureViewController()
gestureVc.isNAV = true
gestureVc.type = GestureViewControllerTypeLogin
gestureVc.hidesBottomBarWhenPushed = true
let homeVc : MLNavigationContrller = self.window!.rootViewController! as! MLNavigationContrller
homeVc.pushViewController(gestureVc, animated: false)
//登陆时判断是否打开指纹解锁
MLUserInfo.sharedMLUserInfo().loadUserInfoFromSanbox()
if (MLUserInfo.sharedMLUserInfo().zwjs != nil) {//打开了指纹解锁
let verify : FingerPrintVerify = FingerPrintVerify()
verify.isNAV = true
verify.verifyFingerprint()
}
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {//将进入后台
// EaseMobUIClient.sharedInstance().applicationWillResignActive(application)
}
func applicationDidEnterBackground(application: UIApplication) {//进入后台
// EaseMobUIClient.sharedInstance().applicationDidEnterBackground(application)
//判断是否有密码
//计算字符串长度
let str = PCCircleViewConst.getGestureWithKey(gestureFinalSaveKey)
if str == nil {//没有密码
}else{//跳转
//跳转
let gestureVc :GestureViewController = GestureViewController()
gestureVc.type = GestureViewControllerTypeLogin
gestureVc.hidesBottomBarWhenPushed = true
let homeVc : MLNavigationContrller = self.window!.rootViewController! as! MLNavigationContrller
//取出NAV顶部控制器
let viewC :UIViewController = homeVc.topViewController!
//判断类型
if viewC.isKindOfClass(GestureViewController) {
NSLog("123%@",viewC)
}else{
viewC.presentViewController(gestureVc, animated: false, completion: nil)
}
}
}
func applicationWillEnterForeground(application: UIApplication) {//即将进入前台
// EaseMobUIClient.sharedInstance().applicationWillEnterForeground(application)
//登陆时判断是否打开指纹解锁
MLUserInfo.sharedMLUserInfo().loadUserInfoFromSanbox()
if (MLUserInfo.sharedMLUserInfo().zwjs != nil) {//打开了指纹解锁
let verify : FingerPrintVerify = FingerPrintVerify()
verify.verifyFingerprint()
}
}
func applicationDidBecomeActive(application: UIApplication) {//进入前台
// EaseMobUIClient.sharedInstance().applicationDidBecomeActive(application)
}
func applicationWillTerminate(application: UIApplication) {
// EaseMobUIClient.sharedInstance().applicationWillTerminate(application)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("\(completionHandler)")
}
@available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
if shortcutItem.type == "扫一扫" {
print("点击了扫一扫")
}else if shortcutItem.type == "通知中心" {
print("通知中心")
//判断是否有密码
//计算字符串长度
let Vc :MLTzzxController = MLTzzxController()
Vc.hidesBottomBarWhenPushed = true
let homeVc : MLNavigationContrller = self.window!.rootViewController! as! MLNavigationContrller
//取出NAV顶部控制器
let viewC :UIViewController = homeVc.topViewController!
//判断类型
if viewC.isKindOfClass(MLTzzxController) {
}else{
homeVc.pushViewController(Vc, animated: false)
}
//取出密码
let str = PCCircleViewConst.getGestureWithKey(gestureFinalSaveKey)
if str != nil {//有手势密码
let gestureVc :GestureViewController = GestureViewController()
gestureVc.type = GestureViewControllerTypeLogin
gestureVc.hidesBottomBarWhenPushed = true
homeVc.presentViewController(gestureVc, animated: false, completion: nil)
}
}else if shortcutItem.type == "每日量表" {
print("每日量表")
//判断是否有密码
//计算字符串长度
let Vc :MLMrlbController = MLMrlbController()
Vc.hidesBottomBarWhenPushed = true
let homeVc : MLNavigationContrller = self.window!.rootViewController! as! MLNavigationContrller
//取出NAV顶部控制器
let viewC :UIViewController = homeVc.topViewController!
//判断类型
if viewC.isKindOfClass(MLMrlbController) {
}else{
homeVc.pushViewController(Vc, animated: false)
}
//取出密码
let str = PCCircleViewConst.getGestureWithKey(gestureFinalSaveKey)
if str != nil {//有手势密码
let gestureVc :GestureViewController = GestureViewController()
gestureVc.type = GestureViewControllerTypeLogin
gestureVc.hidesBottomBarWhenPushed = true
homeVc.presentViewController(gestureVc, animated: false, completion: nil)
}
}else if shortcutItem.type == "我的医生" {
print("我的医生")
//判断是否有密码
//计算字符串长度
let Vc :MLWdysController = MLWdysController()
Vc.hidesBottomBarWhenPushed = true
let homeVc : MLNavigationContrller = self.window!.rootViewController! as! MLNavigationContrller
//取出NAV顶部控制器
let viewC :UIViewController = homeVc.topViewController!
//判断类型
if viewC.isKindOfClass(MLWdysController) {
}else{
homeVc.pushViewController(Vc, animated: false)
}
//取出密码
let str = PCCircleViewConst.getGestureWithKey(gestureFinalSaveKey)
if str != nil {//有手势密码
let gestureVc :GestureViewController = GestureViewController()
gestureVc.type = GestureViewControllerTypeLogin
gestureVc.hidesBottomBarWhenPushed = true
homeVc.presentViewController(gestureVc, animated: false, completion: nil)
}
}
}
func applicationProtectedDataWillBecomeUnavailable(application: UIApplication) {
// EaseMobUIClient.sharedInstance().applicationProtectedDataWillBecomeUnavailable(application)
}
func applicationProtectedDataDidBecomeAvailable(application: UIApplication) {
// EaseMobUIClient.sharedInstance().applicationProtectedDataDidBecomeAvailable(application)
}
func applicationDidReceiveMemoryWarning(application: UIApplication) {//APP退出
// EaseMobUIClient.sharedInstance().applicationDidReceiveMemoryWarning(application)
if self.isUp == "否" {//注册到选择身份退出时
MLUserInfo.sharedMLUserInfo().loadUserInfoFromSanbox()
MLUserInfo.sharedMLUserInfo().user = nil
MLUserInfo.sharedMLUserInfo().token = nil
MLUserInfo.sharedMLUserInfo().zwjs = nil
MLUserInfo.sharedMLUserInfo().saveUserInfoToSanbox()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// EaseMobUIClient.sharedInstance().application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
// Required获取极光token
JPUSHService.registerDeviceToken(deviceToken)
print("\(deviceToken)")
}
// 当 DeviceToken 获取失败时,系统会回调此方法
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
// EaseMobUIClient.sharedInstance().application(application, didFailToRegisterForRemoteNotificationsWithError: error)
print("推送获取失败\(error)")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
// EaseMobUIClient.sharedInstance().application(application, didReceiveRemoteNotification: userInfo)
// 处理收到的 APNs 消息
JPUSHService.handleRemoteNotification(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
JPUSHService.handleRemoteNotification(userInfo)
completionHandler(UIBackgroundFetchResult.NewData);
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// EaseMobUIClient.sharedInstance().application(application, didReceiveLocalNotification: notification)
}
//环信登陆
// func userForEMChat() -> EM_ChatUser! {
// let user = EM_ChatUser()
// user.uid = "ml"
// user.displayName = "毛哥哥是神"
// user.intro = "神就是不用吃饭可以带你飞的人"
// user.avatar = nil
// return user
// }
//ios8推送
@available(iOS 8.0, *)
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if #available(iOS 8.0, *) {
application.registerForRemoteNotifications()
} else {
// Fallback on earlier versions
}
}
}
| apache-2.0 | 849eac4ab95cd2460493b78938a3ef71 | 44.96 | 201 | 0.651799 | 5.358725 | false | false | false | false |
onebytecode/krugozor-iOSVisitors | Pods/SwiftyBeaver/Sources/SBPlatformDestination.swift | 4 | 23640 | //
// SBPlatformDestination
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger on 22.01.16.
// Copyright © 2016 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
// platform-dependent import frameworks to get device details
// valid values for os(): OSX, iOS, watchOS, tvOS, Linux
// in Swift 3 the following were added: FreeBSD, Windows, Android
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
var DEVICE_MODEL: String {
get {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
#else
let DEVICE_MODEL = ""
#endif
#if os(iOS) || os(tvOS)
var DEVICE_NAME = UIDevice.current.name
#else
// under watchOS UIDevice is not existing, http://apple.co/26ch5J1
let DEVICE_NAME = ""
#endif
public class SBPlatformDestination: BaseDestination {
public var appID = ""
public var appSecret = ""
public var encryptionKey = ""
public var analyticsUserName = "" // user email, ID, name, etc.
public var analyticsUUID: String { return uuid }
// when to send to server
public struct SendingPoints {
public var verbose = 0
public var debug = 1
public var info = 5
public var warning = 8
public var error = 10
public var threshold = 10 // send to server if points reach that value
}
public var sendingPoints = SendingPoints()
public var showNSLog = false // executes toNSLog statements to debug the class
var points = 0
public var serverURL = URL(string: "https://api.swiftybeaver.com/api/entries/") // optional
public var entriesFileURL = URL(fileURLWithPath: "") // not optional
public var sendingFileURL = URL(fileURLWithPath: "")
public var analyticsFileURL = URL(fileURLWithPath: "")
private let minAllowedThreshold = 1 // over-rules SendingPoints.Threshold
private let maxAllowedThreshold = 1000 // over-rules SendingPoints.Threshold
private var sendingInProgress = false
private var initialSending = true
// analytics
var uuid = ""
// destination
override public var defaultHashValue: Int {return 3}
let fileManager = FileManager.default
let isoDateFormatter = DateFormatter()
/// init platform with default internal filenames
public init(appID: String, appSecret: String, encryptionKey: String,
entriesFileName: String = "sbplatform_entries.json",
sendingfileName: String = "sbplatform_entries_sending.json",
analyticsFileName: String = "sbplatform_analytics.json") {
super.init()
self.appID = appID
self.appSecret = appSecret
self.encryptionKey = encryptionKey
// setup where to write the json files
var baseURL: URL?
#if os(OSX)
if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
baseURL = url
// try to use ~/Library/Application Support/APP NAME instead of ~/Library/Application Support
if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String {
do {
if let appURL = baseURL?.appendingPathComponent(appName, isDirectory: true) {
try fileManager.createDirectory(at: appURL,
withIntermediateDirectories: true, attributes: nil)
baseURL = appURL
}
} catch {
// it is too early in the class lifetime to be able to use toNSLog()
print("Warning! Could not create folder ~/Library/Application Support/\(appName).")
}
}
}
#else
#if os(tvOS)
// tvOS can just use the caches directory
if let url = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
baseURL = url
}
#elseif os(Linux)
// Linux is using /var/cache
let baseDir = "/var/cache/"
entriesFileURL = URL(fileURLWithPath: baseDir + entriesFileName)
sendingFileURL = URL(fileURLWithPath: baseDir + sendingfileName)
analyticsFileURL = URL(fileURLWithPath: baseDir + analyticsFileName)
#else
// iOS and watchOS are using the app’s document directory
if let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
baseURL = url
}
#endif
#endif
#if os(Linux)
// get, update loaded and save analytics data to file on start
let dict = analytics(analyticsFileURL, update: true)
_ = saveDictToFile(dict, url: analyticsFileURL)
#else
if let baseURL = baseURL {
// is just set for everything but not Linux
entriesFileURL = baseURL.appendingPathComponent(entriesFileName,
isDirectory: false)
sendingFileURL = baseURL.appendingPathComponent(sendingfileName,
isDirectory: false)
analyticsFileURL = baseURL.appendingPathComponent(analyticsFileName,
isDirectory: false)
// get, update loaded and save analytics data to file on start
let dict = analytics(analyticsFileURL, update: true)
_ = saveDictToFile(dict, url: analyticsFileURL)
}
#endif
}
// append to file, each line is a JSON dict
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
file: String, function: String, line: Int, context: Any? = nil) -> String? {
var jsonString: String?
let dict: [String: Any] = [
"timestamp": Date().timeIntervalSince1970,
"level": level.rawValue,
"message": msg,
"thread": thread,
"fileName": file.components(separatedBy: "/").last!,
"function": function,
"line": line]
jsonString = jsonStringFromDict(dict)
if let str = jsonString {
toNSLog("saving '\(msg)' to \(entriesFileURL)")
_ = saveToFile(str, url: entriesFileURL)
//toNSLog(entriesFileURL.path!)
// now decide if the stored log entries should be sent to the server
// add level points to current points amount and send to server if threshold is hit
let newPoints = sendingPointsForLevel(level)
points += newPoints
toNSLog("current sending points: \(points)")
if (points >= sendingPoints.threshold && points >= minAllowedThreshold) || points > maxAllowedThreshold {
toNSLog("\(points) points is >= threshold")
// above threshold, send to server
sendNow()
} else if initialSending {
initialSending = false
// first logging at this session
// send if json file still contains old log entries
if let logEntries = logsFromFile(entriesFileURL) {
let lines = logEntries.count
if lines > 1 {
var msg = "initialSending: \(points) points is below threshold "
msg += "but json file already has \(lines) lines."
toNSLog(msg)
sendNow()
}
}
}
}
return jsonString
}
// MARK: Send-to-Server Logic
/// does a (manual) sending attempt of all unsent log entries to SwiftyBeaver Platform
public func sendNow() {
if sendFileExists() {
toNSLog("reset points to 0")
points = 0
} else {
if !renameJsonToSendFile() {
return
}
}
if !sendingInProgress {
sendingInProgress = true
//let (jsonString, lines) = logsFromFile(sendingFileURL)
var lines = 0
guard let logEntries = logsFromFile(sendingFileURL) else {
sendingInProgress = false
return
}
lines = logEntries.count
if lines > 0 {
var payload = [String: Any]()
// merge device and analytics dictionaries
let deviceDetailsDict = deviceDetails()
var analyticsDict = analytics(analyticsFileURL)
for key in deviceDetailsDict.keys {
analyticsDict[key] = deviceDetailsDict[key]
}
payload["device"] = analyticsDict
payload["entries"] = logEntries
if let str = jsonStringFromDict(payload) {
//toNSLog(str) // uncomment to see full payload
toNSLog("Encrypting \(lines) log entries ...")
if let encryptedStr = encrypt(str) {
var msg = "Sending \(lines) encrypted log entries "
msg += "(\(encryptedStr.characters.count) chars) to server ..."
toNSLog(msg)
//toNSLog("Sending \(encryptedStr) ...")
sendToServerAsync(encryptedStr) { ok, _ in
self.toNSLog("Sent \(lines) encrypted log entries to server, received ok: \(ok)")
if ok {
_ = self.deleteFile(self.sendingFileURL)
}
self.sendingInProgress = false
self.points = 0
}
}
}
} else {
sendingInProgress = false
}
}
}
/// sends a string to the SwiftyBeaver Platform server, returns ok if status 200 and HTTP status
func sendToServerAsync(_ str: String?, complete: @escaping (_ ok: Bool, _ status: Int) -> Void) {
let timeout = 10.0
if let payload = str, let queue = self.queue, let serverURL = serverURL {
// create operation queue which uses current serial queue of destination
let operationQueue = OperationQueue()
operationQueue.underlyingQueue = queue
let session = URLSession(configuration:
URLSessionConfiguration.default,
delegate: nil, delegateQueue: operationQueue)
toNSLog("assembling request ...")
// assemble request
var request = URLRequest(url: serverURL,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: timeout)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// basic auth header (just works on Linux for Swift 3.1+, macOS is fine)
guard let credentials = "\(appID):\(appSecret)".data(using: String.Encoding.utf8) else {
toNSLog("Error! Could not set basic auth header")
return complete(false, 0)
}
#if os(Linux)
let base64Credentials = Base64.encode([UInt8](credentials))
#else
let base64Credentials = credentials.base64EncodedString(options: [])
#endif
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
//toNSLog("\nrequest:")
//print(request)
// POST parameters
let params = ["payload": payload]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
} catch {
toNSLog("Error! Could not create JSON for server payload.")
return complete(false, 0)
}
toNSLog("sending params: \(params)")
toNSLog("sending ...")
sendingInProgress = true
// send request async to server on destination queue
let task = session.dataTask(with: request) { _, response, error in
var ok = false
var status = 0
self.toNSLog("received response from server")
if let error = error {
// an error did occur
self.toNSLog("Error! Could not send entries to server. \(error)")
} else {
if let response = response as? HTTPURLResponse {
status = response.statusCode
if status == 200 {
// all went well, entries were uploaded to server
ok = true
} else {
// status code was not 200
var msg = "Error! Sending entries to server failed "
msg += "with status code \(status)"
self.toNSLog(msg)
}
}
}
return complete(ok, status)
}
task.resume()
session.finishTasksAndInvalidate()
//while true {} // commenting this line causes a crash on Linux unit tests?!?
}
}
/// returns sending points based on level
func sendingPointsForLevel(_ level: SwiftyBeaver.Level) -> Int {
switch level {
case SwiftyBeaver.Level.debug:
return sendingPoints.debug
case SwiftyBeaver.Level.info:
return sendingPoints.info
case SwiftyBeaver.Level.warning:
return sendingPoints.warning
case SwiftyBeaver.Level.error:
return sendingPoints.error
default:
return sendingPoints.verbose
}
}
// MARK: File Handling
/// appends a string as line to a file.
/// returns boolean about success
func saveToFile(_ str: String, url: URL, overwrite: Bool = false) -> Bool {
do {
if fileManager.fileExists(atPath: url.path) == false || overwrite {
// create file if not existing
let line = str + "\n"
try line.write(to: url, atomically: true, encoding: String.Encoding.utf8)
} else {
// append to end of file
let fileHandle = try FileHandle(forWritingTo: url)
_ = fileHandle.seekToEndOfFile()
let line = str + "\n"
if let data = line.data(using: String.Encoding.utf8) {
fileHandle.write(data)
fileHandle.closeFile()
}
}
return true
} catch {
toNSLog("Error! Could not write to file \(url).")
return false
}
}
func sendFileExists() -> Bool {
return fileManager.fileExists(atPath: sendingFileURL.path)
}
func renameJsonToSendFile() -> Bool {
do {
try fileManager.moveItem(at: entriesFileURL, to: sendingFileURL)
return true
} catch {
toNSLog("SwiftyBeaver Platform Destination could not rename json file.")
return false
}
}
/// returns optional array of log dicts from a file which has 1 json string per line
func logsFromFile(_ url: URL) -> [[String:Any]]? {
var lines = 0
do {
// try to read file, decode every JSON line and put dict from each line in array
let fileContent = try String(contentsOfFile: url.path, encoding: .utf8)
let linesArray = fileContent.components(separatedBy: "\n")
var dicts = [[String: Any]()] // array of dictionaries
for lineJSON in linesArray {
lines += 1
if lineJSON.characters.first == "{" && lineJSON.characters.last == "}" {
// try to parse json string into dict
if let data = lineJSON.data(using: .utf8) {
do {
if let dict = try JSONSerialization.jsonObject(with: data,
options: .mutableContainers) as? [String:Any] {
if !dict.isEmpty {
dicts.append(dict)
}
}
} catch {
var msg = "Error! Could not parse "
msg += "line \(lines) in file \(url)."
toNSLog(msg)
}
}
}
}
dicts.removeFirst()
return dicts
} catch {
toNSLog("Error! Could not read file \(url).")
}
return nil
}
/// returns AES-256 CBC encrypted optional string
func encrypt(_ str: String) -> String? {
return AES256CBC.encryptString(str, password: encryptionKey)
}
/// Delete file to get started again
func deleteFile(_ url: URL) -> Bool {
do {
try FileManager.default.removeItem(at: url)
return true
} catch {
toNSLog("Warning! Could not delete file \(url).")
}
return false
}
// MARK: Device & Analytics
// returns dict with device details. Amount depends on platform
func deviceDetails() -> [String: String] {
var details = [String: String]()
details["os"] = OS
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
// becomes for example 10.11.2 for El Capitan
var osVersionStr = String(osVersion.majorVersion)
osVersionStr += "." + String(osVersion.minorVersion)
osVersionStr += "." + String(osVersion.patchVersion)
details["osVersion"] = osVersionStr
details["hostName"] = ProcessInfo.processInfo.hostName
details["deviceName"] = ""
details["deviceModel"] = ""
if DEVICE_NAME != "" {
details["deviceName"] = DEVICE_NAME
}
if DEVICE_MODEL != "" {
details["deviceModel"] = DEVICE_MODEL
}
return details
}
/// returns (updated) analytics dict, optionally loaded from file.
func analytics(_ url: URL, update: Bool = false) -> [String:Any] {
var dict = [String: Any]()
let now = NSDate().timeIntervalSince1970
uuid = NSUUID().uuidString
dict["uuid"] = uuid
dict["firstStart"] = now
dict["lastStart"] = now
dict["starts"] = 1
dict["userName"] = analyticsUserName
dict["firstAppVersion"] = appVersion()
dict["appVersion"] = appVersion()
dict["firstAppBuild"] = appBuild()
dict["appBuild"] = appBuild()
if let loadedDict = dictFromFile(analyticsFileURL) {
if let val = loadedDict["firstStart"] as? Double {
dict["firstStart"] = val
}
if let val = loadedDict["lastStart"] as? Double {
if update {
dict["lastStart"] = now
} else {
dict["lastStart"] = val
}
}
if let val = loadedDict["starts"] as? Int {
if update {
dict["starts"] = val + 1
} else {
dict["starts"] = val
}
}
if let val = loadedDict["uuid"] as? String {
dict["uuid"] = val
uuid = val
}
if let val = loadedDict["userName"] as? String {
if update && !analyticsUserName.isEmpty {
dict["userName"] = analyticsUserName
} else {
if !val.isEmpty {
dict["userName"] = val
}
}
}
if let val = loadedDict["firstAppVersion"] as? String {
dict["firstAppVersion"] = val
}
if let val = loadedDict["firstAppBuild"] as? Int {
dict["firstAppBuild"] = val
}
}
return dict
}
/// Returns the current app version string (like 1.2.5) or empty string on error
func appVersion() -> String {
if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
return version
}
return ""
}
/// Returns the current app build as integer (like 563, always incrementing) or 0 on error
func appBuild() -> Int {
if let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
if let intVersion = Int(version) {
return intVersion
}
}
return 0
}
/// returns optional dict from a json encoded file
func dictFromFile(_ url: URL) -> [String:Any]? {
do {
let fileContent = try String(contentsOfFile: url.path, encoding: .utf8)
if let data = fileContent.data(using: .utf8) {
return try JSONSerialization.jsonObject(with: data,
options: .mutableContainers) as? [String:Any]
}
} catch {
toNSLog("SwiftyBeaver Platform Destination could not read file \(url)")
}
return nil
}
// turns dict into JSON and saves it to file
func saveDictToFile(_ dict: [String: Any], url: URL) -> Bool {
let jsonString = jsonStringFromDict(dict)
if let str = jsonString {
toNSLog("saving '\(str)' to \(url)")
return saveToFile(str, url: url, overwrite: true)
}
return false
}
// MARK: Debug Helpers
/// log String to toNSLog. Used to debug the class logic
func toNSLog(_ str: String) {
if showNSLog {
#if os(Linux)
print("SBPlatform: \(str)")
#else
NSLog("SBPlatform: \(str)")
#endif
}
}
/// returns the current thread name
class func threadName() -> String {
#if os(Linux)
// on 9/30/2016 not yet implemented in server-side Swift:
// > import Foundation
// > Thread.isMainThread
return ""
#else
if Thread.isMainThread {
return ""
} else {
let threadName = Thread.current.name
if let threadName = threadName, !threadName.isEmpty {
return threadName
} else {
return String(format: "%p", Thread.current)
}
}
#endif
}
}
| apache-2.0 | 92d7ac88ec8e5294f579d9d3bdc88596 | 37.062802 | 117 | 0.527563 | 5.407687 | false | false | false | false |
jkufver/NSSpainEnteranceTracker | NSSpainEnteranceTrackerTests/BeaconActivityTests.swift | 1 | 1477 | //
// BeaconActivityTests.swift
// NSSpainEnteranceTracker
//
// Created by Andreas Claesson on 17/09/14.
// Copyright (c) 2014 Jens Kufver. All rights reserved.
//
import UIKit
import XCTest
class BeaconActivityTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
func testBeaconDescription() {
var beaconActivity = BeaconActivity()
let dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss:sss"
beaconActivity.timeStamp = String(format:"%@", dateFormater.stringFromDate(NSDate()))
beaconActivity.proximityUUID = NSUUID(UUIDString: "123456")
beaconActivity.major = 2
beaconActivity.minor = 1
beaconActivity.proximity = .Immediate
beaconActivity.accuracy = 2
beaconActivity.rssi = 123456
}
}
| mit | b778ad46c532303cca261926f967300d | 29.142857 | 111 | 0.648612 | 4.71885 | false | true | false | false |
tellowkrinkle/Sword | Sources/Sword/Types/VoiceState.swift | 1 | 1281 | //
// VoiceState.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
/// Structure with user's voice state info
public struct VoiceState {
// MARK: Properties
/// The ID of the voice channel
public let channelId: ChannelID
/// Whether or not the user is server deafend
public let isDeafend: Bool
/// Whether or not the user is server muted
public let isMuted: Bool
/// Whether or not the user self deafend themselves
public let isSelfDeafend: Bool
/// Whether or not the user self muted themselves
public let isSelfMuted: Bool
/// Whether or not the bot suppressed the user
public let isSuppressed: Bool
/// The Session ID of the user and voice connection
public let sessionId: String
// MARK: Initializer
/**
Cretaes VoiceState structure
- parameter json: The json data
*/
init(_ json: [String: Any]) {
self.channelId = ChannelID(json["channel_id"] as! String)!
self.isDeafend = json["deaf"] as! Bool
self.isMuted = json["mute"] as! Bool
self.isSelfDeafend = json["self_deaf"] as! Bool
self.isSelfMuted = json["self_mute"] as! Bool
self.isSuppressed = json["suppress"] as! Bool
self.sessionId = json["session_id"] as! String
}
}
| mit | 9e9d44b54300a5b47022cefbf7082e63 | 23.615385 | 62 | 0.685938 | 4.050633 | false | false | false | false |
ypopovych/ExpressCommandLine | Sources/swift-express/main.swift | 1 | 1316 | //===--- main.swift ------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express Command Line is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------===//
commandRegistry().main(arguments: CommandLine.arguments, defaultVerb: "help") { (error) -> () in
switch error {
case .subtaskError(let message):
print("Subtask Error: \(message)")
case .someNSError(let err):
print("NSError: ", err)
case .badOptions(let message):
print("Bad options: \(message)")
case .unknownError(let err):
print("Unknown Error: \(err)")
}
}
| gpl-3.0 | 8cd7d7ec5531ad5dfc804a60b0d06ec3 | 40.125 | 96 | 0.655775 | 4.416107 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATT.swift | 1 | 3438 | //
// GATT.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 2/29/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import Foundation
@_exported import Bluetooth
/**
The Generic Attributes (GATT) define a hierarchical data structure that is exposed to connected Bluetooth Low Energy (LE) devices.
GATT profiles enable extensive innovation while still maintaining full interoperability with other Bluetooth® devices. The profile describes a use case, roles and general behaviors based on the GATT functionality. Services are collections of characteristics and relationships to other services that encapsulate the behavior of part of a device. This also includes hierarchy of services, characteristics and attributes used in the attribute server.
GATT is built on top of the Attribute Protocol (ATT) (see Bluetooth Core System Architecture for block diagram and explanations), which uses GATT data to define the way that two Bluetooth Low Energy devices send and receive standard messages. Note that GATT is not used in Bluetooth BR/EDR implementations, which use only adopted profiles.
*/
internal enum GATTUUID: UInt16 {
case primaryService = 0x2800
case secondaryService = 0x2801
case include = 0x2802
case characteristic = 0x2803
/// Initializes a GATT UUID for service type.
public init(primaryService: Bool) {
self = primaryService ? .primaryService : .secondaryService
}
/// Returns a Bluetooth UUID initialized with the `rawValue` of this GATT UUID.
public var uuid: BluetoothUUID {
return .bit16(rawValue)
}
}
// MARK: - Characteristic Property
/// GATT Characteristic Properties Bitfield valuess
@frozen
public enum GATTCharacteristicProperty: UInt8, BitMaskOption {
case broadcast = 0x01
case read = 0x02
case writeWithoutResponse = 0x04
case write = 0x08
case notify = 0x10
case indicate = 0x20
/// Characteristic supports write with signature
case signedWrite = 0x40 // BT_GATT_CHRC_PROP_AUTH
case extendedProperties = 0x80
}
// MARK: CustomStringConvertible
extension GATTCharacteristicProperty: CustomStringConvertible {
public var description: String {
switch self {
case .broadcast: return "Broadcast"
case .read: return "Read"
case .write: return "Write"
case .writeWithoutResponse: return "Write without Response"
case .notify: return "Notify"
case .indicate: return "Indicate"
case .signedWrite: return "Signed Write"
case .extendedProperties: return "Extended Properties"
}
}
}
// MARK: - Characteristic Extended Property
/// GATT Characteristic Extended Properties Bitfield values.
///
/// The Characteristic Extended Properties bit field describes additional
/// properties on how the Characteristic Value can be used, or how the characteristic
/// descriptors can be accessed.
@frozen
public enum GATTCharacteristicExtendedProperty: UInt8 {
/// If set, permits reliable writes of the Characteristic Value.
case reliableWrite = 0x01
///
case writableAuxiliaries = 0x02
}
| mit | 8834d93dceac660ab6576c4a7af49e1e | 37.177778 | 448 | 0.672875 | 5.052941 | false | false | false | false |
IvoPaunov/selfie-apocalypse | Selfie apocalypse/Selfie apocalypse/SupremeSelfieSlayersController.swift | 1 | 3099 | //
// TopSelfieSlayersController.swift
// Selfie apocalypse
//
// Created by Ivko on 2/6/16.
// Copyright © 2016 Ivo Paounov. All rights reserved.
//
import UIKit
import Parse
class SupremeSelfieSlayersController: UIViewController, UITableViewDataSource {
let transitionManager = TransitionManager()
var supremeSlayers: [PFObject]?
let supremeSlayerCellIdentifier = "SupremeSlayerCell"
@IBOutlet weak var tableViewSupremeSlayers: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.getSupremeSayers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.supremeSlayers?.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.getSupremeSlayerCell(indexPath)
return cell
}
func getSupremeSlayerCell(indexPath: NSIndexPath) -> SupremeSlayerCell{
let cell = NSBundle.mainBundle()
.loadNibNamed(self.supremeSlayerCellIdentifier,
owner: nil,
options: nil)[0] as! SupremeSlayerCell
cell.scoreLabel!.text = String((self.supremeSlayers![indexPath.row] as? Slayer)!.supremeScore)
cell.nameLabel!.text = (self.supremeSlayers![indexPath.row] as? Slayer)!.slayerName
return cell
}
required init?(coder aDecoder: NSCoder) {
self.supremeSlayers = [Slayer]()
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.supremeSlayers = [Slayer]()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
func getSupremeSayers(){
let query = PFQuery(className: String(Slayer))
query.cachePolicy = .NetworkElseCache
query.orderByDescending("supremeScore")
query.limit = 20
query.findObjectsInBackgroundWithBlock {
(result, error) -> Void in
if(error == nil){
self.supremeSlayers = result
print(result)
self.tableViewSupremeSlayers.reloadData()
}
}
}
func setupSupremeSlayersTable(){
tableViewSupremeSlayers
.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.supremeSlayerCellIdentifier)
tableViewSupremeSlayers.rowHeight = UITableViewAutomaticDimension
tableViewSupremeSlayers.estimatedRowHeight = 56
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let toViewController = segue.destinationViewController as UIViewController
self.transitionManager.toLeft = false
toViewController.transitioningDelegate = self.transitionManager
}
}
| mit | 88a1e592d8f631e61bb9acfbea816234 | 30.938144 | 112 | 0.650742 | 5.435088 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/API Bindings/Models/VerificationPageDataUpdate/VerificationPageCollectedData.swift | 1 | 3676 | //
// VerificationPageCollectedData.swift
// StripeIdentity
//
// Created by Mel Ludowise on 2/26/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
extension StripeAPI {
struct VerificationPageCollectedData: Encodable, Equatable {
private(set) var biometricConsent: Bool?
private(set) var face: VerificationPageDataFace?
private(set) var idDocumentBack: VerificationPageDataDocumentFileData?
private(set) var idDocumentFront: VerificationPageDataDocumentFileData?
private(set) var idDocumentType: DocumentType?
init(
biometricConsent: Bool? = nil,
face: VerificationPageDataFace? = nil,
idDocumentBack: VerificationPageDataDocumentFileData? = nil,
idDocumentFront: VerificationPageDataDocumentFileData? = nil,
idDocumentType: DocumentType? = nil
) {
self.biometricConsent = biometricConsent
self.face = face
self.idDocumentBack = idDocumentBack
self.idDocumentFront = idDocumentFront
self.idDocumentType = idDocumentType
}
}
}
/// All mutating functions needs to pass all values explicitly to the new object, as the default value would be nil.
extension StripeAPI.VerificationPageCollectedData {
/// Returns a new `VerificationPageCollectedData`, merging the data from this
/// one with the provided one.
func merging(
_ otherData: StripeAPI.VerificationPageCollectedData
) -> StripeAPI.VerificationPageCollectedData {
return StripeAPI.VerificationPageCollectedData(
biometricConsent: otherData.biometricConsent ?? self.biometricConsent,
face: otherData.face ?? self.face,
idDocumentBack: otherData.idDocumentBack ?? self.idDocumentBack,
idDocumentFront: otherData.idDocumentFront ?? self.idDocumentFront,
idDocumentType: otherData.idDocumentType ?? self.idDocumentType
)
}
/// Merges the data from the provided `VerificationPageCollectedData` into this one.
mutating func merge(_ otherData: StripeAPI.VerificationPageCollectedData) {
self = self.merging(otherData)
}
mutating func clearData(field: StripeAPI.VerificationPageFieldType) {
switch field {
case .biometricConsent:
self.biometricConsent = nil
case .face:
self.face = nil
case .idDocumentBack:
self.idDocumentBack = nil
case .idDocumentFront:
self.idDocumentFront = nil
case .idDocumentType:
self.idDocumentType = nil
}
}
/// Helper to determine the front document score for analytics purposes
var frontDocumentScore: TwoDecimalFloat? {
switch idDocumentType {
case .drivingLicense,
.idCard:
return idDocumentFront?.frontCardScore
case .passport:
return idDocumentFront?.passportScore
case .none:
return nil
}
}
var collectedTypes: Set<StripeAPI.VerificationPageFieldType> {
var ret = Set<StripeAPI.VerificationPageFieldType>()
if self.biometricConsent != nil {
ret.insert(.biometricConsent)
}
if self.face != nil {
ret.insert(.face)
}
if self.idDocumentBack != nil {
ret.insert(.idDocumentBack)
}
if self.idDocumentFront != nil {
ret.insert(.idDocumentFront)
}
if self.idDocumentType != nil {
ret.insert(.idDocumentType)
}
return ret
}
}
| mit | 30b020402ffa81ae987e5d9a13bb9920 | 34 | 116 | 0.648707 | 5.610687 | false | false | false | false |
wqhiOS/WeiBo | WeiBo/WeiBo/Classes/Model/Home/Status.swift | 1 | 963 | //
// Status.swift
// WeiBo
//
// Created by wuqh on 2017/6/17.
// Copyright © 2017年 吴启晗. All rights reserved.
//
import UIKit
class Status: BaseModel {
// MARK: - 属性
/// 时间
var created_at: String?
/// 来源
var source: String? {
didSet {
guard let source = source, source != "" else {
return
}
let startIndex = (source as NSString).range(of: ">").location + 1
let endIndex = (source as NSString).range(of: "<", options: .backwards).location
sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: (endIndex-startIndex)))
}
}
/// 正文
var text: String?
/// id
var mid: Int = 0
// MARK: - 对数据处理的属性
var sourceText: String?
init(dict: [String:AnyObject]) {
super.init()
setValuesForKeys(dict)
}
}
| mit | 926cdcdffc43ba6f38fab3d186f5df7b | 20.952381 | 123 | 0.530369 | 3.991342 | false | false | false | false |
ifeherva/HSTracker | HSTracker/Importers/Handlers/MetaTagImporter.swift | 1 | 2225 | //
// MetaTagImporter.swift
// HSTracker
//
// Created by Benjamin Michotte on 28/08/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Kanna
import RegexUtil
struct MetaTagImporter: HttpImporter {
var siteName: String { return "" }
var handleUrl: RegexPattern { return ".*" }
func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? {
let nodes = doc.xpath("//meta")
let deck = Deck()
guard let deckName = getMetaProperty(nodes: nodes, prop: "x-hearthstone:deck") else {
logger.error("Deck name not found")
return nil
}
logger.verbose("Got deck name \(deckName)")
deck.name = deckName
var cards: [Card] = []
if let heroId = getMetaProperty(nodes: nodes, prop: "x-hearthstone:deck:hero"),
let cardList = getMetaProperty(nodes: nodes, prop: "x-hearthstone:deck:cards")?
.components(separatedBy: ","),
let playerClass = Cards.hero(byId: heroId)?.playerClass {
logger.verbose("Got class \(playerClass)")
deck.playerClass = playerClass
cards = cardList.flatMap {
if let card = Cards.by(cardId: $0) {
card.count = 1
logger.verbose("Got card \(card)")
return card
}
return nil
}
} else if let deckString = getMetaProperty(nodes: nodes, prop: "x-hearthstone:deck:deckstring") {
logger.verbose("****** Got deck string \(deckString)")
guard let (playerClass, cardList) = DeckSerializer
.deserializeDeckString(deckString: deckString) else {
logger.error("Card list not found")
return nil
}
deck.playerClass = playerClass
cards = cardList
} else {
logger.error("Can't find a valid deck")
return nil
}
return (deck, cards)
}
private func getMetaProperty(nodes: XPathObject, prop: String) -> String? {
return nodes.filter({ $0["property"] ?? "" == prop }).first?["content"]
}
}
| mit | 9e11616a27a9f9b3fefc725c1df9066a | 30.771429 | 105 | 0.557554 | 4.576132 | false | false | false | false |
material-components/material-components-ios | components/AppBar/examples/supplemental/ChildOfTrackingScrollViewViewController.swift | 2 | 2837 | // Copyright 2019-present the Material Components for iOS 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 UIKit
import MaterialComponents.MaterialFlexibleHeader
/// A table view controller that subclasses UITableViewController.
///
/// The purpose of this view controller is to demonstrate how the flexible header view interacts
/// with view controllers whose self.view *is* the tracking scroll view. In cases like these, the
/// flexible header view often needs to be added as a subview of the tracking scroll view.
class ChildOfTrackingScrollViewViewController: UITableViewController {
init(title: String? = nil) {
super.init(nibName: nil, bundle: nil)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding unsupported")
}
var headerView: MDCFlexibleHeaderView?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let titleString = title ?? ""
cell.textLabel?.text = "\(titleString): Row \(indexPath.item)"
return cell
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
headerView?.trackingScrollDidScroll()
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
headerView?.trackingScrollDidEndDecelerating()
}
override func scrollViewWillEndDragging(
_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>
) {
headerView?.trackingScrollWillEndDragging(
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
override func scrollViewDidEndDragging(
_ scrollView: UIScrollView,
willDecelerate decelerate: Bool
) {
headerView?.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
| apache-2.0 | c3c531b366c502d40ba69a80478fa964 | 31.988372 | 97 | 0.747621 | 5.102518 | false | false | false | false |
gregheo/SwiftKittens | SwiftKittens/BlurbCellNode.swift | 1 | 2659 | //
// BlurbCellNode.swift
// SwiftKittens
//
// Created by Greg Heo on 2015-03-15.
//
//
import Foundation
import UIKit
private let kTextPadding: CGFloat = 10
private let kLinkAttributeName = "PlaceKittenNodeLinkAttributeName"
class BlurbCellNode: ASCellNode, ASTextNodeDelegate {
private let textNode = ASTextNode()
override init() {
super.init()
textNode.delegate = self
textNode.userInteractionEnabled = true
textNode.linkAttributeNames = [kLinkAttributeName]
let blurb = "kittens courtesy placekitten.com 🐱" as NSString
let string = NSMutableAttributedString(string: blurb as String)
string.addAttribute(NSFontAttributeName, value:UIFont(name: "HelveticaNeue-Light", size: 16.0)!, range:NSMakeRange(0, blurb.length))
string.addAttributes([kLinkAttributeName: NSURL(string: "http://placekitten.com/")!,
NSForegroundColorAttributeName: UIColor.grayColor(),
NSUnderlineStyleAttributeName: (NSUnderlineStyle.StyleSingle.rawValue | NSUnderlineStyle.PatternDot.rawValue)],
range: blurb.rangeOfString("placekitten.com"))
textNode.attributedString = string
addSubnode(textNode)
}
override func didLoad() {
layer.as_allowsHighlightDrawing = true
super.didLoad()
}
override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
// Called on a background thread.
// Custom nodes must call measure() on their subnodes in this method.
let measuredSize = textNode.measure(CGSize(width: constrainedSize.width - 2 * kTextPadding, height: constrainedSize.height - 2 * kTextPadding))
return CGSize(width: constrainedSize.width, height: measuredSize.height + 2 * kTextPadding)
}
override func layout() {
// Called on the main thread.
// Use the stashed size from above, instead of blocking on text sizing.
let textNodeSize = textNode.calculatedSize
textNode.frame = CGRect(x: (self.calculatedSize.width - textNodeSize.width) / 2.0, y: kTextPadding, width: textNodeSize.width, height: textNodeSize.height)
}
// MARK: - ASTextNodeDelegate
func textNode(textNode: ASTextNode!, shouldHighlightLinkAttribute attribute: String!, value: AnyObject!, atPoint point: CGPoint) -> Bool {
// opt into link highlighting -- tap and hold the link to try it! must enable highlighting on a layer, see didLoad()
return true
}
func textNode(textNode: ASTextNode!, tappedLinkAttribute attribute: String!, value: AnyObject!, atPoint point: CGPoint, textRange: NSRange) {
// The node tapped a link; open it if it's a valid URL
if let url = value as? NSURL {
UIApplication.sharedApplication().openURL(url)
}
}
}
| isc | 711a5ac4bbf235e2f010ef6d6500c3c1 | 34.891892 | 159 | 0.73381 | 4.517007 | false | false | false | false |
petester42/Moya | Source/Endpoint.swift | 2 | 3841 | import Foundation
import Alamofire
/// Used for stubbing responses.
public enum EndpointSampleResponse {
/// The network returned a response, including status code and data.
case NetworkResponse(Int, NSData)
/// The network failed to send the request, or failed to retrieve a response (eg a timeout).
case NetworkError(ErrorType)
}
/// Class for reifying a target of the Target enum unto a concrete Endpoint.
public class Endpoint<Target> {
public typealias SampleResponseClosure = () -> EndpointSampleResponse
public let URL: String
public let method: Moya.Method
public let sampleResponseClosure: SampleResponseClosure
public let parameters: [String: AnyObject]?
public let parameterEncoding: Moya.ParameterEncoding
public let httpHeaderFields: [String: String]?
/// Main initializer for Endpoint.
public init(URL: String,
sampleResponseClosure: SampleResponseClosure,
method: Moya.Method = Moya.Method.GET,
parameters: [String: AnyObject]? = nil,
parameterEncoding: Moya.ParameterEncoding = .URL,
httpHeaderFields: [String: String]? = nil) {
self.URL = URL
self.sampleResponseClosure = sampleResponseClosure
self.method = method
self.parameters = parameters
self.parameterEncoding = parameterEncoding
self.httpHeaderFields = httpHeaderFields
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added parameters.
public func endpointByAddingParameters(parameters: [String: AnyObject]) -> Endpoint<Target> {
var newParameters = self.parameters ?? [String: AnyObject]()
for (key, value) in parameters {
newParameters[key] = value
}
return Endpoint(URL: URL, sampleResponseClosure: sampleResponseClosure, method: method, parameters: newParameters, parameterEncoding: parameterEncoding, httpHeaderFields: httpHeaderFields)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added HTTP header fields.
public func endpointByAddingHTTPHeaderFields(httpHeaderFields: [String: String]) -> Endpoint<Target> {
var newHTTPHeaderFields = self.httpHeaderFields ?? [String: String]()
for (key, value) in httpHeaderFields {
newHTTPHeaderFields[key] = value
}
return Endpoint(URL: URL, sampleResponseClosure: sampleResponseClosure, method: method, parameters: parameters, parameterEncoding: parameterEncoding, httpHeaderFields: newHTTPHeaderFields)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with another parameter encoding.
public func endpointByAddingParameterEncoding(newParameterEncoding: Moya.ParameterEncoding) -> Endpoint<Target> {
return Endpoint(URL: URL, sampleResponseClosure: sampleResponseClosure, method: method, parameters: parameters, parameterEncoding: newParameterEncoding, httpHeaderFields: httpHeaderFields)
}
}
/// Extension for converting an Endpoint into an NSURLRequest.
extension Endpoint {
public var urlRequest: NSURLRequest {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = method.rawValue
request.allHTTPHeaderFields = httpHeaderFields
return parameterEncoding.toAlamofire.encode(request, parameters: parameters).0
}
}
/// Required for making Endpoint conform to Equatable.
public func ==<T>(lhs: Endpoint<T>, rhs: Endpoint<T>) -> Bool {
return lhs.urlRequest.isEqual(rhs.urlRequest)
}
/// Required for using Endpoint as a key type in a Dictionary.
extension Endpoint: Equatable, Hashable {
public var hashValue: Int {
return urlRequest.hash
}
}
| mit | e5dac5d7a67b71dd8ec5548531d73147 | 41.677778 | 196 | 0.728196 | 5.425141 | false | false | false | false |
EgeTart/MedicineDMW | DWM/HomePageController.swift | 1 | 5025 | //
// HomePageController.swift
// DWM
//
// Created by 高永效 on 15/9/20.
// Copyright © 2015年 EgeTart. All rights reserved.
//
import UIKit
class HomePageController: UIViewController {
@IBOutlet weak var homeTableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let collectionController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("collectionController")
let MeetingController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MeetingController")
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
homeTableView.dataSource = self
homeTableView.delegate = self
let tabelFootView = UIView(frame: CGRect(x: 0, y: 0, width: homeTableView.frame.width, height: 1000.0))
tabelFootView.backgroundColor = UIColor(red: 248.0 / 255.0, green: 248.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
homeTableView.tableFooterView = tabelFootView
homeTableView.registerNib(UINib(nibName: "HeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "headerView")
homeTableView.registerNib(UINib(nibName: "optionCell", bundle: nil), forCellReuseIdentifier: "optionCell")
searchBar.delegate = self
homeTableView.scrollEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
}
override func viewWillDisappear(animated: Bool) {
navigationController?.navigationBarHidden = false
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
/*
// 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.
}
*/
}
//MARK: 为tableview提供数据
extension HomePageController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var reusedID = ""
if indexPath.section == 0 {
reusedID = "meetingCell"
}
else {
reusedID = "optionCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(reusedID, forIndexPath: indexPath)
if reusedID == "optionCell" {
if indexPath.section == 2 {
(cell as! optionCell).typeImage.image = UIImage(named: "video")
(cell as! optionCell).label.text = "医药视频"
}
}
return cell
}
}
//MARK: 实现tableview的delegate方法
extension HomePageController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 97
}
return 40
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return 8
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("headerView") as! HeaderView
headerView.moreButton.addTarget(self, action: "lookForMore:", forControlEvents: UIControlEvents.TouchUpInside)
self.homeTableView.tableHeaderView = headerView
}
func lookForMore(sender: UIButton) {
self.performSegueWithIdentifier("lastest", sender: self)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
self.navigationController?.pushViewController(collectionController, animated: true)
} else if indexPath.section == 2 {
self.navigationController?.pushViewController(MeetingController, animated: true)
}
}
}
//MARK: 实现UISearchBar Delegate
extension HomePageController: UISearchBarDelegate {
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
self.performSegueWithIdentifier("search", sender: self)
searchBar.resignFirstResponder()
return false
}
}
| mit | b13bab1da7cd77faa82d3dc70b984afb | 30.544304 | 139 | 0.653491 | 5.581187 | false | false | false | false |
onmyway133/Then | Example/Tests/StateTests.swift | 1 | 1259 | //
// StateTests.swift
// Then
//
// Created by Khoa Pham on 12/29/15.
// Copyright © 2015 Fantageek. All rights reserved.
//
import Foundation
import UIKit
import XCTest
@testable import Then
class StateTests: XCTestCase {
func testPending() {
let promise = Promise<Int>()
XCTAssert(promise.result.isPending())
}
func testFulfilled() {
let promise = Promise<Int>()
promise.then { result in
var condition = false
if case let .Fulfilled(value) = result where value == 10 {
condition = true
}
XCTAssert(condition)
return nil
} as Promise<Any>
promise.fulfill(value: 10)
}
func testRejected() {
let promise = Promise<Int>()
let error = NSError(domain: "test", code: 0, userInfo: nil)
promise.then { result in
var condition = false
if case let .Rejected(reason) = result {
let e = reason as NSError
if e == error {
condition = true
}
}
XCTAssert(condition)
return nil
} as Promise<Any>
promise.reject(reason: error)
}
} | mit | b5377bb7fe7feb75ea411272f3740841 | 19.983333 | 70 | 0.527027 | 4.69403 | false | true | false | false |
ReiVerdugo/uikit-fundamentals | step6.4-bondVillains-flowLayoutTemplate/BondVillains/ViewController.swift | 2 | 1764 | //
// ViewController.swift
// BondVillains
//
// Created by Jason on 11/19/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: Properties
// Get ahold of some villains, for the table
// This is an array of Villain instances
let allVillains = Villain.allVillains
// MARK: Table View Data Source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allVillains.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("VillainCell")!
let villain = self.allVillains[indexPath.row]
// Set the name and image
cell.textLabel?.text = villain.name
cell.imageView?.image = UIImage(named: villain.imageName)
// If the cell has a detail label, we will put the evil scheme in.
if let detailTextLabel = cell.detailTextLabel {
detailTextLabel.text = "Scheme: \(villain.evilScheme)"
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("VillainDetailViewController") as! VillainDetailViewController
detailController.villain = self.allVillains[indexPath.row]
self.navigationController!.pushViewController(detailController, animated: true)
}
}
| mit | e44aa38f50a0b1796929a6fbbb43e46e | 33.588235 | 150 | 0.690476 | 5.427692 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | watchOS3/HKworkout/Error.swift | 1 | 3804 | //
// Error.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/5/16.
// Copyright © 2016 LC. All rights reserved.
//
import Foundation
struct Errors {
//MARK: - HealthStore
struct healthStore
{
static let domain:String = "healthkit.healthStore"
struct unknown
{
static let code = 100
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct avaliableData
{
static let code = 101
static let description = [NSLocalizedDescriptionKey : "Health Store Data is Not avaliable"]
}
struct permission
{
static let code = 102
static let description = [NSLocalizedDescriptionKey : "Health Store permission not granted"]
func toString()->String
{
return "permission"
}
}
}//eo
struct heartRate
{
static let domain:String = "healthkit.heartRate"
struct unknown
{
static let code = 200
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct quantity
{
static let code = 201
static let description = [NSLocalizedDescriptionKey : "un-able to create Heart rate quantity type"]
}
}//eo
struct workOut
{
static let domain:String = "healthkit.workout"
struct unknown
{
static let code = 300
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct start
{
static let code = 301
static let description = [NSLocalizedDescriptionKey : "un-able to start workout"]
}
struct end
{
static let code = 302
static let description = [NSLocalizedDescriptionKey : "un-able to end workout"]
}
}//eo
//MARK: - Monitoring
struct monitoring
{
static let domain:String = ""
struct unknown
{
static let code = 400
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct type
{
static let code = 401
static let description = [ NSLocalizedDescriptionKey: "un-able to init type"]
}
struct query
{
static let code = 402
static let description = [ NSLocalizedDescriptionKey: "un-able to query sample"]
}
}
//MARK: - WCSESSION
struct wcSession
{
static let domain:String = "watchconnectivity.wcession"
struct unknown
{
static let code = 500
static let description = [NSLocalizedDescriptionKey : "unknown"]
func toString()->String
{
return "unknown"
}
}
struct supported
{
static let code = 501
static let description = [NSLocalizedDescriptionKey : "wcsession is not supported"]
}
struct reachable
{
static let code = 502
static let description = [NSLocalizedDescriptionKey : "wcsession is not reachable"]
}
}//eo
}
| mit | 0d45fd2b593a1ede0d52350c463e3df8 | 25.971631 | 112 | 0.500131 | 5.66766 | false | false | false | false |
salesforce-ux/design-system-ios | Demo-Swift/slds-sample-app/library/views/DemoCell.swift | 1 | 2397 | // Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
import UIKit
class DemoCell: UITableViewCell {
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.loadView()
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override func layoutSubviews() {
super.layoutSubviews()
if let label = self.textLabel {
label.frame = CGRect(x: 0, y: 10, width: self.frame.width, height: 30)
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func loadView() {
self.backgroundColor = UIColor.sldsFill(.brand)
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = UIColor.sldsFill(.brand)
if let label = self.textLabel {
label.text = "Example App"
label.textAlignment = .center
label.textColor = UIColor.sldsTextColor(.colorTextInverse)
label.font = UIFont.sldsFont(.regular, with: .large)
}
let image = UIImageView(image: UIImage(named: "exampleApp"))
self.addSubview(image)
self.constrainChild(image, xAlignment: .center, yAlignment: .bottom, width: 258, height: 230)
}
}
| bsd-3-clause | 8ebab1cb87edc4d4f853c6ca11b9dfd6 | 33.764706 | 101 | 0.502538 | 5.557994 | false | false | false | false |
zhouxinv/SwiftThirdTest | SwiftTest/AppDelegate.swift | 1 | 2665 | //
// AppDelegate.swift
// SwiftTest
//
// Created by GeWei on 2016/12/19.
// Copyright © 2016年 GeWei. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
// Override point for customization after application launch.
self.window!.backgroundColor = UIColor.white
self.window!.makeKeyAndVisible()
//定义一个视图控制器
let one_vc = ViewController();
//创建导航控制器
let nvc=UINavigationController(rootViewController:one_vc);
//设置根视图
self.window!.rootViewController=nvc;
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| mit | ec0ea23bf40b46ff3976e2a1bc8c1534 | 43.40678 | 285 | 0.728626 | 5.610278 | false | false | false | false |
alblue/swift | stdlib/public/core/StringCharacterView.swift | 1 | 9795 | //===--- StringCharacterView.swift - String's Collection of Characters ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// String is-not-a Sequence or Collection, but it exposes a
// collection of characters.
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#70 : The character string view should have a custom iterator type
// to allow performance optimizations of linear traversals.
import SwiftShims
extension String: BidirectionalCollection {
/// A type that represents the number of steps between two `String.Index`
/// values, where one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
public typealias IndexDistance = Int
public typealias SubSequence = Substring
public typealias Element = Character
/// The position of the first character in a nonempty string.
///
/// In an empty string, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// In an empty string, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// The number of characters in a string.
public var count: Int {
@inline(__always) get {
return distance(from: startIndex, to: endIndex)
}
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
_precondition(i < endIndex, "String index is out of bounds")
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
let stride = _characterStride(startingAt: i)
let nextOffset = i.encodedOffset &+ stride
let nextStride = _characterStride(
startingAt: Index(encodedOffset: nextOffset))
return Index(
encodedOffset: nextOffset, characterStride: nextStride)
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
_precondition(i > startIndex, "String index is out of bounds")
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
let stride = _characterStride(endingAt: i)
let priorOffset = i.encodedOffset &- stride
return Index(encodedOffset: priorOffset, characterStride: stride)
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(*n*), where *n* is the absolute value of `n`.
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the absolute value of `n`.
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: n, limitedBy: limit)
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(*n*), where *n* is the resulting distance.
@inlinable @inline(__always)
public func distance(from start: Index, to end: Index) -> IndexDistance {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _distance(from: start, to: end)
}
/// Accesses the character at the given position.
///
/// You can use the same indices for subscripting a string and its substring.
/// For example, this code finds the first letter after the first space:
///
/// let str = "Greetings, friend! How are you?"
/// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex
/// let substr = str[firstSpace...]
/// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) {
/// print("Capital after a space: \(str[nextCapital])")
/// }
/// // Prints "Capital after a space: H"
///
/// - Parameter i: A valid index of the string. `i` must be less than the
/// string's end index.
@inlinable
public subscript(i: Index) -> Character {
@inline(__always) get {
_boundsCheck(i)
let i = _guts.scalarAlign(i)
let distance = _characterStride(startingAt: i)
if _fastPath(_guts.isFastUTF8) {
let start = i.encodedOffset
let end = start + distance
return _guts.withFastUTF8(range: start..<end) { utf8 in
return Character(unchecked: String._uncheckedFromUTF8(utf8))
}
}
return _foreignSubscript(position: i, distance: distance)
}
}
@inlinable @inline(__always)
internal func _characterStride(startingAt i: Index) -> Int {
// Fast check if it's already been measured, otherwise check resiliently
if let d = i.characterStride { return d }
if i == endIndex { return 0 }
return _guts._opaqueCharacterStride(startingAt: i.encodedOffset)
}
@inlinable @inline(__always)
internal func _characterStride(endingAt i: Index) -> Int {
if i == startIndex { return 0 }
return _guts._opaqueCharacterStride(endingAt: i.encodedOffset)
}
}
// Foreign string support
extension String {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position: Index, distance: Int) -> Character {
#if _runtime(_ObjC)
_sanityCheck(_guts.isForeign)
// Both a fast-path for single-code-unit graphemes and validation:
// ICU treats isolated surrogates as isolated graphemes
if distance == 1 {
return Character(
String(_guts.foreignErrorCorrectedScalar(startingAt: position).0))
}
let start = position.encodedOffset
let end = start + distance
let count = end - start
// TODO(String performance): Stack buffer if small enough
var cus = Array<UInt16>(repeating: 0, count: count)
cus.withUnsafeMutableBufferPointer {
_cocoaStringCopyCharacters(
from: _guts._object.cocoaObject,
range: start..<end,
into: $0.baseAddress._unsafelyUnwrappedUnchecked)
}
return cus.withUnsafeBufferPointer {
return Character(String._uncheckedFromUTF16($0))
}
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
}
| apache-2.0 | 6a9d0ff2f6a81ebe6321b8cf971304a9 | 35.685393 | 85 | 0.643185 | 4.152183 | false | false | false | false |
multinerd/Mia | Mia/Testing/Material/MaterialColor.swift | 1 | 876 | //
// MaterialColor.swift
// Alamofire
//
// Created by Michael Hedaitulla on 8/2/18.
//
import Foundation
public struct MaterialColor: Hashable {
public let name: String
public let color: UIColor
public let textColor: UIColor
public var hashValue: Int {
return name.hashValue + color.hashValue + textColor.hashValue
}
internal init(name: String, color: UIColor, textColor: UIColor) {
self.name = name
self.color = color
self.textColor = textColor
}
internal init(name: String, color: UInt, textColor: UInt) {
self.init(name: name, color: UIColor(rgba: color), textColor: UIColor(rgba: textColor))
}
}
public func ==(lhs: MaterialColor, rhs: MaterialColor) -> Bool {
return lhs.name == rhs.name &&
lhs.color == rhs.color &&
lhs.textColor == rhs.textColor
}
| mit | 48ca0a3991c8225dca1fa214e3c03f61 | 24.028571 | 95 | 0.638128 | 4.093458 | false | false | false | false |
zhangao0086/DKImageBrowserVC | DKPhotoGallery/Resource/DKPhotoGalleryResource.swift | 1 | 2599 | //
// DKPhotoGalleryResource.swift
// DKPhotoGallery
//
// Created by ZhangAo on 15/8/11.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
/// Manage all resource files and internationalization support for DKPhotoGallery.
public class DKPhotoGalleryResource {
// MARK: - Internationalization
public class func localizedStringWithKey(_ key: String, value: String? = nil) -> String {
let string = customLocalizationBlock?(key)
return string ?? NSLocalizedString(key, tableName: "DKPhotoGallery",
bundle:Bundle.photoGalleryResourceBundle(),
value: value ?? "",
comment: "")
}
@objc public static var customLocalizationBlock: ((_ title: String) -> String?)?
// MARK: - Images
public class func downloadFailedImage() -> UIImage {
return imageForResource("ImageFailed")
}
public class func closeVideoImage() -> UIImage {
return imageForResource("VideoClose")
}
public class func videoPlayImage() -> UIImage {
return imageForResource("VideoPlay")
}
public class func videoToolbarPlayImage() -> UIImage {
return imageForResource("ToolbarPlay")
}
public class func videoToolbarPauseImage() -> UIImage {
return imageForResource("ToolbarPause")
}
public class func videoPlayControlBackgroundImage() -> UIImage {
return stretchImgFromMiddle(imageForResource("VideoPlayControlBackground"))
}
public class func videoTimeSliderImage() -> UIImage {
return imageForResource("VideoTimeSlider")
}
// MARK: - Private
private class func imageForResource(_ name: String) -> UIImage {
let bundle = Bundle.photoGalleryResourceBundle()
let image = UIImage(named: name, in: bundle, compatibleWith: nil) ?? UIImage()
return image
}
private class func stretchImgFromMiddle(_ image: UIImage) -> UIImage {
let centerX = image.size.width / 2
let centerY = image.size.height / 2
return image.resizableImage(withCapInsets: UIEdgeInsets(top: centerY, left: centerX, bottom: centerY, right: centerX))
}
}
private extension Bundle {
class func photoGalleryResourceBundle() -> Bundle {
let assetPath = Bundle(for: DKPhotoGalleryResource.self).resourcePath!
return Bundle(path: (assetPath as NSString).appendingPathComponent("DKPhotoGallery.bundle"))!
}
}
| mit | 3a08b1161bcbe2600d187db287ef9b9b | 31.061728 | 126 | 0.636504 | 5.183633 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/uiKit/UIKitCatalog.playground/Pages/UIActivityIndicator.xcplaygroundpage/Contents.swift | 1 | 1508 | //: # UIActivityIndicatorView
//: Use an activity indicator to show that a task is in progress. An activity indicator appears as a “gear” that is either spinning or stopped.
//:
//: [UIActivityIndicatorView API Reference](https://developer.apple.com/reference/uikit/uiactivityindicatorview)
import UIKit
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
//containerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let number = 3
let size = CGSize(width: containerView.bounds.width / CGFloat(number),
height: containerView.bounds.width / CGFloat(number))
for i in 0..<number {
for j in 0..<number {
let frame = CGRect(x: CGFloat(i) * size.width, y: CGFloat(j) * size.height, width: size.width, height: size.height)
let indicator = UIActivityIndicatorView(frame: frame)
indicator.activityIndicatorViewStyle = .whiteLarge
indicator.color = UIColor.random
indicator.hidesWhenStopped = false
indicator.startAnimating()
if (i + j) % (number - 1) == 0 {
indicator.stopAnimating()
indicator.color = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
}
containerView.addSubview(indicator)
}
}
PlaygroundPage.current.liveView = containerView
//: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
| mit | 3c9be42ba74d4e4838bcfdaf027d1787 | 39.648649 | 143 | 0.665559 | 4.309456 | false | false | false | false |
dreamsxin/swift | stdlib/private/SwiftPrivate/IO.swift | 5 | 3430 | //===----------------------------------------------------------------------===//
//
// 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 SwiftShims
public struct _FDInputStream {
public let fd: CInt
public var isClosed: Bool = false
public var isEOF: Bool = false
internal var _buffer = [UInt8](repeating: 0, count: 256)
internal var _bufferUsed: Int = 0
public init(fd: CInt) {
self.fd = fd
}
public mutating func getline() -> String? {
if let newlineIndex =
_buffer[0..<_bufferUsed].index(of: UInt8(UnicodeScalar("\n").value)) {
let result = String._fromWellFormedCodeUnitSequence(
UTF8.self, input: _buffer[0..<newlineIndex])
_buffer.removeSubrange(0...newlineIndex)
_bufferUsed -= newlineIndex + 1
return result
}
if isEOF && _bufferUsed > 0 {
let result = String._fromWellFormedCodeUnitSequence(
UTF8.self, input: _buffer[0..<_bufferUsed])
_buffer.removeAll()
_bufferUsed = 0
return result
}
return nil
}
public mutating func read() {
let minFree = 128
var bufferFree = _buffer.count - _bufferUsed
if bufferFree < minFree {
_buffer.reserveCapacity(minFree - bufferFree)
while bufferFree < minFree {
_buffer.append(0)
bufferFree += 1
}
}
let readResult: __swift_ssize_t = _buffer.withUnsafeMutableBufferPointer {
(_buffer) in
let fd = self.fd
let addr = _buffer.baseAddress! + self._bufferUsed
let size = bufferFree
return _swift_stdlib_read(fd, addr, size)
}
if readResult == 0 {
isEOF = true
return
}
if readResult < 0 {
fatalError("read() returned error")
}
_bufferUsed += readResult
}
public mutating func close() {
if isClosed {
return
}
let result = _swift_stdlib_close(fd)
if result < 0 {
fatalError("close() returned an error")
}
isClosed = true
}
}
public struct _Stderr : OutputStream {
public init() {}
public mutating func write(_ string: String) {
for c in string.utf8 {
_swift_stdlib_putc_stderr(CInt(c))
}
}
}
public struct _FDOutputStream : OutputStream {
public let fd: CInt
public var isClosed: Bool = false
public init(fd: CInt) {
self.fd = fd
}
public mutating func write(_ string: String) {
let utf8 = string.nulTerminatedUTF8
utf8.withUnsafeBufferPointer {
(utf8) -> Void in
var writtenBytes = 0
let bufferSize = utf8.count - 1
while writtenBytes != bufferSize {
let result = _swift_stdlib_write(
self.fd, UnsafePointer(utf8.baseAddress! + Int(writtenBytes)),
bufferSize - writtenBytes)
if result < 0 {
fatalError("write() returned an error")
}
writtenBytes += result
}
}
}
public mutating func close() {
if isClosed {
return
}
let result = _swift_stdlib_close(fd)
if result < 0 {
fatalError("close() returned an error")
}
isClosed = true
}
}
| apache-2.0 | a4f02419d07a670c5e71b346c5b7ba91 | 25.384615 | 80 | 0.594461 | 4.325347 | false | false | false | false |
pointfreeco/swift-web | Web.playground/Pages/ApplicativeRouter.xcplaygroundpage/Contents.swift | 1 | 3941 | import ApplicativeRouter
import Either
import Foundation
import Prelude
/*:
First we define a `Route` enum that defines all the different pages a user can visit in our site. Here
we have defined 3 pages:
- The home page
- An "Episodes" page that lists all of the episodes available. It also takes an optional query param that
determines how the episodes should be ordered.
- An "Episode" page that shows a particular episode. An episode can be found by either looking up its
slug or its id, and an optional ref tag can be attached to the query param so that we can track how
visitors are coming to the site.
*/
enum Route {
// e.g. /
case home
// e.g. /episodes?order=asc
case episodes(order: Order?)
// e.g. /episodes/intro-to-functions?ref=twitter
case episode(param: Either<String, Int>, ref: String?)
}
/*:
The enum that determines how to order episodes.
*/
enum Order: String {
case asc
case desc
}
/*:
A small amount of boilerplate needed to use the router. Each case of the route enum needs two functions:
one for extracting associated values out of the cases, and one for putting associated values into the enum.
Fortunately Swift automatically generates one of these functions for us, for if an enum `Foo` has a case
of the form `case bar(Int)`, Swift generates a function `Foo.bar: (Int) -> Foo`, which takes the associated
value as input, and produces a value of the enum.
Maybe someday Swift will also generate the other direction of this function, i.e. given a value of the enum,
optionally extract out the associated value.
This code can also be easily generated by a tool like Sourcery.
*/
extension Route {
enum iso {
static let home = parenthesize <| PartialIso<Prelude.Unit, Route>(
apply: const(.some(.home)),
unapply: { if case .home = $0 { return unit } else { return nil } }
)
static let episodes = parenthesize <| PartialIso(
apply: Route.episodes,
unapply: {
guard case let .episodes(result) = $0 else { return nil }
return result
})
static let episode = parenthesize <| PartialIso(
apply: Route.episode,
unapply: {
guard case let .episode(result) = $0 else { return nil }
return result
})
}
}
/*:
And now we can create our router, i.e. the thing that describes how a `URLRequest` relates to a value of the
`Route` enum. The `ApplicativeRouter` library comes with lots of combinators that allow you to express
most of what you would want to match against.
*/
let router = [
Route.iso.home
<¢> get <% end,
Route.iso.episodes
<¢> get %> lit("episodes")
%> queryParam("order", opt(.rawRepresentable))
<% end,
Route.iso.episode
<¢> get %> lit("episodes") %> pathParam(.intOrString)
<%> queryParam("ref", opt(.string))
<% end
]
.reduce(.empty, <|>)
/*:
And now let's play with the router!
First we can try matching some URL's with the router and see that they produce a `Route` value:
*/
router.match(string: "/")
router.match(string: "/episodes")
router.match(string: "/episodes?order=asc")
router.match(string: "/episodes?order=xyz")
router.match(string: "/episodes/42")
router.match(string: "/episodes/intro-to-funcs")
router.match(string: "/episodes/intro-to-funcs?ref=twitter")
/*:
And we can generate urls for `Route` values that would get routed to that value. Great for type-safe URL
helpers!
*/
router.absoluteString(for: .episodes(order: nil))
router.absoluteString(for: .episodes(order: .asc))
router.absoluteString(for: .home)
router.absoluteString(for: .episode(param: .left("intro-to-funcs"), ref: nil))
router.absoluteString(for: .episode(param: .left("intro-to-funcs"), ref: "twitter"))
router.absoluteString(for: .episode(param: .right(42), ref: nil))
/*:
This is what happens if you try to match a URL that the router doesn't recognize:
*/
router.match(string: "/does-not-exist")
print("✅")
| mit | 87ff838964f733f9ad6796ba06f0eb6e | 31 | 109 | 0.697917 | 3.799228 | false | false | false | false |
MuYangZhe/Swift30Projects | Project 09 - PhotoScroll/PhotoScroll/PageViewController.swift | 1 | 2741 | //
// PageViewController.swift
// PhotoScroll
//
// Created by 牧易 on 17/7/20.
// Copyright © 2017年 MuYi. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController {
var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
var currentIndex:Int?
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
if let viewController = photoCommonViewController(currentIndex ?? 0 ){
let viewControllers = [viewController]
setViewControllers(viewControllers, direction: .forward, animated: false, completion: nil)
}
}
/*
// 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.
}
*/
func photoCommonViewController(_ index:Int) -> PhotoCommenViewController? {
if let storyboard = storyboard ,
let page = storyboard.instantiateViewController(withIdentifier: "PhotoCommenViewController") as? PhotoCommenViewController {
page.imageName = photos[index]
page.photoIndex = index
return page
}
return nil
}
}
extension PageViewController:UIPageViewControllerDataSource{
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? PhotoCommenViewController {
guard let index = viewController.photoIndex , index != 0 else {
return nil
}
return photoCommonViewController(index - 1);
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? PhotoCommenViewController {
guard let index = viewController.photoIndex , index+1 < photos.count else {
return nil
}
return photoCommonViewController(index + 1);
}
return nil
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return photos.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return currentIndex ?? 0
}
}
| mit | b0a7db9e95f18a32ba8f440c787f9976 | 28.397849 | 149 | 0.634967 | 5.84188 | false | false | false | false |
alessandracaroline/SwiftHappyFace | SmileyFace/FaceView.swift | 1 | 3797 | //
// FaceView.swift
// SmileyFace
//
// Created by Alessandra Caroline Faisst on 06/10/15.
// Copyright © 2015 Alessandra Caroline Faisst. All rights reserved.
//
import UIKit
protocol FaceViewDataSource: class {
func smilinessForFaceView(sender: FaceView) -> Double?
}
@IBDesignable
class FaceView: UIView
{
@IBInspectable
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
@IBInspectable
var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } }
@IBInspectable
var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } }
var faceCenter: CGPoint {
return convertPoint(center, fromView: superview)
}
var faceRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
weak var dataSource: FaceViewDataSource?
func scale(gesture: UIPinchGestureRecognizer) {
if gesture.state == .Changed {
scale *= gesture.scale
gesture.scale = 1 // reset to 1, then only getting difference from last time I changed my scale
}
}
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1
static let FaceRadiusToMouthHeightRatio: CGFloat = 3
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
}
private enum Eye { case Left, Right }
private func bezierPathForEye(whichEye: Eye) -> UIBezierPath
{
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticalOffset
switch whichEye {
case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right: eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
path.lineWidth = lineWidth
return path
}
private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath
{
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset)
let end = CGPoint(x: start.x + mouthWidth, y: start.y)
let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y)
let path = UIBezierPath()
path.moveToPoint(start)
path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
override func drawRect(rect: CGRect)
{
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
facePath.lineWidth = lineWidth
color.set()
facePath.stroke()
bezierPathForEye(.Left).stroke()
bezierPathForEye(.Right).stroke()
let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0
let smilePath = bezierPathForSmile(smiliness)
smilePath.stroke()
}
}
| mit | 802b6465bb11bb475c4a2c3a8b731112 | 34.811321 | 137 | 0.659905 | 4.891753 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCFittingServerViewController.swift | 2 | 10278 | //
// NCFittingServerViewController.swift
// Neocom
//
// Created by Artem Shimanski on 08.08.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import Swifter
import Darwin
import CoreData
fileprivate struct Section {
var rows: [Row] = []
var title: String = ""
}
fileprivate struct Row {
var uuid: String
var loadoutName: String?
var typeID: Int
var typeName: String
var fileName: String
}
class NCFittingServerViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
lazy var server: HttpServer = {
let server = HttpServer()
server["/dropzone.js"] = shareFile(Bundle.main.path(forResource: "dropzone", ofType: "js")!)
server["/dropzone.css"] = shareFile(Bundle.main.path(forResource: "dropzone", ofType: "css")!)
server["/main.css"] = shareFile(Bundle.main.path(forResource: "main", ofType: "css")!)
server["/main.js"] = shareFile(Bundle.main.path(forResource: "main", ofType: "js")!)
server["/loadouts"] = scopes {
html {
head {
base {
Swifter.target = "_parent"
}
meta {
charset = "utf-8"
}
link {
rel = "stylesheet"
href = "./main.css"
}
}
body {
section {
h1 {
inner = NSLocalizedString("Neocom II", comment: "")
}
table(self.loadouts) { section in
thead {
th {
colspan = "4"
inner = section.title
}
}
tbody(section.rows) { row in
tr {
let uuid = row.uuid
td {
a {
href = "/loadout/\(uuid)/dna/"
div {
classs = "imageClip"
img {
src = "/image/\(row.typeID)"
}
}
}
}
td {
width = "100%"
a {
href = "/loadout/\(uuid)/dna/"
inner = "\(row.typeName)"
}
p {
small {
inner = "\(row.loadoutName ?? "")"
}
}
}
td {
a {
href = "/loadout/\(uuid)/eft/\(row.fileName).cfg"
inner = "EFT"
}
}
td {
a {
href = "/loadout/\(uuid)/xml/\(row.fileName).xml"
inner = "XML"
}
}
}
}
}
div {
classs = "footer"
a {
href = "/loadout/all/xml/loadouts.xml"
inner = NSLocalizedString("DOWNLOAD ALL", comment: "")
}
}
}
}
}
}
server["/"] = scopes {
html {
head {
meta {
charset = "utf-8"
}
script {
src = "./dropzone.js"
}
link {
rel = "stylesheet"
href = "./dropzone.css"
}
link {
rel = "stylesheet"
href = "./main.css"
}
}
body {
iframe {
idd = "content"
src = "./loadouts"
onload = "resizeIframe(this)"
}
section {
div {
idd = "dropzone"
form {
idd = "formUpload"
action = "/upload"
classs = "dropzone needsclick"
div {
classs = "dz-message needsclick"
p {
inner = NSLocalizedString("Drop files here or click to upload loadouts.", comment: "")
}
span {
classs = "note needsclick"
inner = "(EVE-XML and EFT formats are supported)"
}
}
}
}
script {
src = "./main.js"
}
}
}
}
}
server["/image/:typeID"] = { r in
return .raw(200, "OK", nil, { w in
let data: Data? = NCDatabase.sharedDatabase?.performTaskAndWait { context -> Data? in
guard let s = r.params[":typeID"], let typeID = Int(s) else {return nil}
guard let type = NCDBInvType.invTypes(managedObjectContext: context)[typeID] else {return nil}
guard let image = type.icon?.image?.image else {return nil}
guard let data = UIImagePNGRepresentation(image) else {return nil}
return data
}
if let data = data {
try? w.write(data)
}
})
}
server["/loadout/:uuid/:format/:name"] = { r in
guard let uuid = r.params[":uuid"],
let format = r.params[":format"]
else {return .movedPermanently("/")}
switch format {
case "dna":
let dna: String? = NCStorage.sharedStorage?.performTaskAndWait { managedObjectContext -> String? in
guard let loadout: NCLoadout = managedObjectContext.fetch("Loadout", where: "uuid == %@", uuid) else {return nil}
guard let data = loadout.data?.data else {return nil}
return (NCLoadoutRepresentation.dna([(typeID: Int(loadout.typeID), data: data, name: loadout.name ?? "")]).value as? [String])?.first
}
if let dna = dna {
return .movedPermanently("https://o.smium.org/loadout/dna/\(dna)")
}
case "eft":
let eft: String? = NCStorage.sharedStorage?.performTaskAndWait { managedObjectContext -> String? in
guard let loadout: NCLoadout = managedObjectContext.fetch("Loadout", where: "uuid == %@", uuid) else {return nil}
guard let data = loadout.data?.data else {return nil}
return (NCLoadoutRepresentation.eft([(typeID: Int(loadout.typeID), data: data, name: loadout.name ?? "")]).value as? [String])?.first
}
if let eft = eft {
return .raw(200, "OK", ["Content-Type" : "application/octet-stream", "Content-Disposition" : "attachment"], { w in
try? w.write(eft.data(using: .utf8)!)
})
}
case "xml":
let xml: String? = NCStorage.sharedStorage?.performTaskAndWait { managedObjectContext -> String? in
if uuid == "all" {
guard let loadouts: [NCLoadout] = managedObjectContext.fetch("Loadout") else {return nil}
let array = loadouts.compactMap { loadout -> (typeID: Int, data: NCFittingLoadout, name: String)? in
guard let data = loadout.data?.data else {return nil}
return (typeID: Int(loadout.typeID), data: data, name: loadout.name ?? "")
}
return NCLoadoutRepresentation.xml(array).value as? String
}
else {
guard let loadout: NCLoadout = managedObjectContext.fetch("Loadout", where: "uuid == %@", uuid) else {return nil}
guard let data = loadout.data?.data else {return nil}
return NCLoadoutRepresentation.xml([(typeID: Int(loadout.typeID), data: data, name: loadout.name ?? "")]).value as? String
}
}
if let xml = xml {
return .raw(200, "OK", ["Content-Type" : "application/octet-stream", "Content-Disposition" : "attachment"], { w in
try? w.write(xml.data(using: .utf8)!)
})
}
default:
break
}
return .movedPermanently("/")
}
server.POST["/upload"] = { r in
guard let multipart = r.parseMultiPartFormData().first else {return .internalServerError}
let data = Data(bytes: multipart.body)
if let loadouts = NCLoadoutRepresentation(value: data)?.loadouts {
NCStorage.sharedStorage?.performTaskAndWait { managedObjectContext in
loadouts.forEach { i in
let loadout = NCLoadout(entity: NSEntityDescription.entity(forEntityName: "Loadout", in: managedObjectContext)!, insertInto: managedObjectContext)
loadout.data = NCLoadoutData(entity: NSEntityDescription.entity(forEntityName: "LoadoutData", in: managedObjectContext)!, insertInto: managedObjectContext)
loadout.typeID = Int32(i.typeID)
loadout.name = i.name
loadout.data?.data = i.data
loadout.uuid = UUID().uuidString
}
}
return HttpResponse.ok(.html(""))
}
return HttpResponse.ok(.html(""))
}
return server
}()
override func viewDidLoad() {
super.viewDidLoad()
textLabel.text = nil
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
do {
try server.start(80)
var urls = UIDevice.interfaceAddresses.filter{$0.family == .ipv4}.map{"http://\($0.address)/"}
if let hostName = UIDevice.hostName {
urls.insert("http://\(hostName.lowercased())/", at: 0)
}
if urls.isEmpty {
textLabel.text = NSLocalizedString("Unable to determine your IP Address", comment: "")
}
else {
textLabel.attributedText = NSLocalizedString("Open one of the following links", comment: "") + ":\n\n" + urls.joined(separator: "\n") * [NSAttributedStringKey.foregroundColor: UIColor.caption]
}
}
catch {
do {
try server.start(8080)
var urls = UIDevice.interfaceAddresses.filter{$0.family == .ipv4}.map{"http://\($0.address):8080/"}
if let hostName = UIDevice.hostName {
urls.insert("http://\(hostName.lowercased()):8080/", at: 0)
}
if urls.isEmpty {
textLabel.text = NSLocalizedString("Unable to determine your IP Address", comment: "")
}
else {
textLabel.attributedText = NSLocalizedString("Open one of the following links", comment: "") + ":\n\n" + urls.joined(separator: "\n") * [NSAttributedStringKey.foregroundColor: UIColor.caption]
}
}
catch {
textLabel.text = error.localizedDescription
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
server.stop()
}
fileprivate var loadouts: [Section] {
return NCStorage.sharedStorage?.performTaskAndWait { managedObjectContext -> [Section] in
guard let loadouts: [NCLoadout] = managedObjectContext.fetch("Loadout") else {return []}
var groups = [String: [Row]]()
NCDatabase.sharedDatabase?.performTaskAndWait { managedObjectContext in
let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext)
for loadout in loadouts {
guard let uuid = loadout.uuid else {continue}
guard let type = invTypes[Int(loadout.typeID)] else {continue}
guard let name = type.group?.groupName else {continue}
let key = name
var section = groups[key] ?? []
section.append(Row(uuid: uuid,
loadoutName: loadout.name,
typeID: Int(type.typeID),
typeName: type.typeName ?? "",
fileName: "\(type.typeName ?? "") - \(loadout.name?.isEmpty == false ? loadout.name! : type.typeName ?? "")"))
groups[key] = section
}
}
return groups.sorted(by: { $0.key < $1.key}).map {
Section(rows: $0.value.sorted {$0.typeName < $1.typeName}, title: $0.key.uppercased())
}
} ?? []
}
}
| lgpl-2.1 | 9d1eae9899bfea2eaa447fddbaeab1fc | 28.875 | 197 | 0.589666 | 3.718162 | false | false | false | false |
ngageoint/fog-machine | Demo/FogViewshed/FogViewshed/Utility/StreamReader.swift | 2 | 2985 | import Foundation
// from http://stackoverflow.com/questions/24581517/read-a-file-url-line-by-line-in-swift/24648951#24648951
class StreamReader {
let encoding : UInt
let chunkSize : Int
var fileHandle : NSFileHandle!
let buffer : NSMutableData!
let delimData : NSData!
var atEof : Bool = false
init?(path: String, delimiter: String = "\n", encoding : UInt = NSUTF8StringEncoding, chunkSize : Int = 4096) {
self.chunkSize = chunkSize
self.encoding = encoding
if let fileHandle = NSFileHandle(forReadingAtPath: path),
delimData = delimiter.dataUsingEncoding(encoding),
buffer = NSMutableData(capacity: chunkSize)
{
self.fileHandle = fileHandle
self.delimData = delimData
self.buffer = buffer
} else {
self.fileHandle = nil
self.delimData = nil
self.buffer = nil
return nil
}
}
deinit {
self.close()
}
/// Return next line, or nil on EOF.
func nextLine() -> String? {
precondition(fileHandle != nil, "Attempt to read from closed file")
if atEof {
return nil
}
// Read data chunks from file until a line delimiter is found:
var range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))
while range.location == NSNotFound {
let tmpData = fileHandle.readDataOfLength(chunkSize)
if tmpData.length == 0 {
// EOF or read error.
atEof = true
if buffer.length > 0 {
// Buffer contains last line in file (not terminated by delimiter).
let line = NSString(data: buffer, encoding: encoding)
buffer.length = 0
return line as String?
}
// No more lines.
return nil
}
buffer.appendData(tmpData)
range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))
}
// Convert complete line (excluding the delimiter) to a string:
let line = NSString(data: buffer.subdataWithRange(NSMakeRange(0, range.location)),
encoding: encoding)
// Remove line (and the delimiter) from the buffer:
buffer.replaceBytesInRange(NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0)
return line as String?
}
/// Start reading from the beginning of file.
func rewind() -> Void {
fileHandle.seekToFileOffset(0)
buffer.length = 0
atEof = false
}
/// Close the underlying file. No reading must be done after calling this method.
func close() -> Void {
fileHandle?.closeFile()
fileHandle = nil
}
} | mit | e031e7d0d50fe3971e2e58c870c72888 | 33.321839 | 115 | 0.561139 | 5.016807 | false | false | false | false |
blue42u/swift-t | stc/tests/6390-app.swift | 4 | 530 | import files;
import assert;
// Test redirection
app (file out) echo (string arg) {
"/bin/echo" arg @stdout=out;
}
app (file out) echostderr (string arg) {
"./6390-echostderr.sh" arg @stderr=out
}
main () {
string msg = "hello,world";
file tmp = echo(msg);
// echo appends newline
assertEqual(read(tmp), msg + "\n", "contents of tmp");
// Also write out to file for external checking
file f<"6390.txt"> = echo(msg);
file tmp2 = echostderr(msg);
assertEqual(read(tmp2), msg + "\n", "contents of tmp2");
}
| apache-2.0 | 15c1c17bf8600f33017eafc5ad11c0b5 | 20.2 | 58 | 0.643396 | 3.028571 | false | false | false | false |
coshkun/Localbume | Localbume/Localbume/LocationDetailsViewController.swift | 1 | 16064 | //
// LocationDetailsViewController.swift
// Localbume
//
// Created by coskun on 6.09.2017.
// Copyright © 2017 coskun. All rights reserved.
//
import UIKit
import CoreLocation
import CoreData
private let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .ShortStyle
return formatter
}()
class LocationDetailsViewController: UITableViewController {
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var addPhotoImageView: UIImageView!
@IBOutlet weak var addPhotoLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var saveBarButton: UIBarButtonItem!
@IBOutlet weak var cancelBarButton: UIBarButtonItem!
@IBOutlet weak var navBarItem: UINavigationItem!
var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var placemark: CLPlacemark?
var categoryName = "No Category"
var dbContext: NSManagedObjectContext!
var date = NSDate()
//Edit Mode
var descriptionText = ""
var locationToEdit: Location? {
didSet {
if let location = locationToEdit {
descriptionText = location.locationDescription
categoryName = location.category
date = location.date
coordinate = CLLocationCoordinate2D(latitude: location.latitude
, longitude: location.longitude)
placemark = location.placemark
}
}
}
//Photo Picker
var image: UIImage?
var observer: AnyObject!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
descriptionTextView.text = descriptionText
categoryLabel.text = categoryName
let degOfLat = abs(Int(coordinate.latitude))
let degOfLong = abs(Int(coordinate.longitude))
let minOfLat = (abs(Double(coordinate.latitude)) - Double(degOfLat)) * 60
let minOfLong = (abs(Double(coordinate.longitude)) - Double(degOfLong)) * 60
latitudeLabel.text = String(degOfLat) + "° " + String(format: "%07.4f", minOfLat) + " ' " + getSingOfLat(coordinate.latitude)
longitudeLabel.text = String(format: "%03d", degOfLong) + "° " + String(format: "%07.4f", minOfLong) + " ' " + getSingOfLong(coordinate.longitude)
if let placemark = placemark {
addressLabel.text = string(from: placemark)
} else {
addressLabel.text = "No Address Found"
}
dateLabel.text = format(date)
// Books way to disable KBD
//let aSelector = NSSelectorFromString("hideKeyboard")
let gr = UITapGestureRecognizer(target: self, action: Selector("hideKeyboard:"))
gr.cancelsTouchesInView = false
tableView.addGestureRecognizer(gr)
// isEditMode
if let location = locationToEdit {
navBarItem.title = "Edit Location"
if location.hasPhoto {
if let img = location.photoImage {
show(img)
}
}
} else {
navBarItem.title = "Tag Location"
}
// Fix for photo on change device orientation
/*
let nc = NSNotificationCenter.defaultCenter()
nc.addObserverForName("UIDeviceOrientationDidChange", object: nil, queue: NSOperationQueue.mainQueue()) { _ in
if self.isViewLoaded() {
self.tableView.reloadData()
}
}
*/
// Background tasks
listenForBackgroundNotification()
// COLORIZING:
tableView.backgroundColor = UIColor(white: 11/255.0, alpha: 1.0)
tableView.separatorColor = UIColor(white: 0.0, alpha: 1.0)
tableView.indicatorStyle = .White
descriptionTextView.textColor = UIColor.whiteColor()
descriptionTextView.backgroundColor = UIColor.blackColor()
addPhotoLabel.textColor = UIColor.whiteColor()
addPhotoLabel.highlightedTextColor = addPhotoLabel.textColor
addressLabel.textColor = UIColor(white: 1.0, alpha: 0.4)
addressLabel.highlightedTextColor = addressLabel.textColor
}
@objc func hideKeyboard(gestureRecognizer: UITapGestureRecognizer){
let point = gestureRecognizer.locationInView(tableView)
let indexPath = tableView.indexPathForRowAtPoint(point)
if indexPath != nil && indexPath!.section == 0 && indexPath!.row == 0 {
return
}
descriptionTextView.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancel_Action(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func save_Action(sender: UIBarButtonItem) {
let hudView = HudView.hud(inView: navigationController!.view, animated: true)
var location: Location
if let tmp = locationToEdit {
hudView.text = "Updated"
location = tmp
} else {
hudView.text = "Tagged"
//1
location = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: self.dbContext!) as! Location
}
location.locationDescription = descriptionTextView.text
location.category = categoryName
location.latitude = coordinate.latitude
location.longitude = coordinate.longitude
location.date = date
location.placemark = placemark
//image ops
if let img = image {
if !location.hasPhoto {
location.photoID = Location.nextPhotoID() as NSNumber
}
if let data = UIImageJPEGRepresentation(img, 0.75) {
do {
try data.writeToURL(location.photoURL, atomically: true)
} catch {
print("Error while writing file: \(location.photoURL)")
}
}
}
do {
try dbContext.save()
// DISPATCH - Delayed Execution Tactics (Functions.swift)
afterDelay(0.6, closure: {
self.dismissViewControllerAnimated(true, completion: nil)
})
//dismissViewControllerAnimated(true, completion: nil)
} catch let error as NSError {
//fatalError("Kayıt sırasında hata: \(error.localizedDescription)")
fatalCoreDateError(error)
}
}
// MARK: - Helpers
func getSingOfLat(latitude: CLLocationDegrees) -> String {
var sng = "--"
if Double(latitude) < -0.00000833 { sng = "S" }
else if Double(latitude) > 0.00000833 { sng = "N" }
else { sng = "--" }
return sng
}
func getSingOfLong(longitude: CLLocationDegrees) -> String {
var sng = "--"
if Double(longitude) < -0.00000833 { sng = "W" }
else if Double(longitude) > 0.00000833 { sng = "E" }
else { sng = "--" }
return sng
}
func string(from placemark: CLPlacemark) -> String {
// 1
var line1 = ""
//2
if let s = placemark.subThoroughfare {
line1 += s + " "
}
//3
if let s = placemark.thoroughfare {
line1 += s
}
//4
var line2 = ""
if let s = placemark.locality {
line2 += s + " \n"
}
if let s = placemark.administrativeArea {
line2 += s + " "
}
if let s = placemark.postalCode {
line2 += s + " - "
}
if let s = placemark.country {
line2 += s
}
return line1 + "\n" + line2
}
func format(date: NSDate) -> String {
return dateFormatter.stringFromDate(date)
}
/*
// My Way to Disable KBD
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//super.scrollViewWillBeginDragging(scrollView)
// Dismiss KBD
UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
}
*/
// MARK: - TableView DataSource
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
descriptionTextView.becomeFirstResponder()
} else if indexPath.section == 1 && indexPath.row == 0 {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
pickPhoto()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 88
} else if indexPath.section == 2 && indexPath.row == 2 {
addressLabel.frame.size = CGSize(width: view.bounds.size.width / 2, height: 10000)
addressLabel.sizeToFit()
addressLabel.frame.origin.x = view.bounds.size.width - addressLabel.frame.size.width - 15
return addressLabel.frame.size.height + 20
} else if indexPath.section == 1 {
// resize for image
if addPhotoImageView.hidden {
return 44
} else {
let img = addPhotoImageView.image! as UIImage
// isEditMode
if let location = locationToEdit {
if location.hasPhoto {
if let _ = location.photoImage {
return 220
}
}
}
var nH:CGFloat = 24.0
var scl:CGFloat = 1.0
let w = img.size.width
let h = img.size.height
scl = addPhotoImageView.frame.width / w
nH = h * scl
//addPhotoImageView.frame = CGRect(x: 15.0, y: 10.0, width: 550.0, height: Double(nH))
return round(nH) + 20
}
} else {
return 44
}
}
// MARK: - Colorizing TableView Cells
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor(white: 22/255.0, alpha: 1.0)
if let textLabel = cell.textLabel {
textLabel.textColor = UIColor.whiteColor()
textLabel.highlightedTextColor = textLabel.textColor
}
if let detailLabel = cell.detailTextLabel {
detailLabel.textColor = UIColor(white: 1.0, alpha: 0.4)
detailLabel.highlightedTextColor = detailLabel.textColor
}
if indexPath.row == 2 {
let addressLabel = cell.viewWithTag(100) as! UILabel
addressLabel.textColor = UIColor.whiteColor()
addressLabel.highlightedTextColor = addressLabel.textColor
}
let selectionView = UIView(frame: CGRect.zero)
selectionView.backgroundColor = UIColor(white: 1.0, alpha: 0.2)
cell.selectedBackgroundView = selectionView
}
// 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.
if segue.identifier == "CategoryPickerSegue" {
let controler = segue.destinationViewController as! CategoryPickerViewController
controler.selectedCategoryName = categoryName
}
}
// Capture the UNWIND SEGUE
@IBAction func categoryPickerDidPickedCategory(segue: UIStoryboardSegue) {
let controller = segue.sourceViewController as! CategoryPickerViewController
categoryName = controller.selectedCategoryName
categoryLabel.text = categoryName
}
// MARK: - Destructor
deinit {
// print("*** deinit \(self)")
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}
// MARK: - Photolibrary
extension LocationDetailsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func takePhotoWithCamera() {
//let imagePicker = UIImagePickerController()
let imagePicker = MyImagePickerController()
imagePicker.view.tintColor = view.tintColor
imagePicker.sourceType = .Camera
imagePicker.delegate = self
imagePicker.showsCameraControls = true
presentViewController(imagePicker, animated: true, completion: nil)
}
func choosePhotoFromLibrary() {
//let imagePicker = UIImagePickerController()
let imagePicker = MyImagePickerController()
imagePicker.view.tintColor = view.tintColor
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = true
presentViewController(imagePicker, animated: true, completion: nil)
}
func pickPhoto(){
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
showPhotoMenu()
} else {
choosePhotoFromLibrary()
}
}
func showPhotoMenu() {
let alc = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alc.addAction(cancelAction)
let takePhotoAction = UIAlertAction(title: "Take Photo", style: .Default, handler: { _ in self.takePhotoWithCamera() })
alc.addAction(takePhotoAction)
let fromLibAction = UIAlertAction(title: "Choose From Library", style: .Default, handler: { _ in self.choosePhotoFromLibrary() })
alc.addAction(fromLibAction)
presentViewController(alc, animated: true, completion: nil)
}
func show(image: UIImage) {
addPhotoImageView.image = image
addPhotoImageView.hidden = false
// addPhotoImageView.frame = CGRect(x: 15, y: 10, width: 260, height: 260)
addPhotoImageView.image = image
addPhotoLabel.hidden = true
}
// Delegates
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
image = info[UIImagePickerControllerEditedImage] as? UIImage
if let img = image {
show(img)
}
tableView.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
// Background tasks
func listenForBackgroundNotification() {
let nc = NSNotificationCenter.defaultCenter()
observer = nc.addObserverForName("UIApplicationDidEnterBackground", object: nil, queue: NSOperationQueue.mainQueue()) {
[weak self] _ in
if let strongSelf = self {
if strongSelf.presentedViewController != nil {
strongSelf.dismissViewControllerAnimated(false, completion: nil)
}
strongSelf.descriptionTextView.resignFirstResponder()
}
}
}
}
| mit | 890ba1df9add4980266c73a338220e8e | 35.412698 | 154 | 0.607423 | 5.414026 | false | false | false | false |
tutsplus/iOS-MagnetMessage | MessageMe/MessageViewController.swift | 1 | 7330 | //
// MessageViewController.swift
// MessageMe
//
// Created by Bart Jacobs on 26/11/15.
// Copyright © 2015 Magnet. All rights reserved.
//
import UIKit
import MagnetMax
import CoreLocation
class MessageViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, SignInViewControllerDelegate, RecipientsViewControllerDelegate {
let SegueSignIn = "SegueSignIn"
let SegueRecipients = "SegueRecipients"
let SegueCreateAccount = "SegueCreateAccount"
@IBOutlet weak var messageView: UIView!
@IBOutlet weak var buttonsView: UIView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var locationSwitch: UISwitch!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var recipientsTextField: UITextField!
var locationManager: CLLocationManager?
var currentLocation: CLLocation?
var recipients: [MMUser] = []
var user: MMUser? {
didSet {
updateView()
}
}
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
MMX.start()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "didReceiveMessage:", name: MMXDidReceiveMessageNotification, object: nil)
setupView()
}
// MARK: -
// MARK: Prepare for Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueSignIn {
let signInViewController = segue.destinationViewController as! SignInViewController
// Configure Sign In View Controller
signInViewController.hasAccount = true
signInViewController.delegate = self
} else if segue.identifier == SegueCreateAccount {
let signInViewController = segue.destinationViewController as! SignInViewController
// Configure Sign In View Controller
signInViewController.hasAccount = false
signInViewController.delegate = self
} else if segue.identifier == SegueRecipients {
let recipientsViewController = segue.destinationViewController as! RecipientsViewController
// Configure Recipients View Controller
recipientsViewController.delegate = self
}
}
// MARK: -
// MARK: Location Manager Delegate Methods
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager?.requestLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
// Update Current Location
currentLocation = location
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
locationSwitch.setOn(false, animated: true)
}
// MARK: -
// MARK: Text Field Delegate Methods
func textFieldDidBeginEditing(textField: UITextField) {
performSegueWithIdentifier(SegueRecipients, sender: self)
}
// MARK: -
// MARK: Sign In View Controller Delegate Methods
func controller(controller: SignInViewController, didSignInWithUser user: MMUser) {
self.user = user
}
// MARK: -
// MARK: Recipients View Controller Delegate Methods
func controller(controller: RecipientsViewController, didSelectRecipients recipients: [MMUser]) {
// Update Recipients
self.recipients = recipients
var recipientsAsStrings: [String] = []
for recipient in recipients {
recipientsAsStrings.append(recipient.userName)
}
// Update Text Field
recipientsTextField.text = recipientsAsStrings.joinWithSeparator(", ")
}
// MARK: -
// MARK: View Methods
func setupView() {
updateView()
}
func updateView() {
let signedIn = (user != nil)
buttonsView.hidden = signedIn
messageView.hidden = !signedIn
}
// MARK: -
// MARK: Actions
@IBAction func done(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func sendMessage(sender: UIButton) {
guard let messageAsString = messageTextField.text else {
showAlertWithTitle("Message Required", message: "You need to enter a message.")
return
}
guard recipients.count > 0 else {
showAlertWithTitle("Recipients Required", message: "You need to have at least one recipient.")
return
}
let toRecipients = Set(recipients)
var contents: [String : String] = ["message" : messageAsString]
if let location = currentLocation {
let coordinate = location.coordinate
contents["location"] = "\(coordinate.latitude),\(coordinate.longitude)"
}
let message = MMXMessage(toRecipients: toRecipients, messageContent: contents)
message.sendWithSuccess({ (invalidUsernames) -> Void in
self.showAlertWithTitle("Message Sent", message: "Your message was successfully sent.")
}) { (error) -> Void in
print(error)
}
}
@IBAction func locationSwitchDidChange(sender: UISwitch) {
if sender.on {
requestLocation()
}
}
// MARK: -
// MARK: Notification Handling
func didReceiveMessage(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
guard let message = userInfo[MMXMessageKey] as? MMXMessage else { return }
// Send Delivery Confirmation
message.sendDeliveryConfirmation()
print(message)
}
// MARK: -
// MARK: Helper Methods
private func showAlertWithTitle(title: String, message: String) {
// Initialize Alert Controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Configure Alert Controller
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
// Present Alert Controller
presentViewController(alertController, animated: true, completion: nil)
}
private func requestLocation() {
if locationManager == nil {
// Initialize Location Manager
let locationManager = CLLocationManager()
// Configure Location Manager
locationManager.delegate = self
// Set Location Manager
self.locationManager = locationManager
}
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
// Request Location
locationManager?.requestLocation()
} else {
// Ask User for Permission
locationManager?.requestWhenInUseAuthorization()
}
}
}
| bsd-2-clause | e9d3c06b4e88eb7f08bed69aec47bfd9 | 32.162896 | 159 | 0.626825 | 5.997545 | false | false | false | false |
lpniuniu/bookmark | bookmark/bookmark/BookAboutViewController/ThanksViewController.swift | 1 | 1444 | //
// ThanksViewController.swift
// bookmark
//
// Created by familymrfan on 17/1/20.
// Copyright © 2017年 niuniu. All rights reserved.
//
import UIKit
import SnapKit
class ThanksViewController: UIViewController {
let textView:UITextView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let path = Bundle.main.path(forResource: "tks", ofType: "txt")
let text = try! String(contentsOfFile: path!, encoding: .utf8)
textView.text = text
textView.isEditable = false
textView.font = UIFont.systemFont(ofSize: 18)
view.addSubview(textView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
textView.snp.remakeConstraints { (maker:ConstraintMaker) in
maker.edges.equalToSuperview()
}
}
/*
// 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.
}
*/
}
| mit | 988e0789bcd83dd5de1dd68ff056e845 | 26.188679 | 106 | 0.652325 | 4.868243 | false | false | false | false |
Draveness/RbSwift | Sources/Regex.swift | 1 | 7030 | //
// RegexSupport.swift
// SwiftPatch
//
// Created by draveness on 18/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
infix operator =~
/// A Regexp holds a regular expression, used to match a pattern against strings.
/// Regexps are created using the `"xyz".regex` and by `init(pattern:)` constructor.
public struct Regex {
/// Inside pattern which is immutable after initialization.
public let pattern: String
/// A regular expression converted from a pattern
public let regexp: NSRegularExpression
/// Designated intializer for `Regexp` which encapsulates a `NSRegularExpression` instance inside.
/// Converts the passed-in pattern to a `NSRegularExpression` inside.
///
/// - Parameter pattern: A string pattern
/// - Parameter literal: A bool value indicates the `NSRegularExpression` matches a literal pattern
public init(_ pattern: String, literal: Bool = false) {
self.pattern = pattern
let options: NSRegularExpression.Options = literal ? .ignoreMetacharacters : NSRegularExpression.Options(rawValue: 0)
self.regexp = try! NSRegularExpression(pattern: pattern, options: options)
}
/// Invokes its `NSRegularExpression#firstMatch(in:options:range:)` method first to check it str is matched with
/// current `regexp`. Returns `nil` if `NSRegularExpression#firstMatch(in:options:range:)` returns false, or this
/// methods will encapsulates all the data inside a `MatchData` struct.
///
/// "[a-e]+".regex.match("hello") { data in
/// print(data.match) #=> "e"
/// }
///
/// "[a-e]+".regex.match("hello") { data in
/// print(data.match) #=> "e"
/// }
///
/// If the second parameter is present, it specifies the position in the string to begin the search.
///
/// "[a-e]+".regex.match("hello", 1) { data in
/// print(data.match) #=> "e"
/// print(data.range) #=> NSRange< loc: 1, length: 1 }>
/// }
///
/// - Parameters:
/// - str: A string
/// - pos: The position in the string to begin the search
/// - closure: A closure invoked if there is a match
/// - Returns: A `MatchData` instance contains all match results in it
@discardableResult
public func match(_ str: String, _ pos: Int = 0, closure: ((MatchData) -> Void)? = nil) -> MatchData? {
// let str = str.bridge
guard let result = regexp.firstMatch(in: str, options: [], range: NSMakeRange(pos, str.length - pos)) else { return nil }
let match = str.bridge.substring(with: result.range)
var captures: [String] = []
var ranges: [NSRange] = []
for index in 1..<result.numberOfRanges {
let range = result.rangeAt(index)
ranges.append(range)
captures.append(str.bridge.substring(with: range))
}
let matchData = MatchData(match: match, range: result.range, captures: captures, ranges: ranges)
if let closure = closure { closure(matchData) }
return matchData
}
/// Invokes its `NSRegularExpression#matches(in:options:range:)` method to check it str is matched with
/// current `regexp`. Returns `[]` if returns false, or this methods will encapsulates all
/// the data inside a `MatchData` struct, and returns `[MatchData]`
///
/// "[aeiou]+".regex.scan("hello") { data in
/// print(data.match) #=> e, o
/// }
///
/// - Parameters:
/// - pattern: A string
/// - closure: A closure invoked if there is a match
/// - Returns: An array of `MatchData` instance contains all match results in it
@discardableResult
public func scan(_ str: String, closure: ((MatchData) -> Void)? = nil) -> [MatchData] {
let matches = regexp.matches(in: str, options: [], range: NSMakeRange(0, str.length))
var matchDatas: [MatchData] = []
for match in matches {
let substr = str.bridge.substring(with: match.range)
var datas: [String] = []
var ranges: [NSRange] = []
autoreleasepool {
for index in 1..<match.numberOfRanges {
let range = match.rangeAt(index)
ranges.append(range)
datas.append(str.bridge.substring(with: range))
}
}
let matchData = MatchData(match: substr, range: match.range, captures: datas, ranges: ranges)
if let closure = closure { closure(matchData) }
matchDatas.append(matchData)
}
return matchDatas
}
/// Invokes `NSRegularExpression#stringByReplacingMatches(in:options:range:withTemplate:)` method to replace original match
/// result with template, $1, $2... are used to capture the match group in the str.
///
/// let str = "hello"
/// "l".regex.replace(str, "abc") #=> "heabcabco"
/// "le".regex.replace(str, "lll") #=> "hello"
/// ".".literal.replace(str, "lll") #=> "hello"
/// ".".regex.replace(str, "lll") #=> "lllllllllllllll"
/// "^he".regex.replace(str, "lll") #=> "lllllo"
///
/// "\\b(?<!['’`])[a-z]".regex.replace("my name is draven", "a") #=> "ay aame as araven"
///
/// - Parameters:
/// - str: A string waiting for replacing
/// - template: A template string used to replace original str
/// - Returns: A new string with all matching result replaced by template
public func replace(_ str: String, _ template: String) -> String {
return regexp.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.length), withTemplate: template)
}
/// Returns true if string is match with `Regex`
///
/// let regex = "hello".regex
/// if regex =~ "hello world" {
/// print("this will match")
/// }
///
/// if regex =~ "world" {
/// print("this won't match")
/// }
///
/// - Parameters:
/// - regex: A Regex struct used to match the string
/// - str: A string waiting to match
/// - Returns: A bool value indicates whether the str is matched with the Regexp
public static func =~(regex: Regex, str: String) -> Bool {
return regex.match(str) != nil
}
/// Returns true if string is match with `Regex`
///
/// let regex = "hello".regex
/// if "hello world" =~ regex {
/// print("this will match")
/// }
///
/// if "world" =~ regex {
/// print("this won't match")
/// }
///
/// - Parameters:
/// - str: A string waiting to match
/// - regex: A Regex struct used to match the string
/// - Returns: A bool value indicates whether the str is matched with the Regexp
public static func =~(str: String, regex: Regex) -> Bool {
return regex =~ str
}
}
| mit | 6be8ab9e62a3f52511b23baa0e0e48dd | 41.077844 | 129 | 0.581471 | 4.138398 | false | false | false | false |
ahoppen/swift | test/SourceKit/CursorInfo/closure_capture.swift | 1 | 3356 | func takeClosure(_ closure: () -> Void) {}
func simple(bar: Int) {
takeClosure { [bar] in
print(bar)
}
}
// RUN: %sourcekitd-test -req=cursor -pos=3:13 %s -- %s | %FileCheck %s --check-prefix=SIMPLE_PARAM
// SIMPLE_PARAM: source.lang.swift.decl.var.parameter (3:13-3:16)
// SIMPLE_PARAM: SECONDARY SYMBOLS BEGIN
// There should be no secondary symbols
// SIMPLE_PARAM-NEXT: SECONDARY SYMBOLS END
// RUN: %sourcekitd-test -req=cursor -pos=4:18 %s -- %s | %FileCheck %s --check-prefix=SIMPLE_CAPTURE
// SIMPLE_CAPTURE: source.lang.swift.decl.var.local (4:18-4:21)
// SIMPLE_CAPTURE: SECONDARY SYMBOLS BEGIN
// SIMPLE_CAPTURE: source.lang.swift.ref.var.local (3:13-3:16)
// RUN: %sourcekitd-test -req=cursor -pos=5:11 %s -- %s | %FileCheck %s --check-prefix=SIMPLE_REF
// SIMPLE_REF: source.lang.swift.ref.var.local (4:18-4:21)
// SIMPLE_REF: SECONDARY SYMBOLS BEGIN
// SIMPLE_REF: source.lang.swift.ref.var.local (3:13-3:16)
func doubleNested(bar: Int) {
takeClosure { [bar] in
takeClosure { [bar] in
print(bar)
}
}
}
// RUN: %sourcekitd-test -req=cursor -pos=26:18 %s -- %s | %FileCheck %s --check-prefix=DOUBLE_NESTED_FIRST_CAPTURE
// DOUBLE_NESTED_FIRST_CAPTURE: source.lang.swift.decl.var.local (26:18-26:21)
// DOUBLE_NESTED_FIRST_CAPTURE: SECONDARY SYMBOLS BEGIN
// DOUBLE_NESTED_FIRST_CAPTURE: source.lang.swift.ref.var.local (25:19-25:22)
// RUN: %sourcekitd-test -req=cursor -pos=27:20 %s -- %s | %FileCheck %s --check-prefix=DOUBLE_NESTED_SECOND_CAPTURE
// DOUBLE_NESTED_SECOND_CAPTURE: source.lang.swift.decl.var.local (27:20-27:23)
// DOUBLE_NESTED_SECOND_CAPTURE: SECONDARY SYMBOLS BEGIN
// DOUBLE_NESTED_SECOND_CAPTURE: source.lang.swift.ref.var.local (26:18-26:21)
// DOUBLE_NESTED_SECOND_CAPTURE: source.lang.swift.ref.var.local (25:19-25:22)
// RUN: %sourcekitd-test -req=cursor -pos=28:13 %s -- %s | %FileCheck %s --check-prefix=DOUBLE_NESTED_REF
// DOUBLE_NESTED_REF: source.lang.swift.ref.var.local (27:20-27:23)
// DOUBLE_NESTED_REF: SECONDARY SYMBOLS BEGIN
// DOUBLE_NESTED_REF: source.lang.swift.ref.var.local (26:18-26:21)
// DOUBLE_NESTED_REF: source.lang.swift.ref.var.local (25:19-25:22)
// Make sure we don't report secondary symbols if the variable is captured explicitly using '='
func explicitCapture(bar: Int) {
takeClosure { [bar = bar] in
print(bar)
}
}
// RUN: %sourcekitd-test -req=cursor -pos=53:11 %s -- %s | %FileCheck %s --check-prefix=EXPLICIT_CAPTURE_REF
// EXPLICIT_CAPTURE_REF: source.lang.swift.ref.var.local (52:18-52:21)
// EXPLICIT_CAPTURE_REF: SECONDARY SYMBOLS BEGIN
// There should be no secondary symbols
// EXPLICIT_CAPTURE_REF-NEXT: SECONDARY SYMBOLS END
func multipleCaptures(bar: Int, baz: Int) {
takeClosure { [bar, baz] in
print(bar)
print(baz)
}
}
// RUN: %sourcekitd-test -req=cursor -pos=65:11 %s -- %s | %FileCheck %s --check-prefix=MULTIPLE_CAPTURES_BAR
// MULTIPLE_CAPTURES_BAR: source.lang.swift.ref.var.local (64:18-64:21)
// MULTIPLE_CAPTURES_BAR: SECONDARY SYMBOLS BEGIN
// MULTIPLE_CAPTURES_BAR.lang.swift.ref.var.local (63:23-63:26)
// RUN: %sourcekitd-test -req=cursor -pos=66:11 %s -- %s | %FileCheck %s --check-prefix=MULTIPLE_CAPTURES_BAZ
// MULTIPLE_CAPTURES_BAZ: source.lang.swift.ref.var.local (64:23-64:26)
// MULTIPLE_CAPTURES_BAZ: SECONDARY SYMBOLS BEGIN
// MULTIPLE_CAPTURES_BAZ.lang.swift.ref.var.local (63:33-63:36)
| apache-2.0 | fb743e62219d0da0db49a84c29119a33 | 42.025641 | 116 | 0.7059 | 2.931004 | false | true | false | false |
fhchina/EasyIOS-Swift | Pod/Classes/Extend/EUI/EUI+ImageProperty.swift | 4 | 1083 | //
// EUI+ImageProperty.swift
// medical
//
// Created by zhuchao on 15/5/1.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Foundation
class ImageProperty:ViewProperty{
var src = ""
override func view() -> UIImageView{
var view = UIImageView()
view.tagProperty = self
if !isEmpty(self.src) {
if self.src.hasPrefix("http") {
view.kf_setImageWithURL(NSURL(string: self.src)!)
}else{
view.image = UIImage(named: self.src)
}
}
self.renderViewStyle(view)
for subTag in self.subTags {
view.addSubview(subTag.getView())
}
return view
}
override func renderTag(pelement:OGElement){
self.tagOut += ["src"]
super.renderTag(pelement)
if let src = EUIParse.string(pelement,key:"src"),let filterHtml = self.bindTheKeyPath(src, key: "src") {
self.src = filterHtml
}
}
override func childLoop(pelement: OGElement) {
}
}
| mit | 49af5db46280a8fcf584ec1321f1052c | 23.568182 | 112 | 0.555042 | 4.06391 | false | false | false | false |
kstaring/swift | test/SourceKit/Indexing/index.swift | 7 | 2825 | // RUN: %sourcekitd-test -req=index %s -- -serialize-diagnostics-path %t.dia %s | %sed_clean > %t.response
// RUN: diff -u %s.response %t.response
var globV: Int
class CC {
init() {}
var instV: CC
func meth() {}
func instanceFunc0(_ a: Int, b: Float) -> Int {
return 0
}
func instanceFunc1(a x: Int, b y: Float) -> Int {
return 0
}
class func smeth() {}
}
func +(a : CC, b: CC) -> CC {
return a
}
struct S {
func meth() {}
static func smeth() {}
}
enum E {
case EElem
}
protocol Prot {
func protMeth(_ a: Prot)
}
func foo(_ a: CC, b: inout E) {
globV = 0
a + a.instV
a.meth()
CC.smeth()
b = E.EElem
var local: CC
class LocalCC {}
var local2: LocalCC
}
typealias CCAlias = CC
extension CC : Prot {
func meth2(_ x: CCAlias) {}
func protMeth(_ a: Prot) {}
var extV : Int { return 0 }
}
class SubCC : CC, Prot {}
var globV2: SubCC
class ComputedProperty {
var value : Int {
get {
var result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
var readOnly : Int { return 0 }
}
class BC2 {
func protMeth(_ a: Prot) {}
}
class SubC2 : BC2, Prot {
override func protMeth(_ a: Prot) {}
}
class CC2 {
subscript (i : Int) -> Int {
get {
return i
}
set(v) {
v+1
}
}
}
func test1(_ cp: ComputedProperty, sub: CC2) {
var x = cp.value
x = cp.readOnly
cp.value = x
++cp.value
x = sub[0]
sub[0] = x
++sub[0]
}
struct S2 {
func sfoo() {}
}
var globReadOnly : S2 {
get {
return S2();
}
}
func test2() {
globReadOnly.sfoo()
}
class B1 {
func foo() {}
}
class SB1 : B1 {
override func foo() {
foo()
self.foo()
super.foo()
}
}
func test3(_ c: SB1, s: S2) {
test2()
c.foo()
s.sfoo()
}
// Test candidates.
struct S3 {
func test() {} // no.
}
protocol P2 {
func test() // no.
}
class CC3 {
func meth() {} // no.
class func test1() {} // no.
func test2() {} // yes.
}
extension CC3 {
func test3() {} // yes.
}
extension Undeclared {
func meth() {}
}
class CC4 {
convenience init(x: Int) {
self.init(x:0)
}
}
class SubCC4 : CC4 {
init(x: Int) {
super.init(x:0)
}
}
class Observing {
init() {}
var globObserving : Int {
willSet {
test2()
}
didSet {
test2()
}
}
}
// <rdar://problem/18640140> :: Crash in swift::Mangle::Mangler::mangleIdentifier()
class rdar18640140 {
// didSet is not compatible with set/get
var S1: Int {
get {
return 1
}
set {
}
didSet {
}
}
}
protocol rdar18640140Protocol {
var S1: Int {
get
set
get
}
}
@available(*, unavailable)
class AlwaysUnavailableClass {
}
@available(iOS 99.99, *)
class ConditionalUnavailableClass1{
}
@available(OSX 99.99, *)
class ConditionalUnavailableClass2{
}
| apache-2.0 | ccccc313636eb6e50a9de7a536c71b15 | 12.516746 | 106 | 0.55823 | 2.879715 | false | true | false | false |
lfaoro/Cast | Cast/ShortenClient.swift | 1 | 3375 | import Cocoa
import RxSwift
import RxCocoa
import SwiftyJSON
public class ShortenClient {
var shortenURL: NSURL?
var responseKey: String?
// MARK: - Public
public func shorten(URL URL: NSURL) -> Observable<String?> {
guard let shortenURLPref = app.prefs.shortenService else {
return failWith(ConnectionError.InvalidData("shortenURLPref"))
}
keepRecent(URL: URL)
switch shortenURLPref {
case "Is.Gd":
shortenURL = NSURL(string: "https://is.gd/create.php?format=json&url=" +
URL.absoluteString)!
responseKey = "shorturl"
case "Hive.am":
shortenURL = NSURL(string: "https://hive.am/api?api=spublic&url=\(URL.absoluteString)" +
"&description=cast.lfaoro.com&type=DIRECT")!
responseKey = "short"
case "Bit.ly":
let bitlyAPIurl = "https://api-ssl.bitly.com"
let bitlyAPIshorten = bitlyAPIurl + "/v3/shorten?access_token=" + bitlyOAuth2Token +
"&longUrl=" + URL.relativeString!
shortenURL = NSURL(string: bitlyAPIshorten)!
case "Su.Pr":
shortenURL = NSURL(string: "http://su.pr/api/shorten?longUrl=\(URL.absoluteString)")!
responseKey = "shortUrl"
default: shortenURL = nil
}
let session = NSURLSession.sharedSession()
return session.rx_JSON(shortenURL!)
.debug("Shortening with: \(shortenURLPref)")
.retry(3)
.map {
if shortenURLPref != "Bitly" {
return $0[self.responseKey!] as? String
} else {
guard let data = $0["data"] as? NSDictionary, url = data["url"] as? String else {
return nil }
return url
}
}
}
@available(*, deprecated=1.2, renamed="shorten")
public class func shortenWithIsGd(URL URL: NSURL) -> Observable<String?> {
let session = NSURLSession.sharedSession()
let shorten = NSURL(string: "https://is.gd/create.php?format=json&url=" + URL.absoluteString)!
keepRecent(URL: URL)
return session.rx_JSON(shorten)
.debug("shorten")
.retry(3)
.map { $0["shorturl"] as? String }
}
@available(*, deprecated=1.2, renamed="shorten")
public class func shortenWithHive(URL URL: NSURL) -> Observable<String?> {
let hiveAPIURL = "https://hive.am/api?api=spublic&url=\(URL.absoluteString)" +
"&description=cast.lfaoro.com&type=DIRECT"
let session = NSURLSession.sharedSession()
let shorten = NSURL(string: hiveAPIURL)!
return session.rx_JSON(shorten)
.retry(3)
.map { $0["short"] as? String }
}
@available(*, deprecated=1.2, renamed="shorten")
public class func shortenWithBitly(URL: NSURL) -> Observable<NSURL> {
let bitlyAPIurl = "https://api-ssl.bitly.com"
let bitlyAPIshorten = bitlyAPIurl + "/v3/shorten?access_token=" + bitlyOAuth2Token +
"&longUrl=" + URL.relativeString!
let url = NSURL(string: bitlyAPIshorten)!
return create { stream in
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url) { (data, response, error) in
if let data = data {
let jsonData = JSON(data: data)
let statusCode = jsonData["status_code"].int
if statusCode == 200 {
if let shortenedURL = jsonData["data"]["url"].URL {
sendNext(stream, shortenedURL)
sendCompleted(stream)
}
} else {
sendError(stream, ConnectionError.StatusCode(jsonData["status_code"].int!))
}
} else {
sendError(stream, ConnectionError.NoResponse((error!.localizedDescription)))
}
}.resume()
return NopDisposable.instance
}
}
}
| mit | 0a80644fe2e5eaf60c9aa15155241a51 | 26.892562 | 96 | 0.677037 | 3.395372 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | Sources/Disposable.swift | 1 | 9961 | //
// Disposable.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents something that can be “disposed”, usually associated with freeing
/// resources or canceling work.
public protocol Disposable: AnyObject {
/// Whether this disposable has been disposed already.
var isDisposed: Bool { get }
/// Disposing of the resources represented by `self`. If `self` has already
/// been disposed of, it does nothing.
///
/// - note: Implementations must issue a memory barrier.
func dispose()
}
/// Represents the state of a disposable.
private enum DisposableState: Int32 {
/// The disposable is active.
case active
/// The disposable has been disposed.
case disposed
}
extension UnsafeAtomicState where State == DisposableState {
/// Try to transition from `active` to `disposed`.
///
/// - returns: `true` if the transition succeeds. `false` otherwise.
@inline(__always)
fileprivate func tryDispose() -> Bool {
return tryTransition(from: .active, to: .disposed)
}
}
/// A disposable that does not have side effect upon disposal.
internal final class _SimpleDisposable: Disposable {
private let state = UnsafeAtomicState<DisposableState>(.active)
var isDisposed: Bool {
return state.is(.disposed)
}
func dispose() {
_ = state.tryDispose()
}
deinit {
state.deinitialize()
}
}
/// A disposable that has already been disposed.
internal final class NopDisposable: Disposable {
static let shared = NopDisposable()
var isDisposed = true
func dispose() {}
private init() {}
}
/// A type-erased disposable that forwards operations to an underlying disposable.
public final class AnyDisposable: Disposable {
private final class ActionDisposable: Disposable {
let state: UnsafeAtomicState<DisposableState>
var action: (() -> Void)?
var isDisposed: Bool {
return state.is(.disposed)
}
init(_ action: (() -> Void)?) {
self.state = UnsafeAtomicState(.active)
self.action = action
}
deinit {
state.deinitialize()
}
func dispose() {
if state.tryDispose() {
action?()
action = nil
}
}
}
private let base: Disposable
public var isDisposed: Bool {
return base.isDisposed
}
/// Create a disposable which runs the given action upon disposal.
///
/// - parameters:
/// - action: A closure to run when calling `dispose()`.
public init(_ action: @escaping () -> Void) {
base = ActionDisposable(action)
}
/// Create a disposable.
public init() {
base = _SimpleDisposable()
}
/// Create a disposable which wraps the given disposable.
///
/// - parameters:
/// - disposable: The disposable to be wrapped.
public init(_ disposable: Disposable) {
base = disposable
}
public func dispose() {
base.dispose()
}
}
/// A disposable that will dispose of any number of other disposables.
public final class CompositeDisposable: Disposable {
private let disposables: Atomic<Bag<Disposable>?>
private var state: UnsafeAtomicState<DisposableState>
public var isDisposed: Bool {
return state.is(.disposed)
}
/// Initialize a `CompositeDisposable` containing the given sequence of
/// disposables.
///
/// - parameters:
/// - disposables: A collection of objects conforming to the `Disposable`
/// protocol
public init<S: Sequence>(_ disposables: S) where S.Iterator.Element == Disposable {
let bag = Bag(disposables)
self.disposables = Atomic(bag)
self.state = UnsafeAtomicState(.active)
}
/// Initialize a `CompositeDisposable` containing the given sequence of
/// disposables.
///
/// - parameters:
/// - disposables: A collection of objects conforming to the `Disposable`
/// protocol
public convenience init<S: Sequence>(_ disposables: S)
where S.Iterator.Element == Disposable?
{
self.init(disposables.compactMap { $0 })
}
/// Initializes an empty `CompositeDisposable`.
public convenience init() {
self.init([Disposable]())
}
public func dispose() {
if state.tryDispose(), let disposables = disposables.swap(nil) {
for disposable in disposables {
disposable.dispose()
}
}
}
/// Add the given disposable to the composite.
///
/// - parameters:
/// - disposable: A disposable.
///
/// - returns: A disposable to remove `disposable` from the composite. `nil` if the
/// composite has been disposed of, `disposable` has been disposed of, or
/// `disposable` is `nil`.
@discardableResult
public func add(_ disposable: Disposable?) -> Disposable? {
guard let d = disposable, !d.isDisposed, !isDisposed else {
disposable?.dispose()
return nil
}
return disposables.modify { disposables in
guard let token = disposables?.insert(d) else { return nil }
return AnyDisposable { [weak self] in
self?.disposables.modify {
$0?.remove(using: token)
}
}
}
}
/// Add the given action to the composite.
///
/// - parameters:
/// - action: A closure to be invoked when the composite is disposed of.
///
/// - returns: A disposable to remove `disposable` from the composite. `nil` if the
/// composite has been disposed of, `disposable` has been disposed of, or
/// `disposable` is `nil`.
@discardableResult
public func add(_ action: @escaping () -> Void) -> Disposable? {
return add(AnyDisposable(action))
}
deinit {
state.deinitialize()
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// ````
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(observer)
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Disposable to add.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: CompositeDisposable, rhs: Disposable?) -> Disposable? {
return lhs.add(rhs)
}
/// Adds the right-hand-side `ActionDisposable` to the left-hand-side
/// `CompositeDisposable`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Closure to add as a disposable.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: CompositeDisposable, rhs: @escaping () -> Void) -> Disposable? {
return lhs.add(rhs)
}
}
/// A disposable that, upon deinitialization, will automatically dispose of
/// its inner disposable.
public final class ScopedDisposable<Inner: Disposable>: Disposable {
/// The disposable which will be disposed when the ScopedDisposable
/// deinitializes.
public let inner: Inner
public var isDisposed: Bool {
return inner.isDisposed
}
/// Initialize the receiver to dispose of the argument upon
/// deinitialization.
///
/// - parameters:
/// - disposable: A disposable to dispose of when deinitializing.
public init(_ disposable: Inner) {
inner = disposable
}
deinit {
dispose()
}
public func dispose() {
return inner.dispose()
}
}
extension ScopedDisposable where Inner == AnyDisposable {
/// Initialize the receiver to dispose of the argument upon
/// deinitialization.
///
/// - parameters:
/// - disposable: A disposable to dispose of when deinitializing, which
/// will be wrapped in an `AnyDisposable`.
public convenience init(_ disposable: Disposable) {
self.init(Inner(disposable))
}
}
extension ScopedDisposable where Inner == CompositeDisposable {
/// Adds the right-hand-side disposable to the left-hand-side
/// `ScopedDisposable<CompositeDisposable>`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Disposable to add.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: ScopedDisposable<CompositeDisposable>, rhs: Disposable?) -> Disposable? {
return lhs.inner.add(rhs)
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `ScopedDisposable<CompositeDisposable>`.
///
/// ````
/// disposable += { ... }
/// ````
///
/// - parameters:
/// - lhs: Disposable to add to.
/// - rhs: Closure to add as a disposable.
///
/// - returns: An instance of `DisposableHandle` that can be used to opaquely
/// remove the disposable later (if desired).
@discardableResult
public static func += (lhs: ScopedDisposable<CompositeDisposable>, rhs: @escaping () -> Void) -> Disposable? {
return lhs.inner.add(rhs)
}
}
/// A disposable that disposes of its wrapped disposable, and allows its
/// wrapped disposable to be replaced.
public final class SerialDisposable: Disposable {
private let _inner: Atomic<Disposable?>
private var state: UnsafeAtomicState<DisposableState>
public var isDisposed: Bool {
return state.is(.disposed)
}
/// The current inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var inner: Disposable? {
get {
return _inner.value
}
set(disposable) {
_inner.swap(disposable)?.dispose()
if let disposable = disposable, isDisposed {
disposable.dispose()
}
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
///
/// - parameters:
/// - disposable: Optional disposable.
public init(_ disposable: Disposable? = nil) {
self._inner = Atomic(disposable)
self.state = UnsafeAtomicState(DisposableState.active)
}
public func dispose() {
if state.tryDispose() {
_inner.swap(nil)?.dispose()
}
}
deinit {
state.deinitialize()
}
}
| mit | 361d64699599dc18f2376fdc1f440da3 | 25.202632 | 111 | 0.669077 | 3.797483 | false | false | false | false |
a736220388/TestKitchen_1606 | TestKitchen/TestKitchen/classes/community/homePage/CookBookViewController.swift | 1 | 7470 | //
// CookBookViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CookBookViewController: KTCHomeViewController {
var scrollView:UIScrollView?
private var recommendView:CBRecommendView?
private var foodView:CBMaterialView?
private var categoryView:CBMaterialView?
private var segCtrl:KTCSegmentCtrl?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createMyNav()
createHomePageView()
downloadRecommendData()
downloadFoodData()
downloadCategoryData()
}
func downloadCategoryData(){
let params = ["methodName":"CategoryIndex"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = .Category
downloader.postWithUrl(kHostUrl, params: params)
}
func downloadFoodData(){
let dict = ["methodName":"MaterialSubtype"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = KTCDownloaderType.FoodMaterial
downloader.postWithUrl(kHostUrl, params: dict)
}
func createHomePageView(){
automaticallyAdjustsScrollViewInsets = false
//推荐,食材,分类的滚动视图
scrollView = UIScrollView()
view.addSubview(scrollView!)
scrollView!.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
let containerView = UIView.createView()
scrollView!.addSubview(containerView)
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView!)
make.height.equalTo(self!.scrollView!)
}
recommendView = CBRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo(containerView)
})
foodView = CBMaterialView()
foodView?.backgroundColor = UIColor.redColor()
containerView.addSubview(foodView!)
foodView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((recommendView?.snp_right)!)
})
categoryView = CBMaterialView()
categoryView?.backgroundColor = UIColor.yellowColor()
containerView.addSubview(categoryView!)
categoryView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((foodView?.snp_right)!)
})
containerView.snp_makeConstraints { (make) in
make.right.equalTo((categoryView?.snp_right)!)
}
scrollView!.pagingEnabled = true
scrollView!.showsHorizontalScrollIndicator = false
scrollView?.delegate = self
}
func downloadRecommendData(){
let dict = ["methodName":"SceneHome"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = KTCDownloaderType.Recommend
downloader.postWithUrl(kHostUrl, params: dict)
}
func createMyNav(){
segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44 ), titleNames: ["推荐","食材","分类"])
segCtrl?.delegate = self
navigationItem.titleView = segCtrl
addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true)
addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false)
}
func scanAction(){
}
func searchAction(){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//显示首页推荐的数据
func showRecommendData(model:CBRecommendModel){
recommendView?.model = model
recommendView?.clickClosure = {
[weak self]
title,link in
if link.hasPrefix("app://food_course_series") == true{
let id = link.componentsSeparatedByString("#")[1]
/*
let startRange = NSString(string: link).rangeOfString("#")
let endRange = NSString(string: link).rangeOfString("#", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, link.characters.count))
let id = NSString(string: link).substringWithRange(NSMakeRange(startRange.location+1, endRange.location-startRange.location-1))
*/
let foodCourseCtrl = FoodCourseViewController()
foodCourseCtrl.seriesId = id
self!.navigationController?.pushViewController(foodCourseCtrl, animated: true)
}
}
}
func gotoFoodCoursePage(seriesId:String){
}
/*
// 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.
}
*/
}
extension CookBookViewController : KTCDownloaderDelegate{
func downloader(downloader: KTCDownloader, didFailWithError error: NSError) {
print(error)
}
func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) {
if downloader.type == .Recommend{
if let jsonData = data{
let model = CBRecommendModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.recommendView?.model = model
self?.showRecommendData(model)
})
}
}else if downloader.type == .FoodMaterial{
if let jsonData = data{
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.foodView?.model = model
})
}
}else if downloader.type == .Category{
if let jsonData = data{
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self?.categoryView?.model = model
})
}
}
}
}
extension CookBookViewController:KTCSegmentCtrlDelegate{
func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) {
scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true)
}
}
extension CookBookViewController:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
segCtrl?.selectedIndex = index
}
}
| mit | 2659295a23714cc36147367a06891cf3 | 35.170732 | 167 | 0.618476 | 5.174459 | false | false | false | false |
ripventura/VCHTTPConnect | Example/Pods/EFQRCode/Source/QRCodeType.swift | 2 | 3942 | //
// QRCodeType.swift
// EFQRCode
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// 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.
#if os(iOS) || os(tvOS) || os(macOS)
#else
struct QRCodeType {
private static let QRCodeLimitLength: [[Int]] = [
[17, 14, 11, 7],
[32, 26, 20, 14],
[53, 42, 32, 24],
[78, 62, 46, 34],
[106, 84, 60, 44],
[134, 106, 74, 58],
[154, 122, 86, 64],
[192, 152, 108, 84],
[230, 180, 130, 98],
[271, 213, 151, 119],
[321, 251, 177, 137],
[367, 287, 203, 155],
[425, 331, 241, 177],
[458, 362, 258, 194],
[520, 412, 292, 220],
[586, 450, 322, 250],
[644, 504, 364, 280],
[718, 560, 394, 310],
[792, 624, 442, 338],
[858, 666, 482, 382],
[929, 711, 509, 403],
[1003, 779, 565, 439],
[1091, 857, 611, 461],
[1171, 911, 661, 511],
[1273, 997, 715, 535],
[1367, 1059, 751, 593],
[1465, 1125, 805, 625],
[1528, 1190, 868, 658],
[1628, 1264, 908, 698],
[1732, 1370, 982, 742],
[1840, 1452, 1030, 790],
[1952, 1538, 1112, 842],
[2068, 1628, 1168, 898],
[2188, 1722, 1228, 958],
[2303, 1809, 1283, 983],
[2431, 1911, 1351, 1051],
[2563, 1989, 1423, 1093],
[2699, 2099, 1499, 1139],
[2809, 2213, 1579, 1219],
[2953, 2331, 1663, 1273]
]
}
extension QRCodeType {
/// Get the type by string length
static func typeNumber(of sText: String, errorCorrectLevel nCorrectLevel: QRErrorCorrectLevel) throws -> Int {
var nType = 1
let length = sText.utf8.count
let len = QRCodeLimitLength.count
for i in 0...len {
var nLimit = 0
switch (nCorrectLevel) {
case QRErrorCorrectLevel.L:
nLimit = QRCodeLimitLength[i][0]
case QRErrorCorrectLevel.M:
nLimit = QRCodeLimitLength[i][1]
case QRErrorCorrectLevel.Q:
nLimit = QRCodeLimitLength[i][2]
case QRErrorCorrectLevel.H:
nLimit = QRCodeLimitLength[i][3]
}
if (length <= nLimit) {
break
} else {
nType += 1
}
}
if (nType > QRCodeLimitLength.count) {
throw Failed("Too long data")
}
return nType
}
}
#endif
| mit | c56f95501015415a46933557aa8607fa | 35.165138 | 118 | 0.51243 | 4.038934 | false | false | false | false |
ffried/FFUIKit | Sources/FFUIKit/Extensions/UIView+AutoLayout.swift | 1 | 1828 | //
// UIView+AutoLayout.swift
// FFUIKit
//
// Created by Florian Friedrich on 09/03/16.
// Copyright 2016 Florian Friedrich
//
// 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.
//
#if !os(watchOS)
import UIKit
import FFFoundation
extension UIView {
public final func enableAutoLayout() {
if translatesAutoresizingMaskIntoConstraints {
translatesAutoresizingMaskIntoConstraints = false
}
}
// Would you really want to use this!?
public final func disableAutoLayout() {
if !translatesAutoresizingMaskIntoConstraints {
translatesAutoresizingMaskIntoConstraints = true
}
}
@discardableResult
public final func setupFullscreen(in view: UIView, with insets: UIEdgeInsets = .init(), prepare constraintPreparations: ((NSLayoutConstraint) -> Void)? = nil) -> [NSLayoutConstraint] {
enableAutoLayout()
if superview != view {
view.addSubview(self)
}
let constraints = [
"H:|-(==left)-[view]-(==right)-|",
"V:|-(==top)-[view]-(==bottom)-|"
].constraints(with: ["view": self], metrics: insets.asMetrics)
if let preps = constraintPreparations { constraints.forEach(preps) }
constraints.activate()
return constraints
}
}
#endif
| apache-2.0 | ad1c854ae55e0bc69394f01048bbbfec | 32.851852 | 188 | 0.665755 | 4.639594 | false | false | false | false |
Minecodecraft/EstateBand | EstateBand/UserListViewController.swift | 1 | 4865 | //
// UserListViewController.swift
// EstateBand
//
// Created by Minecode on 2017/6/12.
// Copyright © 2017年 org.minecode. All rights reserved.
//
import UIKit
import CoreData
class UserListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// Widget List
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var logoutButton: UIBarButtonItem!
var deleteButton: UIBarButtonItem!
// Data
var appDelegate: AppDelegate!
var userArray: [AnyObject]!
override func viewDidLoad() {
super.viewDidLoad()
self.appDelegate = UIApplication.shared.delegate as! AppDelegate
// 设置导航数据
self.navigationItem.title = "Worker List"
deleteButton = UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(toggleDelete(_:)))
self.navigationItem.leftBarButtonItem = deleteButton
// 设置底栏数据
self.tabBarItem.title = "Worker List"
self.tabBarItem.image = UIImage(named: "userList")
// 装载表格数据
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.dataSource = self
// 设置界面数据
}
override func viewWillAppear(_ animated: Bool) {
// 创建要抓取的目标实体
let request = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName: "User", in: self.appDelegate.managedObjectContext)
request.entity = entity
userArray = try! self.appDelegate.managedObjectContext.fetch(request) as [AnyObject]
self.tableView.reloadData()
// 修改界面数据
headerLabel.text = "\(userArray.count) workers"
}
func toggleDelete(_ sender: AnyObject) {
self.tableView.setEditing(!self.tableView.isEditing, animated: true)
if self.tableView.isEditing {
deleteButton.title = "Done"
} else {
deleteButton.title = "Delete"
}
}
@IBAction func logoutAction(_ sender: UIBarButtonItem) {
// let loginViewController = self.storyboard?.instantiateViewController(withIdentifier: "loginView")
// present(loginViewController!, animated: true, completion: nil)
self.dismiss(animated: true, completion: nil)
}
// MARK: - realization of TableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
let user = userArray[indexPath.row] as! User
cell.textLabel?.text = user.name
cell.detailTextLabel?.text = String(format: "%@%d", String("WorkID: "), user.workNumber)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let rowNo = indexPath.row
let deleteUser = userArray[rowNo] as! User
self.appDelegate.managedObjectContext.delete(deleteUser)
do {
try self.appDelegate.managedObjectContext.save()
} catch {
let alert = UIAlertController(title: "Failed", message: "Something error!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: {
(action) in self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
userArray.remove(at: rowNo)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
// func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
// NSLog("Here")
// let userDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "userDetailView") as! UserDetailViewController
// userDetailViewController.user = userArray[indexPath.row] as! User
// self.navigationController?.pushViewController(userDetailViewController, animated: true)
// }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue2UserDetailView" {
let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)
let target = segue.destination as! UserDetailViewController
target.user = userArray[indexPath!.row] as! User
}
}
}
| mit | af9aa05601dc50af8bf543e0a97c9266 | 39.525424 | 146 | 0.655583 | 5.060317 | false | false | false | false |
he-mark-qinglong/swift-keypoints | MyPlayground.playground/section-1.swift | 1 | 11398 | //导入框架,所有Cocoa框架都已经封装过了
import Cocoa
//基本变量
func variableTest(){
//❓在调用变量时,如果 variable?.doSomeThing()中variable为nil,则返回nil,否则展开调用返回调用结果
//由于这个原因,在swift中应该是没有基本类型了,比如int,bool,char *等等
var variable:Int? = 2
variable = nil
var variable2:Bool = true
variable2 = true
enum Rank: Int{
case Ace = 1
case Two, Three, Four, Five, Six,
Seven,
Eight, Nine, Ten
case Jack, Queen, King
func description()->String{
switch self{
case .Ace:
return "ace"
case .Jack:
return "Jack"
case .King:
return "King"
case .Queen:
return "Queen"
default:
return String (self.toRaw())
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
ace.description()
if let convertedRank = Rank.fromRaw(3){
let threeDescription = convertedRank.description()
}
}
variableTest();
//自定义类型
func selfDefinitionTypeTest(){
var str = "Hello, playground"
var equivalentEmptyArray = Array<Int>()
equivalentEmptyArray += 4;
struct MyType: Printable {
var name = "Untitled"
var description: String { //默认的描述函数,打印的时候用
return "MyType: \(name)"
}
}
let value = MyType()
println("Created a \(value)")
struct MyType2: DebugPrintable {
var name = "Untitled"
var debugDescription: String {
return "MyType: \(name)"
}
}
let value2 = MyType2()
}
selfDefinitionTypeTest();
//元组,C++ 中std::tuple<T>, python内核类型
func tupleTest(){
func tuple() -> (Double, Double, Double){
return (5, 2, 7);
}
var (a,b,c) = tuple()
a
b
c
var ret = tuple()
ret.0
ret.1
ret.2
}
tupleTest();
//模板测试
func templateTest(){
struct TmpVar<T>{
var integer = 2
var string = "let's have a talk"
init(var integer:Int){
self.integer = integer
}
}
func mySort< T > (var array:Array<TmpVar<T>>) -> Array<TmpVar<T>>{
for x in 0 .. array.count-1 {
if array[x].integer > array[x+1].integer {
swap(&array[x], &array[x+1])
}
}
return array
}
var myArray = [TmpVar<Int>(integer: 3), TmpVar(integer:102), TmpVar(integer:100)]
var anotherArray = mySort(myArray)
for x in anotherArray {
print(x.integer)
}
}
templateTest();
func ffpTest(){
//函数式编程,
//函数内嵌函数,改变外部值
func returnFifteen() -> Int{
var y = 10
func add5(){
y += 5
}
add5()
return y
}
returnFifteen()
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
//摘录来自: Apple Inc. “The Swift Programming Language”。 iBooks. https://itun.es/us/jEUH0.l
//函数返回函数
func makeIncrementer() ->
Double->Int{ //实际上是(Double)->Int,也就是一个函数
func addOne(number:Double)->Int{
return 1 + Int(number);
}
return addOne;
}
var increment = makeIncrementer()
increment(7.0);
func closuerTest(){
var list:Int[] = [1,2,3]
func hasAnyMatched(#list:Int[], //#符号表示这个表量和外部的变量是同一个变量
var/*表示函数内部可以改变这个值,没有var相当于const*/
Condition/*第二参数名*/ condition:Int->Bool) -> Bool{
for item in list{
if condition(item){
return true;
}
}
return false
}
var numbers = [20, 19, 7, 12]
var condition = { number in number < 10}
var match = hasAnyMatched(numbers, condition)
match
numbers.map({
(number:Int)->Int in
return 3*number
})
//闭包的类型已知,不用给出参数类型,返回类型,简化版:
var mappedValue = numbers.map({number in number+3})
mappedValue
numbers
}
closuerTest();
}
ffpTest();
//扩展类型
//protocol定义和扩展只能放在全局文件中
protocol Nothing{
}
extension Int{
var simpleDescription:String{
return "The number \(self)"
}
mutating func adjust(){
self += 42
}
}
func extensionTest(){
var number = 7
number.adjust()
number.simpleDescription
}
extensionTest();
//In-Out Parameters
func In_Out_Parameters(){
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 5
swapTwoInts(&someInt, &anotherInt)
someInt
anotherInt
}
In_Out_Parameters();
//闭包
/*
Closure expression syntax has the following general form:
{ (parameters) -> return type in
statements
}
*/
func ClosureTest(){
var names = ["He", "Qinglong"]
//传入一个闭包作为排序的条件函数
var reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )
//由于sort的输入参数中,第一个参数的类型可以推导,所以闭包的参数类型也可以被推导出来,因此可以简写为:
reversed = sort(names, {s1, s2 in return s1 < s2})
//更进一步,隐式的返回类型
reversed = sort(names, {s1, s2 in s1 < s2})
/*Swift automatically provides shorthand argument names to inline closures,
which can be used to refer to the values of the closure’s arguments
by the names $0, $1, $2, and so on.
*/
reversed = sort(names, {$0 > $1})
//尾随形式
reversed = sort(names){ $0 > $1}
//Here, $0 and $1 refer to the closure’s first and second String arguments
/*Swift’s String type defines its string-specific implementation of the greater-than
operator (>) as a function that has two parameters of type String,
and returns a value of type Bool
*/
reversed = sort(names, >)
//尾随形式的解释:
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({
// closure's body goes here
})
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ]
let numbers = [16, 58, 510]
let strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
strings
// strings is inferred to be of type String[]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
//返回函数的函数
func makeIncrementor(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementor() -> Int {
runningTotal += amount
return runningTotal
}
return incrementor
}
}
ClosureTest();
//Type Methods,静态成员函数
func typeMethodsTest(){
//在类里面使用class声明静态成员方法
class SomeClass {
var xx:Int = 0 //目前为止,没有实现类的静态成员变量
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
//在结构体里面使用static声明静态成员方法 和 静态成员变量
struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) {
if level > highestUnlockedLevel { highestUnlockedLevel = level }
}
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level: Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
}
typeMethodsTest();
//class inheritance
func inheritance(){
//Base lcass
class Vehicle {
var numberOfWheels: Int
var maxPassengers: Int
func description() -> String {
return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
}
init() {
numberOfWheels = 0
maxPassengers = 1
}
}
class Car: Vehicle {
var speed: Double = 0.0
init() {
super.init()
maxPassengers = 5
numberOfWheels = 4
}
override func description() -> String {
return super.description() + "; "
+ "traveling at \(speed) mph"
}
}
let car = Car()
println("Car: \(car.description())")
class SpeedLimitedCar: Car {
override var speed: Double {
get {
return super.speed
}
set {
super.speed = min(newValue, 40.0)
}
}
func subClassFunc(){
println("我的青春我做主")
}
init(){} //构造函数/初始器
deinit{} //析构函数/析构器
}
var normalCar:Car = Car()
normalCar.speed = 100;
var limitedCar = SpeedLimitedCar()
normalCar = limitedCar
//// ((SpeedLimitedCar*)normalCar).subClassFunc(); //看来不能强制转换
}
inheritance();
//可选类型: ? 与 !
func optionalTest(){
class Person {
var residence: Residence?
init(){}
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
var xx:String?
// ? 在residence为空的时候不会崩溃,返回的值是nil
if let roomCount = john.residence?.numberOfRooms {
xx = "John's residence has \(roomCount) room(s)."
} else {
xx = "Unable to retrieve the number of rooms."
}
println(xx?)
// !在residence为空的时候会再这里崩溃
// this triggers a runtime error
let roomCount = john.residence!.numberOfRooms
}
optionalTest();
| gpl-2.0 | dbad78ca57a65145ffd2ed936dd4abac | 23.055046 | 91 | 0.548246 | 4.108108 | false | false | false | false |
devincoughlin/swift | test/decl/var/property_wrappers.swift | 1 | 49745 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{'init(wrappedValue:)' cannot be failable}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue // expected-error{{property wrappers are not yet supported on local properties}}
var x = 17
x = 42
_ = x
}
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
@Wrapper(stored: 17)
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17) // expected-error {{initializer expects a single parameter of type 'T' [with T = (wrappedValue: Int, stored: Int)]}}
// expected-note@-1 {{did you mean to pass a tuple?}}
var x3 = 42
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
// FIXME: For some reason this is type-checked twice, second time around solver complains about <<error type>> argument
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to expected argument type 'Int'}}
// expected-error@-1 {{cannot convert value of type '<<error type>>' to expected argument type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{property wrapper type 'WrapperForHashable' declared here}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
// FIXME: Diagnostic should be better here
@WrapperForHashable
var y: NotHashable // expected-error{{property type 'NotHashable' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperForHashable'}}
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
// FIXME: Need a better diagnostic here
@HasNestedWrapper.NestedWrapper
var w: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'HasNestedWrapper.NestedWrapper'}}
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{property wrapper type 'Function' declared here}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
@Function var f2: (Int) -> Float // expected-error{{property type '(Int) -> Float' does not match that of the 'wrappedValue' property of its wrapper type 'Function'}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> {
@propertyWrapper
struct NestedWrapper<U> { // expected-note{{property wrapper type 'NestedWrapper' declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{incorrect argument label in call (have 'x:', expected 'y:')}}
// expected-error@-1 {{cannot convert value of type 'Wrapper<Bool>' to expected argument type 'Int'}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
// expected-note@-2{{'BrokenLazy' declared here}}
struct S {
@BrokenLazy // expected-error{{struct 'BrokenLazy' cannot be used as an attribute}}
var wrappedValue: Int
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper { // expected-note{{property wrapper type 'SR_10899_Wrapper' declared here}}
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match that of the 'wrappedValue' property of its wrapper type 'SR_10899_Wrapper'}}
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> {
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> { // expected-note{{property wrapper type 'WrapperD' declared here}}
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperD<WrapperC, Int, String>'}}
func triggerErrors(d: Double) {
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
}
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
@Foo var x: Int = 42 // expected-error {{cannot invoke initializer for ty}}
// expected-note@-1{{overloads for 'Foo<_>' exist with these partially matching paramet}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject {
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error 2 {{'SR_11288_S4.SR_11288_Wrapper4.Type' (aka 'SR_11288_S0.Type') requires that 'SR_11288_S4' conform to 'AnyObject'}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
// SR-11477
// Two initializers that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W1 { // Okay
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Two initializers with default arguments that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W2 { // Okay
let name: String
init(anotherName: String = "DefaultParamInit1") {
self.name = anotherName
}
init(name: String = "DefaultParamInit2") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Single initializer that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W3 { // Okay
let name: String
init() {
self.name = "Init"
}
var wrappedValue: Int {
get { return 0 }
}
}
// rdar://problem/56213175 - backward compatibility issue with Swift 5.1,
// which unconditionally skipped protocol members.
protocol ProtocolWithWrapper {
associatedtype Wrapper = Float // expected-note{{associated type 'Wrapper' declared here}}
}
struct UsesProtocolWithWrapper: ProtocolWithWrapper {
@Wrapper var foo: Int // expected-warning{{ignoring associated type 'Wrapper' in favor of module-scoped property wrapper 'Wrapper'; please qualify the reference with 'property_wrappers'}}{{4-4=property_wrappers.}}
}
| apache-2.0 | d85b900d2a63881eda925dfcbf34ba07 | 26.774986 | 234 | 0.647884 | 4.17499 | false | false | false | false |
simonbs/bemyeyes-ios | BeMyEyes/Source/Views/Button.swift | 1 | 2218 | //
// Button.swift
// BeMyEyes
//
// Created by Tobias DM on 08/10/14.
// Copyright (c) 2014 Be My Eyes. All rights reserved.
//
import UIKit
@IBDesignable class Button: UIControl {
@IBInspectable var title: String? {
didSet {
titleLabel.text = title
}
}
@IBInspectable var font: UIFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) {
didSet {
titleLabel.font = font
}
}
var color: UIColor = UIColor.whiteColor()
var highlightedColor: UIColor = UIColor.lightTextColor()
var selectedColor: UIColor = UIColor.lightTextColor()
var disabledColor: UIColor = UIColor.lightTextColor()
override var enabled: Bool {
didSet {
updateToState()
}
}
override var highlighted: Bool {
didSet {
updateToState()
}
}
private lazy var titleLabel: MaskedLabel = {
let label = MaskedLabel()
label.font = self.font
label.textAlignment = .Center
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = CGRectInset(bounds, 15, 7.5)
}
override func prepareForInterfaceBuilder() {
setup()
}
}
extension Button {
func setup() {
opaque = false
backgroundColor = UIColor.clearColor()
addSubview(titleLabel)
}
func accessibilityLabel() -> String! {
return titleLabel.accessibilityLabel
}
func updateToState() {
titleLabel.color = colorForState(state)
}
func colorForState(state: UIControlState) -> UIColor {
switch (state) {
case UIControlState.Normal: return color
case UIControlState.Selected: return selectedColor
case UIControlState.Highlighted: return highlightedColor
case UIControlState.Disabled: return disabledColor
default: return color
}
}
}
| mit | 95292c7b999e54c1fff36641beaa567f | 22.595745 | 97 | 0.594229 | 5.110599 | false | false | false | false |
ndleon09/TopApps | TopApps/App.swift | 1 | 908 | //
// App.swift
// TopApps
//
// Created by Nelson Dominguez on 24/04/16.
// Copyright © 2016 Nelson Dominguez. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
class App: Object
{
dynamic var id: Int = 0
dynamic var name: String?
dynamic var category: String?
dynamic var image: String?
dynamic var summary: String?
override static func primaryKey() -> String? {
return "id"
}
}
extension App {
static func build(json: JSON) -> App {
let app = App()
app.id = json["id"]["attributes"]["im:id"].intValue
app.name = json["im:name"]["label"].stringValue
app.category = json["category"]["attributes"]["label"].stringValue
app.image = json["im:image"].array?.last!["label"].stringValue
app.summary = json["summary"]["label"].stringValue
return app
}
}
| mit | 96c19825af6ce60fccddd565fee851ad | 22.25641 | 74 | 0.6086 | 4.104072 | false | false | false | false |
milseman/swift | stdlib/public/SDK/Foundation/Measurement.swift | 13 | 14999 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(value))
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(type(of: unit).baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(_ lhs: Measurement<LeftHandSideType>, _ rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Measurement)
}
}
// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}
// @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }
// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
| apache-2.0 | 2bab2ea58811b80adf9cf699a4dc82db | 45.580745 | 280 | 0.65471 | 4.674042 | false | false | false | false |
tkuichooseyou/LivingWords | LivingWords/BibleParser.swift | 1 | 2796 | import UIKit
public class BibleParser: NSObject {
static let errorMessage = "Verse not found"
public class func textForParsedVerse(parsedVerse:ParsedVerse) -> String {
let verseStart = parsedVerse.numberStart.integerValue
let verseEnd = parsedVerse.numberEnd.integerValue
if verseEnd < verseStart {
return errorMessage
}
let chapterStartPattern = "<span (?:id=\"calibre_link-\\d+\" )?class=\"chapter-num\">\\s\(parsedVerse.chapterStart)\\s</span>"
let numberEndBound = parsedVerse.numberEnd.integerValue + 1
let chapterEndBound = parsedVerse.chapterStart.integerValue + 1
let endBoundOne = "(?:<p (?:id=\"calibre_link-\\d+\" )?class=\"heading\".{1,50}<\\/p>.{1,50}?<span class=\"book-name\".+?</span><span (?:id=\"calibre_link-\\d+\" )?class=\"chapter-num\">\\s\(chapterEndBound)\\s</span>)"
let endBoundTwo = "(?:<span (?:id=\"calibre_link-\\d+\" )?class=\"verse-num\">\(numberEndBound)</span>)"
let endBound = "(?:" + endBoundOne + "|" + endBoundTwo + ")"
let normalCaptureGroup = "(<span (?:id=\"calibre_link-\\d+\" )?class=\"verse-num\">\(parsedVerse.numberStart)</span>(?:.*?)?)"
let pattern = parsedVerse.numberStart == 1 ?
"(" + chapterStartPattern + ".*?)" + endBound :
chapterStartPattern + "(?:.*?)" + normalCaptureGroup + endBound
if let bookPath = NSBundle.mainBundle().pathForResource(parsedVerse.bookFileString(), ofType: "html", inDirectory: "esv"),
bookString = try? NSString(contentsOfFile: bookPath, encoding: NSUTF8StringEncoding) as String {
if let htmlString = matchesForRegexInText(pattern, text: bookString).first,
htmlData = htmlString
.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : NSUTF8StringEncoding] as [String : AnyObject]
return try! NSAttributedString(data: htmlData, options: options, documentAttributes: nil).string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
?? errorMessage
}
}
return errorMessage
}
class func matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = try! NSRegularExpression(pattern: regex, options: .DotMatchesLineSeparators)
let nsString = text as NSString
let results = regex.matchesInString(text,
options: .ReportProgress, range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.rangeAtIndex(1))}
}
}
| apache-2.0 | 9620344679bbbbd4138270d5d700e51d | 61.133333 | 227 | 0.6402 | 4.922535 | false | false | false | false |
randallli/material-components-ios | components/Dialogs/examples/DialogsCustomShadowViewController.swift | 1 | 3896 | /*
Copyright 2018-present the Material Components for iOS 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 Foundation
import MaterialComponents
class CustomShadowViewController: UIViewController {
let bodyLabel = UILabel()
let dismissButton = MDCFlatButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 32.0
bodyLabel.text =
"This presented view has a corner radius so we've set the corner radius on the presentation controller."
bodyLabel.translatesAutoresizingMaskIntoConstraints = false
bodyLabel.numberOfLines = 0
bodyLabel.sizeToFit()
self.view.addSubview(bodyLabel)
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-[body]-|", options: [], metrics: nil, views: [ "body": bodyLabel]))
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-[body]-|", options: [], metrics: nil, views: [ "body": bodyLabel]))
}
override var preferredContentSize: CGSize {
get {
return CGSize(width:200.0, height:140.0);
}
set {
super.preferredContentSize = newValue
}
}
}
class DialogsCustomShadowViewController: UIViewController {
let flatButton = MDCFlatButton()
let transitionController = MDCDialogTransitionController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
flatButton.setTitle("PRESENT ALERT", for: UIControlState())
flatButton.setTitleColor(UIColor(white: 0.1, alpha:1), for: UIControlState())
flatButton.sizeToFit()
flatButton.translatesAutoresizingMaskIntoConstraints = false
flatButton.addTarget(self, action: #selector(tap), for: .touchUpInside)
self.view.addSubview(flatButton)
NSLayoutConstraint.activate([
NSLayoutConstraint(item:flatButton,
attribute:.centerX,
relatedBy:.equal,
toItem:self.view,
attribute:.centerX,
multiplier:1.0,
constant: 0.0),
NSLayoutConstraint(item:flatButton,
attribute:.centerY,
relatedBy:.equal,
toItem:self.view,
attribute:.centerY,
multiplier:1.0,
constant: 0.0)
])
}
@objc func tap(_ sender: Any) {
let presentedController = CustomShadowViewController(nibName: nil, bundle: nil)
presentedController.modalPresentationStyle = .custom;
presentedController.transitioningDelegate = self.transitionController;
self.present(presentedController, animated: true, completion: nil)
// We set the corner radius to adjust the shadow that is implemented via the trackingView in the
// presentation controller.
if let presentationController = presentedController.mdc_dialogPresentationController {
presentationController.dialogCornerRadius = presentedController.view.layer.cornerRadius
}
}
// MARK: Catalog by convention
@objc class func catalogBreadcrumbs() -> [String] {
return [ "Dialogs", "View with Corner Radius"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
@objc class func catalogIsPresentable() -> Bool {
return false
}
}
| apache-2.0 | c877fc0e3faa4e7f4a259ba242d096a4 | 32.299145 | 127 | 0.689168 | 5.236559 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | Carthage/Checkouts/Nuke/Tests/RateLimiterTests.swift | 1 | 2543 | // The MIT License (MIT)
//
// Copyright (c) 2017 Alexander Grebenyuk (github.com/kean).
import XCTest
import Nuke
class RateLimiterTests: XCTestCase {
// MARK: Thread Safety
func testThreadSafety() {
let scheduler = MockScheduler()
let limiter = RateLimiter(scheduler: scheduler, rate: 10000, burst: 1000)
// can't figure out how to put closures that accept
// escaping closures as parameters directly in the array
struct Op {
let closure: (@escaping () -> Void) -> Void
}
var ops = [Op]()
ops.append(Op() { fulfill in
limiter.execute(token: nil) { finish in
sleep(UInt32(Double(rnd(10)) / 100.0))
finish()
fulfill()
}
})
ops.append(Op() { fulfill in
// cancel after executing
let cts = CancellationTokenSource()
limiter.execute(token: cts.token) { finish in
sleep(UInt32(Double(rnd(10)) / 100.0))
finish()
}
cts.cancel()
fulfill() // we don't except fulfil
})
ops.append(Op() { fulfill in
// cancel immediately
let cts = CancellationTokenSource()
cts.cancel()
limiter.execute(token: cts.token) { finish in
sleep(UInt32(Double(rnd(10)) / 100.0))
finish()
XCTFail() // must not be executed
}
fulfill()
})
for _ in 0..<5000 {
expect { fulfill in
let queue = OperationQueue()
// RateLimiter is not designed (unlike user-facing classes) to
// handle unlimited pressure from the outside, thus we limit
// the number of concurrent ops
queue.maxConcurrentOperationCount = 50
queue.addOperation {
ops.randomItem().closure(fulfill)
}
}
}
wait()
}
}
private class MockScheduler: Nuke.AsyncScheduler {
private let queue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 50
return queue
}()
fileprivate func execute(token: CancellationToken?, closure: @escaping (@escaping () -> Void) -> Void) {
queue.addOperation {
closure { return }
}
}
}
| mit | fc9b77a30b1ac0269ffabfca17811f3c | 28.569767 | 108 | 0.505309 | 5.23251 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/Announcements/CardView/AnnouncementCardViewModel.swift | 1 | 7467 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
/// An announcement card view model
public final class AnnouncementCardViewModel {
// MARK: - Types
public typealias AccessibilityId = Accessibility.Identifier.AnnouncementCard
public typealias DidAppear = () -> Void
/// The priority under which the announcement should show
public enum Priority {
case high
case low
}
/// The style of the background
public struct Background {
/// A blank white background. a computed property.
public static var white: Background {
Background(color: .white)
}
/// The background color
let color: UIColor
/// The background image
let imageName: String?
let bundle: Bundle
/// Computes the `UIImage` out of `imageName`
var image: UIImage? {
guard let imageName = imageName else { return nil }
return UIImage(
named: imageName,
in: bundle,
compatibleWith: .none
)
}
public init(color: UIColor = .clear, imageName: String? = nil, bundle: Bundle = .main) {
self.imageName = imageName
self.color = color
self.bundle = bundle
}
}
/// The border style of the card
public enum Border {
/// Round corners with radius value
case roundCorners(_ radius: CGFloat)
/// Separator
case bottomSeparator(_ color: UIColor)
/// No border
case none
}
/// The alignment of the content
public enum Alignment {
/// Natual alignment (leading -> trailing)
case natural
/// Center alignment
case center
}
public enum BadgeImage {
case hidden
case visible(BadgeImageViewModel, CGSize)
public init(
image: ImageResource,
contentColor: UIColor? = .defaultBadge,
backgroundColor: UIColor = .lightBadgeBackground,
cornerRadius: BadgeImageViewModel.CornerRadius = .roundedHigh,
accessibilityID: String = AccessibilityId.badge,
size: CGSize
) {
let image = ImageViewContent(
imageResource: image,
accessibility: .id(accessibilityID),
renderingMode: contentColor.flatMap { .template($0) } ?? .normal
)
let theme = BadgeImageViewModel.Theme(
backgroundColor: backgroundColor,
cornerRadius: cornerRadius,
imageViewContent: image,
marginOffset: 0
)
self = .visible(.init(theme: theme), size)
}
var verticalPadding: CGFloat {
switch self {
case .hidden:
return 0.0
case .visible:
return 16.0
}
}
var size: CGSize {
switch self {
case .hidden:
return .zero
case .visible(_, let value):
return value
}
}
var viewModel: BadgeImageViewModel? {
switch self {
case .hidden:
return nil
case .visible(let value, _):
return value
}
}
var isVisible: Bool {
switch self {
case .hidden:
return false
case .visible:
return true
}
}
}
/// The dismissal state of the card announcement
public enum DismissState {
public typealias Action = () -> Void
/// Indicates the announcement is dismissable and the associated `Action`
/// is should be executed upon dismissal
case dismissible(Action)
/// Indicates the announcement is not dismissable. Therefore `X` button is hidden.
case undismissible
}
/// The presentation type of the card
public enum Presentation {
/// This will render a regular full size card
case regular
}
/// The interaction of the user with the card itself
public enum Interaction {
/// The background is tappable
case tappable(() -> Void)
/// No interaction
case none
var isTappable: Bool {
switch self {
case .tappable:
return true
case .none:
return false
}
}
}
// MARK: - Public Properties
public var priority: Priority { .high }
public let presentation: Presentation
public let type: AnnouncementType?
// MARK: - Properties
let interaction: Interaction
let badgeImage: BadgeImage
let contentAlignment: Alignment
let background: Background
let border: Border
let title: String?
let description: String?
let buttons: [ButtonViewModel]
let didAppear: DidAppear?
/// Returns `true` if the dismiss button should be hidden
var isDismissButtonHidden: Bool {
switch dismissState {
case .undismissible:
return true
case .dismissible:
return false
}
}
/// The action associated with the announcement dismissal.
var dismissAction: DismissState.Action? {
switch dismissState {
case .dismissible(let action):
return action
case .undismissible:
return nil
}
}
private let dismissState: DismissState
/// Upon receiving events triggers dismissal.
/// This comes in handy when the user has performed an indirect
/// action that should cause card dismissal.
let dismissalRelay = PublishRelay<Void>()
private var dismissal: Completable {
dismissalRelay
.take(1)
.ignoreElements()
.asCompletable()
.observe(on: MainScheduler.instance)
}
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(
type: AnnouncementType? = nil,
presentation: Presentation = .regular,
interaction: Interaction = .none,
badgeImage: BadgeImage = .hidden,
contentAlignment: Alignment = .natural,
background: Background = .white,
border: Border = .bottomSeparator(.mediumBorder),
title: String? = nil,
description: String? = nil,
buttons: [ButtonViewModel] = [],
dismissState: DismissState,
didAppear: DidAppear? = nil
) {
self.type = type
self.presentation = presentation
self.interaction = interaction
self.badgeImage = badgeImage
self.contentAlignment = contentAlignment
self.background = background
self.border = border
self.title = title
self.description = description
self.dismissState = dismissState
self.buttons = buttons
self.didAppear = didAppear
if let dismissAction = dismissAction {
dismissal
.subscribe(onCompleted: dismissAction)
.disposed(by: disposeBag)
}
}
}
extension AnnouncementCardViewModel: Equatable {
public static func == (lhs: AnnouncementCardViewModel, rhs: AnnouncementCardViewModel) -> Bool {
lhs.type == rhs.type
}
}
| lgpl-3.0 | 98b68219dd2708d4e93454ace74eaa0b | 25.856115 | 100 | 0.571926 | 5.509963 | false | false | false | false |
waterskier2007/NVActivityIndicatorView | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallRotate.swift | 1 | 4025 | //
// NVActivityIndicatorAnimationBallRotate.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 UIKit
class NVActivityIndicatorAnimationBallRotate: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.7, -0.13, 0.22, 0.86)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = [0, 0.5, 1]
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
let leftCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let rightCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let centerCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
leftCircle.opacity = 0.8
leftCircle.frame = CGRect(x: 0, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
rightCircle.opacity = 0.8
rightCircle.frame = CGRect(x: size.width - circleSize, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
centerCircle.frame = CGRect(x: (size.width - circleSize) / 2, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
let circle = CALayer()
<<<<<<< HEAD
let frame = CGRect(x: (layer.bounds.width - size.width) / 2, y: (layer.bounds.height - size.height) / 2, width: size.width, height: size.height)
=======
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height)
>>>>>>> ninjaprox/master
circle.frame = frame
circle.addSublayer(leftCircle)
circle.addSublayer(rightCircle)
circle.addSublayer(centerCircle)
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 7973b8589e3602d31abf28f5fff1e643 | 45.264368 | 162 | 0.704845 | 4.537768 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/AppDelegate.swift | 1 | 19064 | //
// AppDelegate.swift
// Slide for Reddit
//
// Created by Carlos Crane on 12/22/16.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import UIKit
import reddift
import UserNotifications
import RealmSwift
import SDWebImage
/// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain.
public let OAuth2TokenRepositoryDidSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidSaveToken")
/// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain.
public let OAuth2TokenRepositoryDidFailToSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidFailToSaveToken")
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let name = "reddittoken"
var session: Session? = nil
var fetcher: BackgroundFetch? = nil
var subreddits: [Subreddit] = []
var paginator = Paginator()
var login: SubredditsViewController?
var seenFile: String?
var commentsFile: String?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
seenFile = documentDirectory.appending("/seen.plist")
commentsFile = documentDirectory.appending("/comments.plist")
let config = Realm.Configuration(
schemaVersion: 4,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 4) {
}
})
Realm.Configuration.defaultConfiguration = config
application.setMinimumBackgroundFetchInterval(TimeInterval.init(900))
let fileManager = FileManager.default
if(!fileManager.fileExists(atPath: seenFile!)){
if let bundlePath = Bundle.main.path(forResource: "seen", ofType: "plist"){
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do{
try fileManager.copyItem(atPath: bundlePath, toPath: seenFile!)
}catch{
print("copy failure.")
}
}else{
print("file myData.plist not found.")
}
}else{
print("file myData.plist already exits at path.")
}
if(!fileManager.fileExists(atPath: commentsFile!)){
if let bundlePath = Bundle.main.path(forResource: "comments", ofType: "plist"){
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do{
try fileManager.copyItem(atPath: bundlePath, toPath: commentsFile!)
}catch{
print("copy failure.")
}
}else{
print("file myData.plist not found.")
}
}else{
print("file myData.plist already exits at path.")
}
session = Session()
History.seenTimes = NSMutableDictionary.init(contentsOfFile: seenFile!)!
History.commentCounts = NSMutableDictionary.init(contentsOfFile: commentsFile!)!
UIApplication.shared.statusBarStyle = .lightContent
SettingValues.initialize()
FontGenerator.initialize()
AccountController.initialize()
PostFilter.initialize()
Drafts.initialize()
Subscriptions.sync(name: AccountController.currentName, completion: nil)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
if((error) != nil){
print(error!.localizedDescription)
}
}
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
if((error) != nil){
print(error!.localizedDescription)
}
}
UIApplication.shared.registerForRemoteNotifications()
} else {
// Fallback on earlier versions
}
if !UserDefaults.standard.bool(forKey: "sc" + name){
syncColors(subredditController: nil)
}
ColorUtil.doInit()
let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
UINavigationBar.appearance().titleTextAttributes = textAttributes
statusBar.frame = CGRect(x: 0, y: 0, width: (self.window?.frame.size.width)!, height: 20)
statusBar.backgroundColor = UIColor.black.withAlphaComponent(0.15)
self.window?.rootViewController?.view.addSubview(statusBar)
return true
}
var statusBar = UIView()
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let session = session {
do {
let request = try session.requestForGettingProfile()
let fetcher = BackgroundFetch(current: session,
request: request,
taskHandler: { (response, dataURL, error) -> Void in
print("Doing")
if let response = response, let dataURL = dataURL {
if response.statusCode == HttpStatus.ok.rawValue {
do {
let data = try Data(contentsOf: dataURL)
let result = accountInResult(from: data, response: response)
switch result {
case .success(let account):
print(account)
UIApplication.shared.applicationIconBadgeNumber = account.inboxCount
self.postLocalNotification("You have \(account.inboxCount) new messages.")
completionHandler(.newData)
return
case .failure(let error):
print(error)
self.postLocalNotification("\(error)")
completionHandler(.failed)
}
}
catch {
}
}
else {
self.postLocalNotification("response code \(response.statusCode)")
completionHandler(.failed)
}
} else {
self.postLocalNotification("Error can not parse response and data.")
completionHandler(.failed)
}
})
fetcher.resume()
self.fetcher = fetcher
} catch {
print(error.localizedDescription)
postLocalNotification("\(error)")
completionHandler(.failed)
}
} else {
print("Fail")
postLocalNotification("session is not available.")
completionHandler(.failed)
}
}
func postLocalNotification(_ message: String) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "New messages!"
content.body = message
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300,
repeats: false)
let identifier = "SlideMSGNotif"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if error != nil {
print(error!.localizedDescription)
// Something went wrong
}
})
} else {
// Fallback on earlier versions
}
}
func syncColors(subredditController: SubredditsViewController?) {
let defaults = UserDefaults.standard
var toReturn: [String] = []
defaults.set(true, forKey: "sc" + name)
defaults.synchronize()
do {
if(!AccountController.isLoggedIn){
try session?.getSubreddit(.default, paginator:paginator, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!)
case .success(let listing):
self.subreddits += listing.children.flatMap({$0 as? Subreddit})
self.paginator = listing.paginator
for sub in self.subreddits{
toReturn.append(sub.displayName)
if(!sub.keyColor.isEmpty){
let color = (UIColor.init(hexString: sub.keyColor))
if(defaults.object(forKey: "color" + sub.displayName) == nil){
defaults.setColor(color: color , forKey: "color+" + sub.displayName)
}
}
}
}
if(subredditController != nil){
DispatchQueue.main.async (execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
})
} else {
Subscriptions.getSubscriptionsFully(session: session!, completion: { (subs, multis) in
for sub in subs {
toReturn.append(sub.displayName)
if(!sub.keyColor.isEmpty){
let color = (UIColor.init(hexString: sub.keyColor))
if(defaults.object(forKey: "color" + sub.displayName) == nil){
defaults.setColor(color: color , forKey: "color+" + sub.displayName)
}
}
}
for m in multis {
toReturn.append("/m/" + m.displayName)
if(!m.keyColor.isEmpty){
let color = (UIColor.init(hexString: m.keyColor))
if(defaults.object(forKey: "color" + m.displayName) == nil){
defaults.setColor(color: color , forKey: "color+" + m.displayName)
}
}
}
toReturn = toReturn.sorted{ $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
toReturn.insert("all", at: 0)
toReturn.insert("slide_ios", at: 0)
toReturn.insert("frontpage", at: 0)
if(subredditController != nil){
DispatchQueue.main.async (execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
})
}
} catch {
print(error)
if(subredditController != nil){
DispatchQueue.main.async (execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print("Returning \(url.absoluteString)")
var parameters: [String:String] = url.getKeyVals()!
if let code = parameters["code"], let state = parameters["state"] {
print(state)
if code.characters.count > 0 {
print(code)
}
}
return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: {(result) -> Void in
print(result)
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of: token.name)
self.login?.setToken(token: token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
} catch {
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidFailToSaveTokenName, object: nil, userInfo: nil)
print(error)
}
})
}
})
}
func killAndReturn(){
if let rootViewController = UIApplication.topViewController() {
var navigationArray = rootViewController.viewControllers
navigationArray.removeAll()
rootViewController.viewControllers = navigationArray
rootViewController.pushViewController(SubredditsViewController(coder: NSCoder.init())!, animated: false)
}
}
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("background")
History.seenTimes.write(toFile: seenFile!, atomically: true)
History.commentCounts.write(toFile: commentsFile!, atomically: true)
// 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) {
self.refreshSession()
}
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) {
History.seenTimes.write(toFile: seenFile!, atomically: true)
History.commentCounts.write(toFile: commentsFile!, atomically: true)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func refreshSession() {
// refresh current session token
do {
try self.session?.refreshToken({ (result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
print(token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
})
}
})
} catch { print(error) }
}
func reloadSession() {
// reddit username is save NSUserDefaults using "currentName" key.
// create an authenticated or anonymous session object
if let currentName = UserDefaults.standard.object(forKey: "name") as? String {
do {
let token = try OAuth2TokenRepository.token(of: currentName)
self.session = Session(token: token)
self.refreshSession()
} catch { print(error) }
} else {
self.session = Session()
}
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UINavigationController? {
if let nav = base as? UINavigationController {
return nav
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
return moreNavigationController
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base?.navigationController
}
}
extension URL {
func getKeyVals() -> Dictionary<String, String>? {
var results = [String:String]()
let keyValues = self.query?.components(separatedBy: "&")
if (keyValues?.count)! > 0 {
for pair in keyValues! {
let kv = pair.components(separatedBy: "=")
if kv.count > 1 {
results.updateValue(kv[1], forKey: kv[0])
}
}
}
return results
}
}
| apache-2.0 | b7f03833ae0393d340be85f4faa0e7da | 44.49642 | 285 | 0.524681 | 6.246068 | false | false | false | false |
suzp1984/IOS-ApiDemo | ApiDemo-Swift/ApiDemo-Swift/MyVignetteFilter.swift | 1 | 1291 |
import UIKit
class MyVignetteFilter: CIFilter {
var inputImage : CIImage?
var inputPercentage : NSNumber? = 1.0
override var outputImage : CIImage? {
return self.makeOutputImage()
}
deinit {
// just making sure we are not leaking
print("farewell")
}
fileprivate func makeOutputImage () -> CIImage? {
guard let inputImage = self.inputImage else {return nil}
guard let inputPercentage = self.inputPercentage else {return nil}
let extent = inputImage.extent
let grad = CIFilter(name: "CIRadialGradient")!
let center = CIVector(x: extent.width/2.0, y: extent.height/2.0)
let smallerDimension = min(extent.width, extent.height)
let largerDimension = max(extent.width, extent.height)
grad.setValue(center, forKey:"inputCenter")
grad.setValue(smallerDimension/2.0 * CGFloat(inputPercentage), forKey:"inputRadius0")
grad.setValue(largerDimension/2.0, forKey:"inputRadius1")
let blend = CIFilter(name: "CIBlendWithMask")!
blend.setValue(inputImage, forKey: "inputImage")
blend.setValue(grad.outputImage, forKey: "inputMaskImage")
return blend.outputImage
}
}
| apache-2.0 | eece32d77b38f0243040b5bd98828271 | 30.487805 | 93 | 0.633617 | 4.578014 | false | false | false | false |
luceefer/TagFlowExample | TagFlowLayout/FlowLayout.swift | 1 | 1125 | //
// FlowLayout.swift
// TagFlowLayout
//
// Created by Diep Nguyen Hoang on 7/30/15.
// Copyright (c) 2015 CodenTrick. All rights reserved.
//
import UIKit
class FlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributesForElementsInRect = super.layoutAttributesForElements(in: rect)
var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()
var leftMargin: CGFloat = 0.0;
for attributes in attributesForElementsInRect! {
if (attributes.frame.origin.x == self.sectionInset.left) {
leftMargin = self.sectionInset.left
} else {
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = leftMargin
attributes.frame = newLeftAlignedFrame
}
leftMargin += attributes.frame.size.width + 8
newAttributesForElementsInRect.append(attributes)
}
return newAttributesForElementsInRect
}
}
| apache-2.0 | 5a50064d4ad8cbd96062c56082363b38 | 33.090909 | 103 | 0.652444 | 5.408654 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Ranking/UserRankingTagTableViewCell.swift | 1 | 1543 | //
// UserRankingTagTableViewCell.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 6/1/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class UserRankingTagTableViewCell: UITableViewCell {
@IBOutlet weak var imgAvatar : UIImageView?
@IBOutlet weak var lblFullName : UILabel?
@IBOutlet weak var lblLevel : UILabel?
@IBOutlet weak var lblNumberStars : UILabel?
var objUserEmployee = UserTagBE()
override func drawRect(rect: CGRect) {
OSPCrop.makeRoundView(self.imgAvatar!)
}
func updateData() -> Void {
self.lblFullName?.text = "\(self.objUserEmployee.user_first_name!) \(self.objUserEmployee.user_last_name!)"
self.lblLevel?.text = "Lvl. \(self.objUserEmployee.user_level!)"
self.lblNumberStars?.text = "\(self.objUserEmployee.user_num_stars!)"
if let url_photo = self.objUserEmployee.user_avatar{
if (url_photo != "") {
OSPImageDownloaded.descargarImagenEnURL(url_photo, paraImageView: self.imgAvatar, conPlaceHolder: nil) { (correct : Bool, nameImage : String!, image : UIImage!) in
if nameImage == url_photo {
self.imgAvatar?.image = image
}
}
} else {
self.imgAvatar!.image = UIImage(named: "ic_user.png")
}
} else {
self.imgAvatar!.image = UIImage(named: "ic_user.png")
}
}
} | mit | 476102a74e696e99347a31bba969a406 | 32.543478 | 179 | 0.586252 | 4.224658 | false | false | false | false |
lorentey/swift | test/SILGen/tuples.swift | 3 | 10817 |
// RUN: %target-swift-emit-silgen -module-name tuples %s | %FileCheck %s
public class C {}
public enum Foo {
case X(C, Int)
}
// <rdar://problem/16020428>
// CHECK-LABEL: sil hidden [ossa] @$s6tuples8matchFoo1xyAA0C0O_tF
func matchFoo(x x: Foo) {
switch x {
case .X(let x):
()
}
}
public protocol P { func foo() }
public struct A : P { public func foo() {} }
func make_int() -> Int { return 0 }
func make_p() -> P { return A() }
func make_xy() -> (x: Int, y: P) { return (make_int(), make_p()) }
// CHECK-LABEL: sil hidden [ossa] @$s6tuples17testShuffleOpaqueyyF
func testShuffleOpaque() {
// CHECK: [[X:%.*]] = alloc_box ${ var P }
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK: [[Y:%.*]] = alloc_box ${ var Int }
// CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]]
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack $P
// CHECK: [[T0:%.*]] = function_ref @$s6tuples7make_xySi1x_AA1P_p1ytyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[TMP]])
// CHECK-NEXT: copy_addr [take] [[TMP]] to [initialization] [[PBX]] : $*P
// CHECK-NEXT: store [[T1]] to [trivial] [[PBY]]
// CHECK-NEXT: dealloc_stack [[TMP]]
var (x,y) : (y:P, x:Int) = make_xy()
// CHECK-NEXT: [[PAIR:%.*]] = alloc_box ${ var (y: P, x: Int) }
// CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]]
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack $P
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples7make_xySi1x_AA1P_p1ytyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[TMP]])
// CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0
// CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1
// CHECK-NEXT: copy_addr [take] [[TMP]] to [initialization] [[PAIR_0]] : $*P
// CHECK-NEXT: store [[T1]] to [trivial] [[PAIR_1]]
// CHECK-NEXT: dealloc_stack [[TMP]]
var pair : (y:P, x:Int) = make_xy()
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack $P
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples7make_xySi1x_AA1P_p1ytyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[TMP]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBPAIR]] : $*(y: P, x: Int)
// CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 0
// CHECK-NEXT: copy_addr [take] [[TMP]] to [[PAIR_0]]
// CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 1
// CHECK-NEXT: assign [[T1]] to [[PAIR_1]]
// CHECK-NEXT: end_access [[WRITE]] : $*(y: P, x: Int)
// CHECK-NEXT: dealloc_stack [[TMP]]
pair = make_xy()
}
// CHECK-LABEL: testShuffleTuple
func testShuffleTuple() {
// CHECK: [[X:%.*]] = alloc_box ${ var P }
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK: [[Y:%.*]] = alloc_box ${ var Int }
// CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples8make_intSiyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]()
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack $P
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples6make_pAA1P_pyF
// CHECK-NEXT: apply [[T0]]([[TMP]])
// CHECK-NEXT: copy_addr [take] [[TMP]] to [initialization] [[PBX]]
// CHECK-NEXT: store [[T1]] to [trivial] [[PBY]]
// CHECK-NEXT: dealloc_stack [[TMP]]
var (x,y) : (y:P, x:Int) = (x: make_int(), y: make_p())
// CHECK-NEXT: [[PAIR:%.*]] = alloc_box ${ var (y: P, x: Int) }
// CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples8make_intSiyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]()
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack $P
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples6make_pAA1P_pyF
// CHECK-NEXT: apply [[T0]]([[TMP]])
// CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0
// CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1
// CHECK-NEXT: copy_addr [take] [[TMP]] to [initialization] [[PBX]]
// CHECK-NEXT: store [[T1]] to [trivial] [[PAIR_1]]
// CHECK-NEXT: dealloc_stack [[TMP]]
var pair : (y:P, x:Int) = (x: make_int(), y: make_p())
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples8make_intSiyF
// CHECK-NEXT: [[INT:%.*]] = apply [[T0]]()
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $P
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$s6tuples6make_pAA1P_pyF
// CHECK-NEXT: apply [[T0]]([[TEMP]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBPAIR]] : $*(y: P, x: Int)
// CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 0
// CHECK-NEXT: copy_addr [take] [[TEMP]] to [[PAIR_0]]
// CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 1
// CHECK-NEXT: assign [[INT]] to [[PAIR_1]]
// CHECK-NEXT: end_access [[WRITE]] : $*(y: P, x: Int)
// CHECK-NEXT: dealloc_stack [[TEMP]]
pair = (x: make_int(), y: make_p())
}
enum GenericEnum<T> {
case one(T)
static var callback: (T) -> Void { fatalError() }
}
// CHECK-LABEL: $s6tuples16testTupleUnsplatyyF
func testTupleUnsplat() {
// CHECK: debug_value [[X:%.+]] : $Int, let, name "x"
// CHECK: debug_value [[Y:%.+]] : $Int, let, name "y"
let x = 1, y = 2
// CHECK: [[TUPLE:%.+]] = tuple ([[X]] : $Int, [[Y]] : $Int)
// CHECK: enum $GenericEnum<(Int, Int)>, #GenericEnum.one!enumelt.1, [[TUPLE]]
_ = GenericEnum<(Int, Int)>.one((x, y))
// CHECK: [[THUNK:%.+]] = function_ref @$sSi_SitIegn_S2iIegyy_TR
// CHECK: [[REABSTRACTED:%.+]] = partial_apply [callee_guaranteed] [[THUNK]]({{%.+}})
// CHECK: [[BORROW:%.*]] = begin_borrow [[REABSTRACTED]]
// CHECK: apply [[BORROW]]([[X]], [[Y]])
_ = GenericEnum<(Int, Int)>.callback((x, y))
} // CHECK: end sil function '$s6tuples16testTupleUnsplatyyF'
// Make sure that we use a load_borrow instead of a load [take] when RValues are
// formed with isGuaranteed set.
extension P {
// CHECK-LABEL: sil [ossa] @$s6tuples1PPAAE12immutableUse5tupleyAA1CC5index_x5valuet_tFZ
// CHECK: bb0([[TUP0:%.*]] : @guaranteed $C, [[TUP1:%.*]] : $*Self
// Allocate space for the RValue.
// CHECK: [[RVALUE:%.*]] = alloc_stack $(index: C, value: Self), let, name "tuple"
//
// Initialize the RValue. (This is here to help pattern matching).
// CHECK: [[ZERO_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 0
// CHECK: [[TUP0_COPY:%.*]] = copy_value [[TUP0]]
// CHECK: store [[TUP0_COPY]] to [init] [[ZERO_ADDR]]
// CHECK: [[ONE_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 1
// CHECK: copy_addr [[TUP1]] to [initialization] [[ONE_ADDR]]
//
// What we are actually trying to check. Note that there is no actual use of
// LOADED_CLASS. This is b/c of the nature of the RValue we are working with.
// CHECK: [[ZERO_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 0
// CHECK: [[LOADED_CLASS:%.*]] = load_borrow [[ZERO_ADDR]]
// CHECK: [[ONE_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 1
// CHECK: apply {{.*}}([[ONE_ADDR]]) : $@convention(witness_method: P)
// CHECK: end_borrow [[LOADED_CLASS]]
// CHECK: destroy_addr [[RVALUE]]
// CHECK: dealloc_stack [[RVALUE]]
public static func immutableUse(tuple: (index: C, value: Self)) -> () {
return tuple.value.foo()
}
}
// CHECK-LABEL: sil [ossa] @$s6tuples15testTupleAssign1xySaySiGz_tF : $@convention(thin) (@inout Array<Int>) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*Array<Int>
// function_ref Array.subscript.modify
// CHECK: [[ACCESSOR:%.*]] = function_ref @$sSayxSiciM : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: ([[VALUE:%.*]], [[TOKEN:%.*]]) = begin_apply [[ACCESSOR]]<Int>(%{{.*}}, [[ACCESS]]) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: assign %{{.*}} to %{{.*}} : $*Int
// CHECK: end_apply [[TOKEN]]
// CHECK: end_access [[ACCESS]] : $*Array<Int>
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] %0 : $*Array<Int>
// function_ref Array.subscript.modify
// CHECK: [[ACCESSOR:%.*]] = function_ref @$sSayxSiciM : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: ([[VALUE:%.*]], [[TOKEN:%.*]]) = begin_apply [[ACCESSOR]]<Int>(%{{.*}}, [[ACCESS]]) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: assign %{{.*}} to %{{.*}} : $*Int
// CHECK: end_apply [[TOKEN]]
// CHECK: end_access [[ACCESS]] : $*Array<Int>
// CHECK-LABEL: } // end sil function '$s6tuples15testTupleAssign1xySaySiGz_tF'
public func testTupleAssign(x: inout [Int]) {
(x[0], x[1]) = (0, 1)
}
// CHECK-LABEL: sil [ossa] @$s6tuples16testTupleSubtype1x1y1zyAA1CC_SiSStF : $@convention(thin) (@guaranteed C, Int, @guaranteed String) -> () {
// CHECK: [[X:%.*]] = copy_value %0 : $C
// CHECK: [[Z:%.*]] = copy_value %2 : $String
// CHECK: [[INPUT:%.*]] = tuple $(x: C, y: Int, z: String) ([[X]], %1, [[Z]])
// CHECK: [[OUTPUT:%.*]] = alloc_stack $(y: Optional<Int>, z: Any, x: AnyObject)
// CHECK: [[INPUT_BORROW:%.*]] = begin_borrow [[INPUT]] : $(x: C, y: Int, z: String)
// CHECK: [[INPUT_COPY:%.*]] = copy_value [[INPUT_BORROW]] : $(x: C, y: Int, z: String)
// CHECK: ([[X:%.*]], [[Y:%.*]], [[Z:%.*]]) = destructure_tuple %12 : $(x: C, y: Int, z: String)
// CHECK: [[Y_ADDR:%.*]] = tuple_element_addr %10 : $*(y: Optional<Int>, z: Any, x: AnyObject), 0
// CHECK: [[Z_ADDR:%.*]] = tuple_element_addr %10 : $*(y: Optional<Int>, z: Any, x: AnyObject), 1
// CHECK: [[X_ADDR:%.*]] = tuple_element_addr %10 : $*(y: Optional<Int>, z: Any, x: AnyObject), 2
// CHECK: [[NEW_Y:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %14 : $Int
// CHECK: store [[NEW_Y]] to [trivial] [[Y_ADDR]] : $*Optional<Int>
// CHECK: [[NEW_Z:%.*]] = init_existential_addr [[Z_ADDR]] : $*Any, $String
// CHECK: store [[Z]] to [init] [[NEW_Z]] : $*String
// CHECK: [[NEW_X:%.*]] = init_existential_ref [[X]] : $C : $C, $AnyObject
// CHECK: store [[NEW_X]] to [init] [[X_ADDR]] : $*AnyObject
// CHECK: end_borrow [[INPUT_BORROW]] : $(x: C, y: Int, z: String)
// CHECK: destroy_addr [[OUTPUT]] : $*(y: Optional<Int>, z: Any, x: AnyObject)
// CHECK: dealloc_stack [[OUTPUT]] : $*(y: Optional<Int>, z: Any, x: AnyObject)
// CHECK: destroy_value [[INPUT]] : $(x: C, y: Int, z: String)
public func testTupleSubtype(x: C, y: Int, z: String) {
let input = (x: x, y: y, z: z)
let output: (y: Int?, z: Any, x: AnyObject) = input
}
| apache-2.0 | d741e92e3fedc9684bdd029f4d2c1ffb | 49.255814 | 187 | 0.559186 | 2.955416 | false | true | false | false |
shvets/TVSetKit | Sources/ios/BookmarksManager.swift | 1 | 2423 | import Foundation
import UIKit
open class BookmarksManager {
public var bookmarks: Bookmarks!
public init(_ bookmarks: Bookmarks) {
self.bookmarks = bookmarks
bookmarks.load()
}
@discardableResult open func addBookmark(item: MediaItem) throws -> Bool {
return bookmarks.addBookmark(item: item)
}
open func removeBookmark(item: MediaItem) throws -> Bool {
return bookmarks.removeBookmark(id: item.id!)
}
open func isBookmark(_ requestType: String) -> Bool {
return requestType != "History" && requestType == "Bookmarks"
}
open func handleBookmark(isBookmark: Bool, localizer: Localizer,
addCallback: @escaping () throws -> Void,
removeCallback: @escaping () throws -> Void) -> UIAlertController? {
var alert: UIAlertController?
if isBookmark {
alert = buildRemoveBookmarkController(removeCallback, localizer: localizer)
}
else {
alert = buildAddBookmarkController(addCallback, localizer: localizer)
}
return alert
}
func buildRemoveBookmarkController(_ callback: @escaping () throws -> Void, localizer: Localizer) -> UIAlertController {
let title = localizer.localize("Your Selection Will Be Removed")
let message = localizer.localize("Confirm Your Choice")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
do {
try callback()
}
catch {
print(error)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(cancelAction)
alertController.addAction(okAction)
return alertController
}
func buildAddBookmarkController(_ callback: @escaping () throws -> Void, localizer: Localizer) -> UIAlertController {
let title = localizer.localize("Your Selection Will Be Added")
let message = localizer.localize("Confirm Your Choice")
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
do {
try callback()
}
catch {
print(error)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(cancelAction)
alert.addAction(okAction)
return alert
}
}
| mit | efb5e8cb9b12d52ce512658e87f5ebac | 27.505882 | 122 | 0.669831 | 4.846 | false | false | false | false |
madbat/Surge | Surge.playground/Contents.swift | 1 | 776 | import Foundation
import Surge
import XCPlayground
// MARK: - Arithmetic
let n = [-1.0, 2.0, 3.0, 4.0, 5.0]
let sum = Surge.sum(n)
let a = [1.0, 3.0, 5.0, 7.0]
let b = [2.0, 4.0, 6.0, 8.0]
let product = Surge.mul(a, b)
// MARK: - Matrix
// ⎛ 1 1 ⎞ ⎛ 3 ⎞
// ⎢ ⎟ * B = ⎢ ⎟ C = ?
// ⎝ 1 -1 ⎠ ⎝ 1 ⎠
let A = Matrix([[1, 1], [1, -1]])
let C = Matrix([[3], [1]])
let B = inv(A) * C
// MARK: - FFT
func plot<T>(values: [T], title: String) {
for value in values {
XCPCaptureValue(title, value: value)
}
}
let count = 64
let frequency = 4.0
let amplitude = 3.0
let x = (0..<count).map { 2.0 * M_PI / Double(count) * Double($0) * frequency }
plot(sin(x), title: "Sine Wave")
plot(fft(sin(x)), title: "FFT")
| mit | ee9ad9b14e0f05ed32617fb917f7ac29 | 17.8 | 79 | 0.515957 | 2.271903 | false | false | false | false |
michaelvu812/MVPaginationTable | MVPaginationTable/AppDelegate.swift | 1 | 7333 | //
// AppDelegate.swift
// MVPaginationTable
//
// Created by Michael on 17/6/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
self.window!.backgroundColor = UIColor.whiteColor()
let viewController = ViewController()
self.window!.rootViewController = viewController
self.window!.makeKeyAndVisible()
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("MVPaginationTable", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MVPaginationTable.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
| mit | a758d55ea8bf506d0909756e086255a8 | 51.378571 | 285 | 0.702032 | 6.162185 | false | false | false | false |
bryancmiller/rockandmarty | Text Adventure/Text Adventure/Place.swift | 1 | 440 | //
// Place.swift
// Text Adventure
//
// Created by Bryan Miller on 5/1/17.
// Copyright © 2017 Bryan Miller. All rights reserved.
//
import UIKit
class Place {
var name: String = ""
var description: String = ""
var item: String = ""
init() {}
init(name: String, description: String, item: String) {
self.name = name
self.description = description
self.item = item
}
}
| apache-2.0 | 4ddd4387cd66fb5962fa383c189d70d8 | 17.291667 | 59 | 0.574032 | 3.752137 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit | Sources/BSWInterfaceKit/Extensions/NSAttributedStrings+Utilities.swift | 1 | 8866 | //
// Created by Pierluigi Cifani on 01/08/16.
// Copyright © 2018 TheLeftBit SL. All rights reserved.
//
#if canImport(UIKit)
import UIKit
public enum AttributedStringSpacing {
case simple
case double
fileprivate var attString: NSAttributedString {
switch self {
case .simple:
return NSAttributedString(string: "\n")
case .double:
return NSAttributedString(string: "\n\n")
}
}
}
public extension Collection where Iterator.Element : NSAttributedString {
func joinedStrings(spacing: AttributedStringSpacing = .simple) -> NSAttributedString {
//This makes me puke, but hey, choose your battles
var extraDetailsString: NSMutableAttributedString? = nil
self.forEach { (string) in
if let extraDetailsString_ = extraDetailsString {
let sumString = extraDetailsString_ + spacing.attString + string
extraDetailsString = sumString.mutableCopy() as? NSMutableAttributedString
} else {
extraDetailsString = string.mutableCopy() as? NSMutableAttributedString
}
}
return extraDetailsString!
}
}
// concatenate attributed strings
public func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
let result = NSMutableAttributedString()
result.append(left)
result.append(right)
return result
}
public extension NSAttributedString {
convenience init?(html: String) {
guard let data = html.data(using: .utf16, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf16.rawValue], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
func modifyingFont(_ newFont: UIFont, onSubstring: String? = nil) -> NSAttributedString {
let string = self.mutableCopy() as! NSMutableAttributedString
let range: NSRange = {
if let substring = onSubstring, let nsRange = nsRangeFor(substring: substring) { return nsRange }
else { return NSRange(location: 0, length: string.length) }
}()
string.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired) { (value, range, _) in
guard let font = value[NSAttributedString.Key.font] as? UIFont else { return }
let finalNewFont = font.isBold ? newFont.bolded() : newFont
string.addAttribute(.font, value: finalNewFont, range: range)
}
return string
}
func modifyingColor(_ newColor: UIColor, onSubstring: String? = nil) -> NSAttributedString {
let string = self.mutableCopy() as! NSMutableAttributedString
let range: NSRange = {
if let substring = onSubstring, let nsRange = nsRangeFor(substring: substring) { return nsRange }
else { return NSRange(location: 0, length: string.length) }
}()
string.removeAttribute(.foregroundColor, range: range)
string.addAttribute(.foregroundColor, value: newColor, range: range)
return string
}
func modifyingBackgroundColor(_ newColor: UIColor, onSubstring: String? = nil) -> NSAttributedString {
let string = self.mutableCopy() as! NSMutableAttributedString
let range: NSRange = {
if let substring = onSubstring, let nsRange = nsRangeFor(substring: substring) { return nsRange }
else { return NSRange(location: 0, length: string.length) }
}()
string.removeAttribute(.backgroundColor, range: range)
string.addAttribute(.backgroundColor, value: newColor, range: range)
return string
}
var bolded: NSAttributedString {
return bolding(substring: self.string)
}
func bolding(substring: String) -> NSAttributedString {
guard let nsRange = nsRangeFor(substring: substring) else {
return self
}
guard let font = self.attributes(at: 0, longestEffectiveRange: nil, in: nsRange)[.font] as? UIFont else {
return self
}
return modifyingFont(font.bolded(), onSubstring: substring)
}
func settingKern(_ kern: CGFloat) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
mutableCopy.setKern(kern)
return mutableCopy
}
func settingParagraphStyle(_ style: NSParagraphStyle) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
mutableCopy.setParagraphStyle(style)
return mutableCopy
}
func settingParagraphStyle(_ style: (NSMutableParagraphStyle) -> ()) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
let p = NSMutableParagraphStyle()
style(p)
mutableCopy.setParagraphStyle(p)
return mutableCopy
}
func settingLineSpacing(_ lineSpacing: CGFloat) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
mutableCopy.setLineSpacing(lineSpacing)
return mutableCopy
}
func settingLineHeight(_ lineHeight: CGFloat) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
mutableCopy.setLineHeight(lineHeight)
return mutableCopy
}
func settingLineHeightMultiplier(_ multiplier: CGFloat) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
mutableCopy.setLineHeightMultiplier(multiplier)
return mutableCopy
}
func addingLink(onSubstring substring: String, linkURL: URL, linkColor: UIColor?, isUnderlined: Bool = false) -> NSAttributedString {
let mutableCopy = self.mutableCopy() as! NSMutableAttributedString
var linkCustomAttributes: [NSAttributedString.Key : Any] = [
.attachment: linkURL
]
if let linkColor = linkColor {
linkCustomAttributes[.foregroundColor] = linkColor
}
if isUnderlined {
linkCustomAttributes[.underlineColor] = linkColor
linkCustomAttributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
}
mutableCopy.addAttributes(onSubstring: substring, attrs: linkCustomAttributes)
return mutableCopy
}
}
public extension NSAttributedString {
///https://stackoverflow.com/a/45161058
convenience init(withIcon iconImage: UIImage, forFont titleFont: UIFont) {
let icon = NSTextAttachment()
icon.bounds = CGRect(x: 0, y: (titleFont.capHeight - iconImage.size.height).rounded() / 2, width: iconImage.size.width, height: iconImage.size.height)
icon.image = iconImage
self.init(attachment: icon)
}
}
public extension NSAttributedString {
func nsRangeFor(substring: String) -> NSRange? {
guard let range = self.string.range(of: substring) else { return nil }
let lowerBound = range.lowerBound.utf16Offset(in: self.string)
let upperBound = range.upperBound.utf16Offset(in: self.string)
return NSRange(location: lowerBound, length: upperBound - lowerBound)
}
}
public extension NSMutableAttributedString {
func addAttributes(onSubstring substring: String, attrs: [NSAttributedString.Key : Any]) {
guard let range = self.nsRangeFor(substring: substring) else { fatalError() }
self.addAttributes(attrs, range: range)
}
func setKern(_ kern: CGFloat) {
self.addAttributes([.kern: kern], range: NSRange(location: 0, length: self.length))
}
func setParagraphStyle(_ style: NSParagraphStyle) {
self.addAttributes([.paragraphStyle: style], range: NSRange(location: 0, length: self.length))
}
func setLineSpacing(_ lineSpacing: CGFloat) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineBreakMode = .byTruncatingTail //We always want this
setParagraphStyle(paragraphStyle)
}
func setLineHeight(_ lineHeight: CGFloat) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.lineBreakMode = .byTruncatingTail //We always want this
setParagraphStyle(paragraphStyle)
}
func setLineHeightMultiplier(_ multiplier: CGFloat) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = multiplier
setParagraphStyle(paragraphStyle)
}
}
#endif
| mit | ad2e04dce98ef2d018b49eb8f2603c5b | 37.71179 | 220 | 0.674112 | 5.362976 | false | false | false | false |
OpenStack-mobile/OAuth2-Swift | Sources/OAuth2/ImplicitGrant.swift | 1 | 3764 | //
// ImplicitGrant.swift
// OAuth2
//
// Created by Alsey Coleman Miller on 12/16/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
import SwiftFoundation
/// [4.2. Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2)
///
/// The implicit grant type is used to obtain access tokens (it does not
/// support the issuance of refresh tokens) and is optimized for public
/// clients known to operate a particular redirection URI. These clients
/// are typically implemented in a browser using a scripting language
/// such as JavaScript.
///
/// Since this is a redirection-based flow, the client must be capable of
/// interacting with the resource owner's user-agent (typically a web
/// browser) and capable of receiving incoming requests (via redirection)
/// from the authorization server.
///
/// Unlike the authorization code grant type, in which the client makes
/// separate requests for authorization and for an access token, the
/// client receives the access token as the result of the authorization
/// request.
///
/// The implicit grant type does not include client authentication, and
/// relies on the presence of the resource owner and the registration of
/// the redirection URI. Because the access token is encoded into the
/// redirection URI, it may be exposed to the resource owner and other
/// applications residing on the same device.
public struct ImplicitGrant {
/// [4.2.1. Authorization Request](https://tools.ietf.org/html/rfc6749#section-4.2.1)
public typealias Request = AuthorizationRequest
/// [4.2.2. Access Token Response](https://tools.ietf.org/html/rfc6749#section-4.2.2)
///
/// The authorization server MUST NOT issue a refresh token.
///
/// For example, the authorization server redirects the user-agent by
/// sending the following HTTP response:
///
/// ```
/// HTTP/1.1 302 Found
/// Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600
/// ```
public struct Response: AccessTokenResponse, JSONDecodable {
public enum Parameter: String {
case scope, state
}
public let accessToken: String
public let tokenType: String
public let expires: TimeInterval?
public let scope: String?
public let state: String?
public init?(urlResponse: HTTP.Response) {
guard urlResponse.statusCode == HTTP.StatusCode.Found.rawValue,
let jsonString = String(UTF8Data: urlResponse.body),
let json = JSON.Value(string: jsonString)
else { return nil }
self.init(JSONValue: json)
}
public init?(JSONValue: JSON.Value) {
guard let JSONObject = JSONValue.objectValue,
let accessToken = JSONObject[AccessTokenResponseParameter.access_token.rawValue]?.stringValue,
let tokenType = JSONObject[AccessTokenResponseParameter.token_type.rawValue]?.stringValue
else { return nil }
self.accessToken = accessToken
self.tokenType = tokenType
if let expires = JSONObject[AccessTokenResponseParameter.expires_in.rawValue]?.integerValue {
self.expires = TimeInterval(expires)
} else {
self.expires = nil
}
self.scope = JSONObject[Parameter.scope.rawValue]?.stringValue
self.state = JSONObject[Parameter.state.rawValue]?.stringValue
}
}
}
| mit | 950686986ec42e0d8724f770d31aa6df | 36.63 | 120 | 0.634334 | 4.893368 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Trivial - 不需要看的题目/412_Fizz Buzz.swift | 1 | 1059 | // 412_Fizz Buzz
// https://leetcode.com/problems/fizz-buzz/
//
// Created by Honghao Zhang on 10/5/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Write a program that outputs the string representation of numbers from 1 to n.
//
//But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
//
//Example:
//
//n = 15,
//
//Return:
//[
// "1",
// "2",
// "Fizz",
// "4",
// "Buzz",
// "Fizz",
// "7",
// "8",
// "Fizz",
// "Buzz",
// "11",
// "Fizz",
// "13",
// "14",
// "FizzBuzz"
//]
//
import Foundation
class Num412 {
func fizzBuzz(_ n: Int) -> [String] {
return Array(1...n).map {
if $0 % 3 == 0, $0 % 5 == 0 {
return "FizzBuzz"
}
else if $0 % 3 == 0 {
return "Fizz"
}
else if $0 % 5 == 0 {
return "Buzz"
}
else {
return String($0)
}
}
}
}
| mit | efc5d4571da8271b51401a0621dcbbc0 | 18.018182 | 193 | 0.512428 | 3.113095 | false | false | false | false |
s-aska/Justaway-for-iOS | Justaway/JustawayEx.swift | 1 | 1818 | //
// JustawayEx.swift
// Justaway
//
// Created by Shinichiro Aska on 4/7/16.
// Copyright © 2016 Shinichiro Aska. All rights reserved.
//
import UIKit
import SafariServices
// MARK: - SafariExURLHandler
class SafariExURLHandler: NSObject {
static var oAuthViewController: SFSafariViewController?
static var successCallback: ((_ account: Account) -> ())?
class func open(_ successCallback: ((_ account: Account) -> ())? = nil) {
SafariExURLHandler.oAuthViewController = Safari.openURL(URL(string: "https://justaway.info/signin/")!)
SafariExURLHandler.successCallback = successCallback
}
class func callback(_ url: URL) {
let exToken = url.lastPathComponent
let array = exToken.characters.split(separator: "-", maxSplits: 2, omittingEmptySubsequences: true)
if array.count != 2 {
return
}
let userId = String(array[0])
guard let accountSettings = AccountSettingsStore.get() else {
return
}
if let account = accountSettings.find(userId) {
let newAccount = Account(account: account, exToken: exToken)
let newSettings = accountSettings.merge([newAccount])
AccountSettingsStore.save(newSettings)
SafariExURLHandler.oAuthViewController?.dismiss(animated: true, completion: {
SafariExURLHandler.successCallback?(newAccount)
MessageAlert.show("Notification started", message: "Notification you will receive when you are not running Justaway.")
})
} else {
SafariExURLHandler.oAuthViewController?.dismiss(animated: true, completion: {
ErrorAlert.show("Missing Account", message: "Please refer to the first account registration.")
})
}
}
}
| mit | 2cc32e4f8c899cc27f78189171159cbf | 36.854167 | 134 | 0.651624 | 5.221264 | false | false | false | false |
anas10/Monumap | Monumap/Wireframes/MapWireframe.swift | 1 | 1110 | //
// MapWireframe.swift
// Monumap
//
// Created by Anas Ait Ali on 12/03/2017.
// Copyright © 2017 Anas Ait Ali. All rights reserved.
//
import UIKit
typealias MapViewModelConstructorType = (MapViewController) -> (MapViewModel)
protocol MapWireframeType {
var storyboard : UIStoryboard! { get }
var provider: Networking { get }
init(storyboard: UIStoryboard, provider: Networking)
func instantiateInitialViewController(dataManager: DataManager) -> MapViewController
}
class MapWireframe: MapWireframeType {
let storyboard: UIStoryboard!
let provider: Networking
required init(storyboard: UIStoryboard = UIStoryboard.main(), provider: Networking) {
self.storyboard = storyboard
self.provider = provider
}
func instantiateInitialViewController(dataManager: DataManager) -> MapViewController {
let vc = self.storyboard.viewControllerWithID(.mapViewControllerID) as! MapViewController
vc.viewModelConstructor = { _ in
MapViewModel(provider: self.provider, dataManager: dataManager)
}
return vc
}
}
| apache-2.0 | fe05951b4dfad6e332d28380773e8ea9 | 27.435897 | 97 | 0.715059 | 4.928889 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/GraphView/GraphLayout.swift | 1 | 6681 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
/// Provides an ordered array of GraphDataLayer objects.
class GraphLayout {
let graphViewSize: CGSize
let graphCenterTime: Date
/// Time at x-origin of graph
let graphStartTime: Date
/// Time is displayed in the timezone at this offset
var timezoneOffsetSecs: Int = 0
/// Time interval covered by the entire graph.
let graphTimeInterval: TimeInterval
/// Starts at size of graph view, but varies with zoom.
var cellViewSize: CGSize
/// Time interval covered by one graph tile.
let cellTimeInterval: TimeInterval
///
var graphCellsInCollection: Int
var graphCellFocusInCollection: Int
/// Use this init to create a graph that starts at a point in time.
init(viewSize: CGSize, startTime: Date, timeIntervalPerTile: TimeInterval, numberOfTiles: Int, tilesInView: CGFloat, tzOffsetSecs: Int) {
self.graphStartTime = startTime
self.graphViewSize = viewSize
self.cellTimeInterval = timeIntervalPerTile
self.graphCellsInCollection = numberOfTiles
self.graphCellFocusInCollection = numberOfTiles / 2
self.graphTimeInterval = timeIntervalPerTile * TimeInterval(numberOfTiles)
self.cellViewSize = CGSize(width: viewSize.width/tilesInView, height: viewSize.height)
self.graphCenterTime = startTime.addingTimeInterval(self.graphTimeInterval/2.0)
self.timezoneOffsetSecs = tzOffsetSecs
}
/// Use this init to create a graph centered around a point in time.
convenience init(viewSize: CGSize, centerTime: Date, startPixelsPerHour: Int, numberOfTiles: Int, tzOffsetSecs: Int) {
let cellViewSize = viewSize
let cellTI = TimeInterval(cellViewSize.width * 3600.0/CGFloat(startPixelsPerHour))
let graphTI = cellTI * TimeInterval(numberOfTiles)
let startTime = centerTime.addingTimeInterval(-graphTI/2.0)
self.init(viewSize: viewSize, startTime: startTime, timeIntervalPerTile: cellTI, numberOfTiles: numberOfTiles, tilesInView: 1, tzOffsetSecs: tzOffsetSecs)
}
/// Call as graph is zoomed in or out!
func updateCellViewSize(_ newSize: CGSize) {
self.cellViewSize = newSize
}
// Override in configure()!
//
// Graph sizing/tiling parameters
//
var zoomIncrement: CGFloat = 0.8
// Place x-axis ticks every 8 hours down to every 15 minutes, depending upon the zoom level
var xAxisLabelTickTimes: [TimeInterval] = [15*60, 30*60, 60*60, 2*60*60, 4*60*60, 8*60*60]
var curXAxisLabelTickTiming: TimeInterval = 60*60
var useRelativeTimes: Bool = false
let kMaxPixelsPerTick: CGFloat = 90
func figureXAxisTickTiming() {
// We are trying to have about 70-80 pixels per tick...
let maxTickIndex = xAxisLabelTickTimes.count - 1
let secondsPerPixel = CGFloat(cellTimeInterval) / cellViewSize.width
let secondsInGraphView = secondsPerPixel * graphViewSize.width
var result: TimeInterval = xAxisLabelTickTimes[0]
for index in 0...maxTickIndex {
let timePerTick = xAxisLabelTickTimes[index]
let ticksInView = secondsInGraphView / CGFloat(timePerTick)
let pixelsPerTick = graphViewSize.width / ticksInView
if pixelsPerTick > kMaxPixelsPerTick {
break
}
result = timePerTick
}
if curXAxisLabelTickTiming != result {
curXAxisLabelTickTiming = result
NSLog("New x-axis tick time interval = \(result)")
}
}
/// Somewhat arbitrary max cell width.
func zoomInMaxCellWidth() -> CGFloat {
return min((4 * graphViewSize.width), 2000.0)
}
/// Cells need to at least cover the view width.
func zoomOutMinCellWidth() -> CGFloat {
return graphViewSize.width / CGFloat(graphCellsInCollection)
}
//
// Header and background configuration
//
var headerHeight: CGFloat = 32.0
var backgroundColor: UIColor = UIColor.gray
//
// Y-axis configuration
//
var yAxisLineLeftMargin: CGFloat = 20.0
var yAxisLineRightMargin: CGFloat = 10.0
var yAxisLineColor: UIColor = UIColor.black
var yAxisValuesWithLines: [Int] = []
// left side labels, corresponding to yAxisRange and yAxisBase
var yAxisValuesWithLabels: [Int] = []
var yAxisRange: CGFloat = 0.0
var yAxisBase: CGFloat = 0.0
var yAxisPixels: CGFloat = 0.0
// right side labels can have a different range and base
var yAxisValuesWithRightEdgeLabels: [Int] = []
var yAxisRightRange: CGFloat = 0.0
var yAxisRightBase: CGFloat = 0.0
//
// Y-axis and X-axis configuration
//
var axesLabelTextColor: UIColor = UIColor.black
var axesLabelTextFont: UIFont = UIFont.systemFont(ofSize: 12.0)
var axesLeftLabelTextColor: UIColor = UIColor.black
var axesRightLabelTextColor: UIColor = UIColor.black
//
// X-axis configuration
//
var hourMarkerStrokeColor = UIColor.black
var largestXAxisDateWidth: CGFloat = 30.0
var xLabelRegularFont = UIFont.systemFont(ofSize: 9.0)
var xLabelLightFont = UIFont.systemFont(ofSize: 8.0)
//
// Methods to override!
//
func graphUtilsForGraphView() -> GraphingUtils {
return GraphingUtils(layout: self, timeIntervalForView: self.graphTimeInterval, startTime: self.graphStartTime, viewSize: self.graphViewSize)
}
func graphUtilsForTimeInterval(_ timeIntervalForView: TimeInterval, startTime: Date) -> GraphingUtils {
return GraphingUtils(layout: self, timeIntervalForView: timeIntervalForView, startTime: startTime, viewSize: self.cellViewSize)
}
func configureGraph() {
}
/// Returns the various layers used to compose the graph, other than the fixed background, and X-axis time values.
func graphLayers(_ viewSize: CGSize, timeIntervalForView: TimeInterval, startTime: Date, tileIndex: Int) -> [GraphDataLayer] {
return []
}
}
| bsd-2-clause | 1668c6d240d20d22110021be8af1185e | 38.767857 | 162 | 0.693758 | 4.626731 | false | false | false | false |
ps2/rileylink_ios | RileyLink/View Controllers/MainViewController.swift | 1 | 10704 | //
// MainViewController.swift
// RileyLink
//
// Created by Pete Schwamb on 5/11/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import UIKit
import SwiftUI
import MinimedKit
import MinimedKitUI
import RileyLinkBLEKit
import RileyLinkKit
import RileyLinkKitUI
import LoopKit
import LoopKitUI
import OmniKitUI
class MainViewController: RileyLinkSettingsViewController {
let deviceDataManager: DeviceDataManager
let insulinTintColor: Color
let guidanceColors: GuidanceColors
init(deviceDataManager: DeviceDataManager, insulinTintColor: Color, guidanceColors: GuidanceColors) {
self.deviceDataManager = deviceDataManager
self.insulinTintColor = insulinTintColor
self.guidanceColors = guidanceColors
let rileyLinkPumpManager = RileyLinkPumpManager(rileyLinkDeviceProvider: deviceDataManager.rileyLinkConnectionManager.deviceProvider, rileyLinkConnectionManager: deviceDataManager.rileyLinkConnectionManager)
super.init(rileyLinkPumpManager: rileyLinkPumpManager, devicesSectionIndex: Section.rileyLinks.rawValue, style: .grouped)
self.title = LocalizedString("RileyLink Testing", comment: "Title for RileyLink Testing main view controller")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.white
tableView.separatorStyle = .none
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 55
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
tableView.register(SettingsImageTableViewCell.self, forCellReuseIdentifier: SettingsImageTableViewCell.className)
let rlImage = UIImage(named: "RileyLink", in: Bundle.main, compatibleWith: tableView.traitCollection)
let imageView = UIImageView(image: rlImage)
imageView.tintColor = UIColor.white
imageView.contentMode = .center
imageView.frame.size.height += 30 // feels right
imageView.backgroundColor = UIColor(named: "RileyLink Tint", in: Bundle.main, compatibleWith: tableView.traitCollection)
tableView.tableHeaderView = imageView
tableView.register(RileyLinkDeviceTableViewCell.self, forCellReuseIdentifier: RileyLinkDeviceTableViewCell.className)
NotificationCenter.default.addObserver(self, selector: #selector(deviceConnectionStateDidChange), name: .DeviceConnectionStateDidChange, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
// Manually invoke the delegate for rows deselecting on appear
for indexPath in tableView.indexPathsForSelectedRows ?? [] {
_ = tableView(tableView, willDeselectRowAt: indexPath)
}
super.viewWillAppear(animated)
}
fileprivate enum Section: Int, CaseCountable {
case rileyLinks = 0
case pump
}
fileprivate enum PumpActionRow: Int, CaseCountable {
case addMinimedPump = 0
case setupOmnipod
}
weak var rileyLinkManager: RileyLinkBluetoothDeviceProvider!
@objc private func deviceConnectionStateDidChange() {
DispatchQueue.main.async {
self.tableView.reloadSections(IndexSet([Section.pump.rawValue]), with: .none)
}
}
private var shouldAllowAddingPump: Bool {
return rileyLinkManager.connectingCount > 0
}
// MARK: Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .rileyLinks:
return super.tableView(tableView, numberOfRowsInSection: section)
case .pump:
if let _ = deviceDataManager.pumpManager {
return 1
} else {
return PumpActionRow.count
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
switch(Section(rawValue: indexPath.section)!) {
case .rileyLinks:
return super.tableView(tableView, cellForRowAt: indexPath)
case .pump:
if let pumpManager = deviceDataManager.pumpManager {
cell = tableView.dequeueReusableCell(withIdentifier: SettingsImageTableViewCell.className, for: indexPath)
cell.imageView?.image = pumpManager.smallImage
cell.textLabel?.text = pumpManager.localizedTitle
cell.detailTextLabel?.text = nil
cell.accessoryType = .disclosureIndicator
} else {
switch(PumpActionRow(rawValue: indexPath.row)!) {
case .addMinimedPump:
cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath)
let textButtonCell = cell as? TextButtonTableViewCell
textButtonCell?.isEnabled = shouldAllowAddingPump
textButtonCell?.isUserInteractionEnabled = shouldAllowAddingPump
cell.textLabel?.text = LocalizedString("Add Minimed Pump", comment: "Title text for button to set up a new minimed pump")
case .setupOmnipod:
cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath)
let textButtonCell = cell as? TextButtonTableViewCell
textButtonCell?.isEnabled = shouldAllowAddingPump
textButtonCell?.isUserInteractionEnabled = shouldAllowAddingPump
cell.textLabel?.text = LocalizedString("Setup Omnipod", comment: "Title text for button to set up omnipod")
}
}
}
return cell
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .rileyLinks:
return super.tableView(tableView, titleForHeaderInSection: section)
case .pump:
return LocalizedString("Pumps", comment: "Title text for section listing configured pumps")
}
}
public override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch Section(rawValue: section)! {
case .rileyLinks:
return super.tableView(tableView, viewForHeaderInSection: section)
case .pump:
return nil
}
}
public override func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return devicesDataSource.tableView(tableView, estimatedHeightForHeaderInSection: section)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch Section(rawValue: indexPath.section)! {
case .rileyLinks:
let device = devicesDataSource.devices[indexPath.row]
let vc = RileyLinkDeviceTableViewController(device: device, batteryAlertLevel: nil, batteryAlertLevelChanged: nil)
show(vc, sender: indexPath)
case .pump:
if let pumpManager = deviceDataManager.pumpManager {
var settings = pumpManager.settingsViewController(insulinTintColor: insulinTintColor, guidanceColors: guidanceColors)
settings.completionDelegate = self
present(settings, animated: true)
} else {
var setupViewController: UIViewController & PumpManagerOnboarding & CompletionNotifying
switch PumpActionRow(rawValue: indexPath.row)! {
case .addMinimedPump:
setupViewController = UIStoryboard(name: "MinimedPumpManager", bundle: Bundle(for: MinimedPumpManagerSetupViewController.self)).instantiateViewController(withIdentifier: "DevelopmentPumpSetup") as! MinimedPumpManagerSetupViewController
case .setupOmnipod:
setupViewController = UIStoryboard(name: "OmnipodPumpManager", bundle: Bundle(for: OmnipodPumpManagerSetupViewController.self)).instantiateViewController(withIdentifier: "DevelopmentPumpSetup") as! OmnipodPumpManagerSetupViewController
}
if let rileyLinkManagerViewController = setupViewController as? RileyLinkManagerSetupViewController {
rileyLinkManagerViewController.rileyLinkPumpManager = RileyLinkPumpManager(rileyLinkDeviceProvider: deviceDataManager.rileyLinkConnectionManager.deviceProvider)
}
setupViewController.setupDelegate = self
setupViewController.completionDelegate = self
present(setupViewController, animated: true, completion: nil)
}
}
}
override func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
switch Section(rawValue: indexPath.section)! {
case .rileyLinks:
break
case .pump:
tableView.reloadSections(IndexSet([Section.pump.rawValue]), with: .none)
}
return indexPath
}
}
extension MainViewController: CompletionDelegate {
func completionNotifyingDidComplete(_ object: CompletionNotifying) {
if let vc = object as? UIViewController, presentedViewController === vc {
dismiss(animated: true, completion: nil)
}
}
}
extension MainViewController: PumpManagerCreateDelegate {
func pumpManagerOnboarding(_ notifying: PumpManagerCreateNotifying, didCreatePumpManager pumpManager: PumpManagerUI) {
deviceDataManager.pumpManager = pumpManager
}
}
extension MainViewController: PumpManagerOnboardingDelegate {
func pumpManagerOnboarding(_ notifying: PumpManagerOnboarding, didOnboardPumpManager pumpManager: PumpManagerUI, withSettings settings: PumpManagerSetupSettings) {
show(pumpManager.settingsViewController(insulinTintColor: insulinTintColor, guidanceColors: guidanceColors), sender: nil)
tableView.reloadSections(IndexSet([Section.pump.rawValue]), with: .none)
}
}
| mit | 72832bd0caece20aa23e39cb84dcf120 | 44.544681 | 255 | 0.688779 | 6.060589 | false | false | false | false |
huangboju/HYAlertController | Carthage/Checkouts/SnapKit/Source/ConstraintMakerRelatable.swift | 1 | 5131 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerRelatable {
internal let description: ConstraintDescription
internal init(_ description: ConstraintDescription) {
self.description = description
}
internal func relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable {
let related: ConstraintItem
let constant: ConstraintConstantTarget
if let other = other as? ConstraintItem {
guard other.attributes == ConstraintAttributes.none ||
other.attributes.layoutAttributes.count <= 1 ||
other.attributes.layoutAttributes == self.description.attributes.layoutAttributes ||
other.attributes == .edges && self.description.attributes == .margins ||
other.attributes == .margins && self.description.attributes == .edges else {
fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))")
}
related = other
constant = 0.0
} else if let other = other as? ConstraintView {
related = ConstraintItem(target: other, attributes: ConstraintAttributes.none)
constant = 0.0
} else if let other = other as? ConstraintConstantTarget {
related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none)
constant = other
} else {
fatalError("Invalid constraint. (\(file), \(line))")
}
let editable = ConstraintMakerEditable(self.description)
editable.description.sourceLocation = (file, line)
editable.description.relation = relation
editable.description.related = related
editable.description.constant = constant
return editable
}
@discardableResult
public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
@discardableResult
public func equalToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.item.superview else {
fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.")
}
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
@discardableResult
public func lessThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line)
}
@discardableResult
public func lessThanOrEqualToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.item.superview else {
fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.")
}
return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line)
}
@discardableResult
public func greaterThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line)
}
@discardableResult
public func greaterThanOrEqualToSuperview(_ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable {
guard let other = self.description.item.superview else {
fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.")
}
return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line)
}
}
| mit | 9fa2b854d4dff2e479ad2093264b6ae4 | 46.073394 | 148 | 0.690704 | 5.030392 | false | false | false | false |
cubixlabs/SocialGIST | Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUINavigationItem.swift | 1 | 2021 | //
// BaseUINavigationItem.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/07/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUINavigationItem is a subclass of UINavigationItem and implements BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUINavigationItem: UINavigationItem, BaseView {
//MARK: - Properties
private var _titleKey:String?;
/// Overriden title property to set title from SyncEngine (Hint '#' prefix).
override open var title: String? {
get {
return super.title;
}
set {
if let key:String = newValue , key.hasPrefix("#") == true {
_titleKey = key; // holding key for using later
super.title = SyncedText.text(forKey: key);
} else {
super.title = newValue;
}
}
} //P.E.
//MARK: - Constructors
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter title: Title of Navigation Item
public override init(title: String) {
super.init(title: title);
} //F.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
} //F.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
open override func awakeFromNib() {
super.awakeFromNib();
self.updateView();
}
//MARK: - Methods
/// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed.
func updateView() {
if let txt:String = self.title , txt.hasPrefix("#") == true {
self.title = txt; // Assigning again to set value from synced data
} else if _titleKey != nil {
self.title = _titleKey;
}
} //F.E.
} //CLS END
| gpl-3.0 | 184c6987a17d022aa245965e22e4fb9c | 28.705882 | 140 | 0.585149 | 4.764151 | false | false | false | false |
mrchenhao/VPNOn | VPNOnData/VPNDataManager+VPN.swift | 2 | 6244 | //
// VPNDataManager+VPN.swift
// VPN On
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import CoreData
import VPNOnKit
extension VPNDataManager
{
func allVPN() -> [VPN]
{
var vpns = [VPN]()
var request = NSFetchRequest(entityName: "VPN")
let sortByTitle = NSSortDescriptor(key: "title", ascending: true)
let sortByServer = NSSortDescriptor(key: "server", ascending: true)
let sortByType = NSSortDescriptor(key: "ikev2", ascending: false)
request.sortDescriptors = [sortByTitle, sortByServer, sortByType]
if let moc = managedObjectContext {
if let results = moc.executeFetchRequest(request, error: nil) as [VPN]? {
for vpn in results {
if vpn.deleted {
continue
}
vpns.append(vpn)
}
}
}
return vpns
}
func createVPN(
title: String,
server: String,
account: String,
password: String,
group: String,
secret: String,
alwaysOn: Bool = true,
ikev2: Bool = false,
certificateURL: String?,
certificate: NSData?
) -> VPN?
{
let entity = NSEntityDescription.entityForName("VPN", inManagedObjectContext: managedObjectContext!)
let vpn = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!) as VPN
vpn.title = title
vpn.server = server
vpn.account = account
vpn.group = group
vpn.alwaysOn = alwaysOn
vpn.ikev2 = ikev2
vpn.certificateURL = certificateURL
var error: NSError?
if !managedObjectContext!.save(&error) {
println("Could not save VPN \(error), \(error?.userInfo)")
} else {
saveContext()
if !vpn.objectID.temporaryID {
VPNKeychainWrapper.setPassword(password, forVPNID: vpn.ID)
VPNKeychainWrapper.setSecret(secret, forVPNID: vpn.ID)
VPNKeychainWrapper.setCertificate(certificate, forVPNID: vpn.ID)
if allVPN().count == 1 {
VPNManager.sharedManager.activatedVPNID = vpn.ID
}
return vpn
}
}
return .None
}
func deleteVPN(vpn:VPN)
{
let objectID = vpn.objectID
let ID = "\(vpn.ID)"
VPNKeychainWrapper.destoryKeyForVPNID(ID)
managedObjectContext!.deleteObject(vpn)
var saveError: NSError?
managedObjectContext!.save(&saveError)
saveContext()
if let activatedVPNID = VPNManager.sharedManager.activatedVPNID {
if activatedVPNID == ID {
VPNManager.sharedManager.activatedVPNID = nil
var vpns = allVPN()
if let firstVPN = vpns.first {
VPNManager.sharedManager.activatedVPNID = firstVPN.ID
}
}
}
}
func VPNByID(ID: NSManagedObjectID) -> VPN?
{
var error: NSError?
if ID.temporaryID {
return .None
}
var result = managedObjectContext?.existingObjectWithID(ID, error: &error)
if let vpn = result {
if !vpn.deleted {
managedObjectContext?.refreshObject(vpn, mergeChanges: true)
return vpn as? VPN
}
} else {
println("Fetch error: \(error)")
return .None
}
return .None
}
func VPNByIDString(ID: String) -> VPN?
{
if let URL = NSURL(string: ID) {
if let scheme = URL.scheme {
if scheme.lowercaseString == "x-coredata" {
if let moid = persistentStoreCoordinator!.managedObjectIDForURIRepresentation(URL) {
return VPNByID(moid)
}
}
}
}
return .None
}
func VPNByPredicate(predicate: NSPredicate) -> [VPN]
{
var vpns = [VPN]()
var request = NSFetchRequest(entityName: "VPN")
request.predicate = predicate
var error: NSError?
let fetchResults = managedObjectContext!.executeFetchRequest(request, error: &error) as [VPN]?
if let results = fetchResults {
for vpn in results {
if vpn.deleted {
continue
}
vpns.append(vpn)
}
} else {
println("Failed to fetch VPNs: \(error?.localizedDescription)")
}
return vpns
}
func VPNBeginsWithTitle(title: String) -> [VPN]
{
let titleBeginsWithPredicate = NSPredicate(format: "title beginswith[cd] %@", argumentArray: [title])
return VPNByPredicate(titleBeginsWithPredicate)
}
func VPNHasTitle(title: String) -> [VPN]
{
let titleBeginsWithPredicate = NSPredicate(format: "title == %@", argumentArray: [title])
return VPNByPredicate(titleBeginsWithPredicate)
}
func duplicate(vpn: VPN) -> VPN?
{
let duplicatedVPNs = VPNDataManager.sharedManager.VPNBeginsWithTitle(vpn.title)
if duplicatedVPNs.count > 0 {
let newTitle = "\(vpn.title) \(duplicatedVPNs.count)"
VPNKeychainWrapper.passwordForVPNID(vpn.ID)
return createVPN(
newTitle,
server: vpn.server,
account: vpn.account,
password: VPNKeychainWrapper.passwordStringForVPNID(vpn.ID) ?? "",
group: vpn.group,
secret: VPNKeychainWrapper.secretStringForVPNID(vpn.ID) ?? "",
alwaysOn: vpn.alwaysOn,
ikev2: vpn.ikev2,
certificateURL: vpn.certificateURL,
certificate: VPNKeychainWrapper.certificateForVPNID(vpn.ID)
)
}
return .None
}
}
| mit | 57c3907e6ae60a8a3469c9a16c3baa41 | 30.22 | 112 | 0.534273 | 5.173157 | false | false | false | false |
xiaomudegithub/viossvc | viossvc/Scenes/Order/OrderListViewController.swift | 1 | 2599 | //
// OrderListViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/28.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import Foundation
class OrderListViewController: BasePageListTableViewController,OEZTableViewDelegate, OrderRefreshDelegate{
var currentPageIndex = 1
override func viewDidLoad() {
super.viewDidLoad()
MobClick.event(AppConst.Event.order_list)
}
override func didRequest(pageIndex: Int) {
let last_id:Int = pageIndex == 1 ? 0 : (dataSource?.last as! OrderListModel).order_id
AppAPIHelper.orderAPI().list(last_id, count: AppConst.DefaultPageSize, complete: completeBlockFunc(), error: errorBlockFunc())
}
override func didRequestComplete(data: AnyObject?) {
let array = data as? Array<OrderListModel>
if data != nil && array?.count > 0 {
dataSource = data as? Array<AnyObject>
}
super.didRequestComplete(data)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func tableView(tableView: UITableView!, rowAtIndexPath indexPath: NSIndexPath!, didAction action: Int, data: AnyObject!) {
let orderModel = dataSource![indexPath.row] as! OrderListModel
/**
* 如果订单已完成则跳转订单详情。反之弹出订单操作页
*/
if orderModel.order_status > 6 {
performSegueWithIdentifier("orderToDetail", sender: indexPath)
} else {
let handleVC = HandleOrderViewController()
handleVC.modalPresentationStyle = .Custom
handleVC.delegate = self
handleVC.setupDataWithModel(orderModel)
handleVC.navigationVC = navigationController
presentViewController(handleVC, animated: true) {
}
}
}
func refreshList() {
beginRefreshing()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is OrderDetailViewController {
let indexPath = sender as! NSIndexPath
let orderModel = dataSource![indexPath.row] as! OrderListModel
let detailVC = segue.destinationViewController as! OrderDetailViewController
detailVC.orderModel = orderModel
}
}
}
| apache-2.0 | 7d2dc136200bc7d26bb796acfa820d36 | 28.627907 | 135 | 0.61146 | 5.612335 | false | false | false | false |
cfr/burningbar | xcode/TestGen/TestGen.playground/Contents.swift | 1 | 1115 |
import Foundation
import TestGen
class Printer: Transport {
typealias CancellationToken = Void
func call(method: String, arguments: [String: AnyObject],
completion: [String : AnyObject] -> Void)
-> CancellationToken {
println("Called \(method) with \(arguments)")
}
func cancel(token: CancellationToken) { }
func cast(method: String, arguments: [String : AnyObject]) { }
func listen(event: String, listener: [String : AnyObject] -> Void) { }
}
let printer = Printer()
let i = Interface(transport: printer)
i.register("u", password: "p", completion: { print($0) })
i.ping() { _ in }
let cj = ["login":"l", "pass":"p"]
let phpArr = [1 as AnyObject, "b" as AnyObject]
let fj: [String: AnyObject] = ["photoURLs": phpArr, "friends": [:], "name": "A",
"birth": "1986-03-25T11:30:00+04:00"]
let user = User(json: ["photoURLs": [], "creds": cj, "friends": ["f": fj], "name": "B"])
user == User(json: fj)
print(user)
if let b = user?.friends.values.array.last?.birth { print(b) }
// TODO: overloading mapping operator example
| unlicense | 58b2f30bfd3b9e246dca5dc505ce9a75 | 33.84375 | 88 | 0.612556 | 3.539683 | false | false | false | false |
mobistix/ios-charts | Charts/Classes/Utils/TimelineCalloutView.swift | 1 | 1351 | //
// TimelineCalloutView.swift
// RLCharts
//
// Created by Alexey Kuchmiy on 23/05/16.
// Copyright © 2016 Realine. All rights reserved.
//
import Foundation;
import SMCalloutView;
public typealias TimelineCalloutAccessoryTapped = () -> Void
public class TimelineCalloutView: SMCalloutView {
public var onAccessoryTapped: TimelineCalloutAccessoryTapped?
var isDismissed = true
public init() {
super.init(frame: CGRect.zero)
let infoButton = UIButton(type: .infoLight)
infoButton.addTarget(self, action: #selector(TimelineCalloutView.accessoryButtonTapped(sender:)), for: .touchUpInside)
rightAccessoryView = infoButton
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func presentAtPoint(point: CGPoint, chartView: UIView, driverName: String) {
dismiss()
isDismissed = false
title = driverName
presentCallout(from: CGRect(x: point.x, y: point.y, width: 0, height: 0), in: chartView, constrainedTo: chartView, animated: true)
}
public func dismiss() {
if !isDismissed {
isDismissed = true
self.dismissCallout(animated: true)
}
}
func accessoryButtonTapped(sender: UIButton) {
onAccessoryTapped?()
}
}
| apache-2.0 | 544f7a3cd7f7ccb884f13f2106a810c6 | 27.723404 | 138 | 0.657037 | 4.5 | false | false | false | false |
bjarkehs/NibDesignable | NibDesignable.swift | 1 | 3958 | //
// NibDesignable.swift
//
// Copyright (c) 2014 Morten Bøgh
//
// 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 UIKit
extension UIView {
// MARK: - Nib loading
/**
Called to load the nib in setupNib().
:returns: UIView instance loaded from a nib file.
*/
public func loadNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: self.nibName(), bundle: bundle)
return nib.instantiateWithOwner(self, options: nil)[0] as! UIView
}
/**
Called in the default implementation of loadNib(). Default is class name.
:returns: Name of a single view nib file.
*/
public func nibName() -> String {
return self.dynamicType.description().componentsSeparatedByString(".").last!
}
}
@IBDesignable
public class NibDesignable: UIView {
// MARK: - Initializer
override public init(frame: CGRect) {
super.init(frame: frame)
self.setupNib()
}
// MARK: - NSCoding
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupNib()
}
// MARK: - Nib loading
/**
Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview.
*/
private func setupNib() {
let view = self.loadNib()
self.addSubview(view)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let bindings = ["view": view]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:NSLayoutFormatOptions(0), metrics:nil, views: bindings))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:NSLayoutFormatOptions(0), metrics:nil, views: bindings))
}
}
@IBDesignable
public class NibDesignableTableViewCell: UITableViewCell {
// MARK: - Initializer
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupNib()
}
// MARK: - NSCoding
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupNib()
}
// MARK: - Nib loading
/**
Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview.
*/
private func setupNib() {
let view = self.loadNib()
self.contentView.addSubview(view)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let bindings = ["view": view]
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:NSLayoutFormatOptions(0), metrics:nil, views: bindings))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:NSLayoutFormatOptions(0), metrics:nil, views: bindings))
}
}
| mit | e48b622a286b6a8af62fb3141447d6af | 35.302752 | 165 | 0.686126 | 4.710714 | false | false | false | false |
alessiobrozzi/firefox-ios | Storage/SQL/SQLiteHistoryRecommendations.swift | 1 | 5239 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
extension SQLiteHistory: HistoryRecommendations {
public func getHighlights() -> Deferred<Maybe<Cursor<Site>>> {
let limit = 20
let bookmarkLimit = 1
let historyLimit = limit - bookmarkLimit
let microsecondsPerMinute: UInt64 = 60_000_000 // 1000 * 1000 * 60
let now = Date.nowMicroseconds()
let thirtyMinutesAgo: UInt64 = now - 30 * microsecondsPerMinute
let threeDaysAgo: UInt64 = now - (60 * microsecondsPerMinute) * 24 * 3
let blacklistedHosts: Args = [
"google.com" ,
"google.ca" ,
"calendar.google.com" ,
"mail.google.com" ,
"mail.yahoo.com" ,
"search.yahoo.com" ,
"localhost" ,
"t.co"
]
var blacklistSubquery = ""
if blacklistedHosts.count > 0 {
blacklistSubquery = "SELECT " + "\(TableDomains).id" +
" FROM " + "\(TableDomains)" +
" WHERE " + "\(TableDomains).domain" + " IN " + BrowserDB.varlist(blacklistedHosts.count)
}
let removeMultipleDomainsSubquery =
" INNER JOIN (SELECT \(ViewHistoryVisits).domain_id AS domain_id, MAX(\(ViewHistoryVisits).visitDate) AS visit_date" +
" FROM \(ViewHistoryVisits)" +
" GROUP BY \(ViewHistoryVisits).domain_id) AS domains ON domains.domain_id = \(TableHistory).domain_id AND visitDate = domains.visit_date"
let subQuerySiteProjection = "historyID, url, siteTitle, guid, visitCount, visitDate, is_bookmarked"
let nonRecentHistory =
"SELECT \(subQuerySiteProjection) FROM (" +
" SELECT \(TableHistory).id as historyID, url, title AS siteTitle, guid, visitDate, \(TableHistory).domain_id," +
" (SELECT COUNT(1) FROM \(TableVisits) WHERE s = \(TableVisits).siteID) AS visitCount," +
" (SELECT COUNT(1) FROM \(ViewBookmarksLocalOnMirror) WHERE \(ViewBookmarksLocalOnMirror).bmkUri == url) AS is_bookmarked" +
" FROM (" +
" SELECT siteID AS s, max(date) AS visitDate" +
" FROM \(TableVisits)" +
" WHERE date < ?" +
" GROUP BY siteID" +
" ORDER BY visitDate DESC" +
" )" +
" LEFT JOIN \(TableHistory) ON \(TableHistory).id = s" +
removeMultipleDomainsSubquery +
" WHERE visitCount <= 3 AND title NOT NULL AND title != '' AND is_bookmarked == 0 AND url NOT IN" +
" (SELECT \(TableActivityStreamBlocklist).url FROM \(TableActivityStreamBlocklist))" +
" AND \(TableHistory).domain_id NOT IN ("
+ blacklistSubquery + ")" +
" LIMIT \(historyLimit)" +
")"
let bookmarkHighlights =
"SELECT \(subQuerySiteProjection) FROM (" +
" SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, \(TableHistory).title AS siteTitle, guid, \(TableHistory).domain_id, NULL AS visitDate, (SELECT count(1) FROM visits WHERE \(TableVisits).siteID = \(TableHistory).id) as visitCount, 1 AS is_bookmarked" +
" FROM (" +
" SELECT bmkUri" +
" FROM \(ViewBookmarksLocalOnMirror)" +
" WHERE \(ViewBookmarksLocalOnMirror).server_modified > ? OR \(ViewBookmarksLocalOnMirror).local_modified > ?" +
" )" +
" LEFT JOIN \(TableHistory) ON \(TableHistory).url = bmkUri" +
removeMultipleDomainsSubquery +
" WHERE visitCount >= 3 AND \(TableHistory).title NOT NULL and \(TableHistory).title != '' AND url NOT IN" +
" (SELECT \(TableActivityStreamBlocklist).url FROM \(TableActivityStreamBlocklist))" +
" LIMIT \(bookmarkLimit)" +
")"
let siteProjection = subQuerySiteProjection.replacingOccurrences(of: "siteTitle", with: "siteTitle AS title")
let highlightsQuery =
"SELECT \(siteProjection), iconID, iconURL, iconType, iconDate, iconWidth, \(TablePageMetadata).title AS metadata_title, media_url, type, description, provider_name " +
"FROM ( \(nonRecentHistory) UNION ALL \(bookmarkHighlights) ) " +
"LEFT JOIN \(ViewHistoryIDsWithWidestFavicons) ON \(ViewHistoryIDsWithWidestFavicons).id = historyID " +
"LEFT OUTER JOIN \(TablePageMetadata) ON \(TablePageMetadata).site_url = url " +
"GROUP BY url"
let otherArgs = [threeDaysAgo, threeDaysAgo] as Args
let args: Args = [thirtyMinutesAgo] + blacklistedHosts + otherArgs
return self.db.runQuery(highlightsQuery, args: args, factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
public func removeHighlightForURL(_ url: String) -> Success {
return self.db.run([("INSERT INTO \(TableActivityStreamBlocklist) (url) VALUES (?)", [url])])
}
}
| mpl-2.0 | 6ebbd3681aaf0f8c85f644fdbc7d5fb2 | 53.572917 | 287 | 0.597824 | 4.628092 | false | false | false | false |
agrippa1994/iOS-PLC | Pods/Charts/Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift | 4 | 11544 | //
// ChartXAxisRendererHorizontalBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart
{
public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart)
}
public override func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
_xAxis.values = xValues
let longest = _xAxis.getLongestLabel() as NSString
let longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont])
_xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5)
_xAxis.labelHeight = longestSize.height
}
public override func renderAxisLabels(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil)
{
return
}
let xoffset = _xAxis.xOffset
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right)
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
}
/// draws the x-labels on the specified y-position
internal func drawLabels(context context: CGContext?, pos: CGFloat, align: NSTextAlignment)
{
let labelFont = _xAxis.labelFont
let labelTextColor = _xAxis.labelTextColor
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
let bd = _chart.data as! BarChartData
let step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
let label = _xAxis.values[i]
if (label == nil)
{
continue
}
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0
// consider groups (center label for each group)
if (step > 1)
{
position.y += (CGFloat(step) - 1.0) / 2.0
}
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, _xAxis.gridLineWidth)
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var position = CGPoint(x: 0.0, y: 0.0)
let bd = _chart.data as! BarChartData
// take into consideration that multiple DataSets increase _deltaX
let step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
_gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_gridLineSegmentsBuffer[0].y = position.y
_gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_gridLineSegmentsBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, _xAxis.axisLineWidth)
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext?)
{
var limitLines = _xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = 0; i < limitLines.count; i++)
{
let l = limitLines[i]
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_limitLineSegmentsBuffer[1].y = position.y
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let add = CGFloat(4.0)
let xOffset: CGFloat = add
let yOffset: CGFloat = l.lineWidth + labelLineHeight
if (l.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
CGContextRestoreGState(context)
}
} | mit | 8c06de1aae2e0b20c029dadeda7feae7 | 37.355482 | 241 | 0.562283 | 5.620253 | false | false | false | false |
benlangmuir/swift | test/SILGen/availability_query.swift | 13 | 7479 | // RUN: %target-swift-emit-sil %s -target %target-cpu-apple-macosx10.50 -verify
// RUN: %target-swift-emit-silgen %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s
// REQUIRES: OS=macosx
// CHECK-LABEL: sil{{.+}}@main{{.*}} {
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK-NOT: {{.*}}integer_literal $Builtin.Int1, -1
// CHECK-NOT: builtin "xor_Int1"{{.*}}
if #available(OSX 10.53.8, iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[MINUSONE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: [[QUERY_INVERSION:%.*]] = builtin "xor_Int1"([[QUERY_RESULT]] : $Builtin.Int1, [[MINUSONE]] : $Builtin.Int1) : $Builtin.Int1
if #unavailable(OSX 10.53.8, iOS 7.1) {
}
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_br [[TRUE]]
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #available(iOS 7.1, *) {
}
// CHECK: [[FALSE:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: cond_br [[FALSE]]
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #unavailable(iOS 7.1) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK-NOT: {{.*}}integer_literal $Builtin.Int1, -1
// CHECK-NOT: builtin "xor_Int1"{{.*}}
if #available(OSX 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[MINUSONE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: [[QUERY_INVERSION:%.*]] = builtin "xor_Int1"([[QUERY_RESULT]] : $Builtin.Int1, [[MINUSONE]] : $Builtin.Int1) : $Builtin.Int1
if #unavailable(OSX 10.52) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK-NOT: {{.*}}integer_literal $Builtin.Int1, -1
// CHECK-NOT: builtin "xor_Int1"{{.*}}
if #available(macOS 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[MINUSONE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: [[QUERY_INVERSION:%.*]] = builtin "xor_Int1"([[QUERY_RESULT]] : $Builtin.Int1, [[MINUSONE]] : $Builtin.Int1) : $Builtin.Int1
if #unavailable(macOS 10.52) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK-NOT: {{.*}}integer_literal $Builtin.Int1, -1
// CHECK-NOT: builtin "xor_Int1"{{.*}}
if #available(OSX 10, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[MINUSONE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: [[QUERY_INVERSION:%.*]] = builtin "xor_Int1"([[QUERY_RESULT]] : $Builtin.Int1, [[MINUSONE]] : $Builtin.Int1) : $Builtin.Int1
if #unavailable(OSX 10) {
}
// CHECK: }
func doThing() {}
func testUnreachableVersionAvailable(condition: Bool) {
if #available(OSX 10.0, *) {
doThing() // no-warning
return
} else {
doThing() // no-warning
}
if #unavailable(OSX 10.0) {
doThing() // no-warning
} else {
doThing() // no-warning
return
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailable(condition: Bool) {
if #available(iOS 7.1, *) {
doThing() // no-warning
return
} else {
doThing() // no-warning
}
if #unavailable(iOS 7.1) {
doThing() // no-warning
} else {
doThing() // no-warning
return
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailableGuard() {
guard #available(iOS 7.1, *) else {
doThing() // no-warning
return
}
guard #unavailable(iOS 7.1) else {
doThing() // no-warning
return
}
doThing() // no-warning
}
| apache-2.0 | bacb216ce7636921d12b112f862cfb35 | 44.603659 | 170 | 0.636716 | 3.344812 | false | false | false | false |
hhsolar/MemoryMaster-iOS | MemoryMaster/View/EditNoteCollectionViewCell.swift | 1 | 8029 | //
// EditNoteCollectionViewCell.swift
// MemoryMaster
//
// Created by apple on 23/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
protocol EditNoteCollectionViewCellDelegate: class {
func noteTitleEdit(for cell: EditNoteCollectionViewCell)
func noteTextContentChange(cardIndex: Int, textViewType: String, textContent: NSAttributedString)
func noteAddPhoto()
}
class EditNoteCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var titleEditButton: UIButton!
@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var bodyTextView: UITextView!
let titleTextView = UITextView()
let titleKeyboardAddPhotoButton = UIButton()
let bodyKeyboardAddPhotoButton = UIButton()
var cardIndex: Int?
var currentStatus: CardStatus?
var editingTextView: UITextView?
weak var delegate: EditNoteCollectionViewCellDelegate?
var titleText: NSAttributedString? {
get {
return titleTextView.attributedText
}
}
var bodyText: NSAttributedString? {
get {
return bodyTextView.attributedText
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
private func setupUI()
{
contentView.backgroundColor = CustomColor.paperColor
titleEditButton.setTitleColor(CustomColor.medianBlue, for: .normal)
// titleTextView
titleTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge)
titleTextView.backgroundColor = CustomColor.paperColor
titleTextView.tag = OutletTag.titleTextView.rawValue
titleTextView.showsVerticalScrollIndicator = false
titleTextView.delegate = self
contentView.addSubview(titleTextView)
let titleAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
titleKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight)
titleKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal)
titleKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside)
titleAccessoryView.addSubview(titleKeyboardAddPhotoButton)
titleTextView.inputAccessoryView = titleAccessoryView
// bodyTextView
bodyTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge)
bodyTextView.backgroundColor = CustomColor.paperColor
bodyTextView.tag = OutletTag.bodyTextView.rawValue
bodyTextView.showsVerticalScrollIndicator = false
bodyTextView.delegate = self
let bodyAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
bodyKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight)
bodyKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal)
bodyKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside)
bodyAccessoryView.addSubview(bodyKeyboardAddPhotoButton)
bodyTextView.inputAccessoryView = bodyAccessoryView
}
override func layoutSubviews() {
super.layoutSubviews()
titleTextView.frame = bodyTextView.frame
}
func updateCell(with cardContent: CardContent, at index: Int, total: Int, cellStatus: CardStatus, noteType: NoteType) {
cardIndex = index
currentStatus = cellStatus
indexLabel.text = String.init(format: "%d / %d", index + 1, total)
bodyTextView.attributedText = cardContent.body.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.body.length))
if noteType == NoteType.single {
titleEditButton.isHidden = false
} else {
titleEditButton.isHidden = true
}
switch cellStatus {
case .titleFront:
titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length))
showTitle(noteType: noteType)
case .bodyFrontWithTitle:
titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length))
showBody(noteType: noteType)
default:
showBody(noteType: noteType)
titleTextView.attributedText = NSAttributedString()
}
}
func showTitle(noteType: NoteType)
{
UIView.animateKeyframes(withDuration: 0.5, delay: 0.3, options: [], animations: {
if noteType == NoteType.single {
self.titleEditButton.setTitle("Remove Title", for: .normal)
self.titleLable.text = "Title"
} else {
self.titleLable.text = "Question"
}
self.titleTextView.alpha = 1.0
self.bodyTextView.alpha = 0.0
}, completion: nil)
titleTextView.isHidden = false
bodyTextView.isHidden = true
bodyTextView.resignFirstResponder()
editingTextView = titleTextView
}
func showBody(noteType: NoteType)
{
UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
if noteType == NoteType.single {
self.titleLable.text = ""
if self.currentStatus == CardStatus.bodyFrontWithTitle {
self.titleEditButton.setTitle("Remove Title", for: .normal)
} else {
self.titleEditButton.setTitle("Add Title", for: .normal)
}
} else {
self.titleLable.text = "Answer"
}
self.titleTextView.alpha = 0.0
self.bodyTextView.alpha = 1.0
}, completion: nil)
titleTextView.isHidden = true
bodyTextView.isHidden = false
titleTextView.resignFirstResponder()
editingTextView = bodyTextView
}
@IBAction func titleEditAction(_ sender: UIButton) {
delegate?.noteTitleEdit(for: self)
}
@objc func addPhotoAction() {
delegate?.noteAddPhoto()
}
func cutTextView(KBHeight: CGFloat) {
editingTextView?.frame.size.height = contentView.bounds.height + CustomSize.barHeight - KBHeight - CustomSize.buttonHeight
}
func extendTextView() {
editingTextView?.frame.size.height = contentView.bounds.height - CustomSize.buttonHeight
}
}
extension EditNoteCollectionViewCell: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
if textView.tag == OutletTag.titleTextView.rawValue {
delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "title", textContent: titleText!)
} else if textView.tag == OutletTag.bodyTextView.rawValue {
delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "body", textContent: bodyText!)
}
}
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange == nil {
let range = textView.selectedRange
let attrubuteStr = NSMutableAttributedString(attributedString: textView.attributedText)
attrubuteStr.addAttributes(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: textView.text.count))
textView.attributedText = attrubuteStr
textView.selectedRange = range
}
}
}
| mit | d9626437e5ecc96716308f0d33c6d733 | 40.8125 | 209 | 0.670279 | 5.278107 | false | false | false | false |
ByteriX/BxInputController | BxInputController/Sources/Sections/View/BxInputStringSectionContentBinder.swift | 1 | 1400 | /**
* @file BxInputStringSectionContentBinder.swift
* @namespace BxInputController
*
* @details Binding string data content of section with view
* @date 18.03.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import Foundation
/// Binding string data content of header section with view
open class BxInputStringHeaderSectionContentBinder<Content: BxInputSectionStringContent, View : BxInputStringSectionContentView> : BxInputBaseSectionContentBinder<Content, View>
{
override open func update()
{
super.update()
view?.contentLabel.font = owner?.settings.headerFont
view?.contentLabel.textColor = owner?.settings.headerColor
view?.contentLabel.text = content.text
}
}
/// Binding string data content of footer section with view
open class BxInputStringFooterSectionContentBinder<T: BxInputSectionStringContent> : BxInputBaseSectionContentBinder<T, BxInputStringSectionContentView>
{
override open func update()
{
super.update()
view?.contentLabel.font = owner?.settings.footerFont
view?.contentLabel.textColor = owner?.settings.footerColor
view?.contentLabel.text = content.text
}
}
| mit | 1d49cfb4fb2ac0cc09dc91e080d4b423 | 31.55814 | 177 | 0.724286 | 4.516129 | false | false | false | false |
CoderJackyHuang/ITClient-Swift | ITClient-Swift/Controller/Base/BaseController.swift | 1 | 1957 | //
// BaseController.swift
// ITClient-Swift
//
// Created by huangyibiao on 15/9/24.
// Copyright © 2015年 huangyibiao. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
/// The base controller, for any view controller exclude navigation controller.
///
/// Author: 黄仪标
/// Blog: http://www.hybblog.com/
/// Github: http://github.com/CoderJackyHuang/
/// Email: [email protected]
/// Weibo: JackyHuang(标哥)
class BaseController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .None
}
/// 创建tableview,默认为Plain样式,默认约束为self.view点满
///
/// - parameter style: 样式,默认为Plain
/// - parameter constraint: 约束,默认为self.view.edges
///
/// - returns: tableView对象
func createTableView(style: UITableViewStyle = .Plain, constraint: ((make: ConstraintMaker) -> Void)? = nil) ->UITableView {
let tableView = UITableView(frame: CGRectZero, style: style)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.separatorStyle = .None
tableView.sectionIndexBackgroundColor = UIColor.blackColor()
tableView.sectionIndexTrackingBackgroundColor = UIColor.darkGrayColor()
tableView.sectionIndexColor = UIColor.whiteColor()
if constraint != nil {
tableView.snp_makeConstraints(closure: constraint!)
} else {
tableView.snp_makeConstraints(closure: { (make) -> Void in
make.edges.equalTo(self.view)
})
}
return tableView
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
}
| mit | 10771a6d5babb76e24c0bb423a789e02 | 29.322581 | 126 | 0.703723 | 4.465558 | false | false | false | false |
Awalz/ark-ios-monitor | ArkMonitor/ARKPushNotificationManager.swift | 1 | 2602 | // Copyright (c) 2016 Ark
//
// 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
import SwiftyArk
import UserNotifications
struct ArkPushNotificationManager {
static public func updateDelegateForgingStatus(_ delegate: Delegate) {
let title = "Delegate Update"
var body : String!
if delegate.isForging == true {
body = "Your delegate \(delegate.username) has been voted into the top 51 delegates (position \(delegate.rate))"
} else {
body = "Your delegate \(delegate.username) has been voted out of the top 51 delegates (position \(delegate.rate))"
}
postNotification(title, body: body)
}
static public func newTransactionNotification(_ transaction: Transaction) {
let title = "Transaction"
var body : String!
switch transaction.status() {
case .received:
body = "You received a new transaction for \(transaction.amount) Ark"
default:
return
}
postNotification(title, body: body)
}
static private func postNotification(_ title: String, body: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: nil)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
if let aError = error {
print(aError)
}
}
}
}
| mit | b53e2e94069613c33fd5fad58aaa4179 | 40.967742 | 137 | 0.679093 | 5.013487 | false | false | false | false |
r4phab/ECAB | ECAB/CounterpointingLogs.swift | 1 | 2478 | //
// CounterpointingLogs.swift
// ECAB
//
// Created by Raphaël Bertin on 21/08/2016.
// Copyright © 2016 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import Foundation
class CounterpointingLogs : SubtestLogs{
init(selectedSession : Session) {
super.init(selectedSession : selectedSession, gameName : "Counterpointing")
let result = ECABLogCalculator.getCounterpintingResult(session)
let resultRatio = result.timeBlockConflict / result.timeBlockNonConflict
let mediansRatio = result.conflictTimeMedian / result.nonConflictTimeMedian
addLogSestion("Session results")
addLogLine("Screens = \(session.moves.count)")
addLogLine("Errors = \(session.errors)")
addLogLine("non-conflict (blocks 1)")
addLogLine("total time 1 = \(r(result.timeBlockNonConflict)) msec")
addLogLine("mean reponse time 1 = \(r(result.nonConflictTimeMean)) msec")
addLogLine("median reponse time 1 = \(r(result.nonConflictTimeMedian)) msec")
addLogBlank()
addLogLine("conflict (blocks 2)")
addLogLine("total time 2 = \(r(result.timeBlockConflict)) msec")
addLogLine("mean reponse time 2 = \(r(result.conflictTimeMean)) msec")
addLogLine("median reponse time 2 = \(r(result.conflictTimeMedian)) msec")
addLogBlank()
addLogLine("ratio total2 / total1 = \(r(resultRatio)) msec")
addLogLine("ratio median2 / median1 = \(r(mediansRatio)) msec")
addLogBlank()
addLogSestion("Moves")
for case let move as Move in session.moves {
counter = counter + 1
let status = move.success.boolValue ? "success" : "false positive"
let inverted = move.inverted.boolValue ? " conflict" : "non-conflict"
// Because I defined old interval as Integer I am changing it to Double
// This condition is to keep old data working.
if move.positionX == blankSpaceTag {
addLogBlank()
} else {
if let newInterval = move.intervalDouble as? Double {
addLogLine("\(counter)) \(status) screen:\(move.positionX) \(r(newInterval)) ms \(inverted) ")
} else {
addLogLine("\(counter)) \(status) screen:\(move.positionX) \(move.interval.integerValue) ms \(inverted)")
}
}
}
}
} | mit | 3bedc6bd419828a064087a04963c8477 | 40.983051 | 125 | 0.613489 | 4.645403 | false | false | false | false |
johnno1962c/swift-corelibs-foundation | Foundation/Boxing.swift | 10 | 8769 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A class type which acts as a handle (pointer-to-pointer) to a Foundation reference type which has only a mutable class (e.g., NSURLComponents).
///
/// Note: This assumes that the result of calling copy() is mutable. The documentation says that classes which do not have a mutable/immutable distinction should just adopt NSCopying instead of NSMutableCopying.
internal final class _MutableHandle<MutableType : NSObject> where MutableType : NSCopying {
@_versioned internal var _pointer : MutableType
init(reference : MutableType) {
_pointer = reference.copy() as! MutableType
}
init(adoptingReference reference: MutableType) {
_pointer = reference
}
/// Apply a closure to the reference type.
func map<ReturnType>(_ whatToDo : (MutableType) throws -> ReturnType) rethrows -> ReturnType {
return try whatToDo(_pointer)
}
func _copiedReference() -> MutableType {
return _pointer.copy() as! MutableType
}
func _uncopiedReference() -> MutableType {
return _pointer
}
}
/// Describes common operations for Foundation struct types that are bridged to a mutable object (e.g. NSURLComponents).
internal protocol _MutableBoxing : ReferenceConvertible {
var _handle : _MutableHandle<ReferenceType> { get set }
/// Apply a mutating closure to the reference type, regardless if it is mutable or immutable.
///
/// This function performs the correct copy-on-write check for efficient mutation.
mutating func _applyMutation<ReturnType>(_ whatToDo : (ReferenceType) -> ReturnType) -> ReturnType
}
extension _MutableBoxing {
@inline(__always)
mutating func _applyMutation<ReturnType>(_ whatToDo : (ReferenceType) -> ReturnType) -> ReturnType {
// Only create a new box if we are not uniquely referenced
if !isKnownUniquelyReferenced(&_handle) {
let ref = _handle._pointer
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._pointer)
}
}
internal enum _MutableUnmanagedWrapper<ImmutableType : NSObject, MutableType : NSObject> where MutableType : NSMutableCopying {
case Immutable(Unmanaged<ImmutableType>)
case Mutable(Unmanaged<MutableType>)
}
internal protocol _SwiftNativeFoundationType : class {
associatedtype ImmutableType : NSObject
associatedtype MutableType : NSObject, NSMutableCopying
var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType> { get }
init(unmanagedImmutableObject: Unmanaged<ImmutableType>)
init(unmanagedMutableObject: Unmanaged<MutableType>)
func mutableCopy(with zone : NSZone) -> Any
var hashValue: Int { get }
var description: String { get }
var debugDescription: String { get }
func releaseWrappedObject()
}
extension _SwiftNativeFoundationType {
@inline(__always)
func _mapUnmanaged<ReturnType>(_ whatToDo : (ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
defer { _fixLifetime(self) }
switch __wrapped {
case .Immutable(let i):
return try i._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
case .Mutable(let m):
return try m._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo(_unsafeReferenceCast($0, to: ImmutableType.self))
}
}
}
func releaseWrappedObject() {
switch __wrapped {
case .Immutable(let i):
i.release()
case .Mutable(let m):
m.release()
}
}
func mutableCopy(with zone : NSZone) -> Any {
return _mapUnmanaged { ($0 as NSObject).mutableCopy() }
}
var hashValue: Int {
return _mapUnmanaged { return $0.hashValue }
}
var description: String {
return _mapUnmanaged { return $0.description }
}
var debugDescription: String {
return _mapUnmanaged { return $0.debugDescription }
}
func isEqual(_ other: AnyObject) -> Bool {
return _mapUnmanaged { return $0.isEqual(other) }
}
}
internal protocol _MutablePairBoxing {
associatedtype WrappedSwiftNSType : _SwiftNativeFoundationType
var _wrapped : WrappedSwiftNSType { get set }
}
extension _MutablePairBoxing {
@inline(__always)
func _mapUnmanaged<ReturnType>(_ whatToDo : (WrappedSwiftNSType.ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
// We are using Unmananged. Make sure that the owning container class
// 'self' is guaranteed to be alive by extending the lifetime of 'self'
// to the end of the scope of this function.
// Note: At the time of this writing using withExtendedLifetime here
// instead of _fixLifetime causes different ARC pair matching behavior
// foiling optimization. This is why we explicitly use _fixLifetime here
// instead.
defer { _fixLifetime(self) }
let unmanagedHandle = Unmanaged.passUnretained(_wrapped)
let wrapper = unmanagedHandle._withUnsafeGuaranteedRef { $0.__wrapped }
switch (wrapper) {
case .Immutable(let i):
return try i._withUnsafeGuaranteedRef {
return try whatToDo($0)
}
case .Mutable(let m):
return try m._withUnsafeGuaranteedRef {
return try whatToDo(_unsafeReferenceCast($0, to: WrappedSwiftNSType.ImmutableType.self))
}
}
}
@inline(__always)
mutating func _applyUnmanagedMutation<ReturnType>(_ whatToDo : (WrappedSwiftNSType.MutableType) throws -> ReturnType) rethrows -> ReturnType {
// We are using Unmananged. Make sure that the owning container class
// 'self' is guaranteed to be alive by extending the lifetime of 'self'
// to the end of the scope of this function.
// Note: At the time of this writing using withExtendedLifetime here
// instead of _fixLifetime causes different ARC pair matching behavior
// foiling optimization. This is why we explicitly use _fixLifetime here
// instead.
defer { _fixLifetime(self) }
var unique = true
let _unmanagedHandle = Unmanaged.passUnretained(_wrapped)
let wrapper = _unmanagedHandle._withUnsafeGuaranteedRef { $0.__wrapped }
// This check is done twice becaue: <rdar://problem/24939065> Value kept live for too long causing uniqueness check to fail
switch (wrapper) {
case .Immutable(_):
break
case .Mutable(_):
unique = isKnownUniquelyReferenced(&_wrapped)
}
switch (wrapper) {
case .Immutable(let i):
// We need to become mutable; by creating a new instance we also become unique
let copy = Unmanaged.passRetained(i._withUnsafeGuaranteedRef {
return _unsafeReferenceCast($0.mutableCopy(), to: WrappedSwiftNSType.MutableType.self) }
)
// Be sure to set the var before calling out; otherwise references to the struct in the closure may be looking at the old value
_wrapped = WrappedSwiftNSType(unmanagedMutableObject: copy)
return try copy._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
case .Mutable(let m):
// Only create a new box if we are not uniquely referenced
if !unique {
let copy = Unmanaged.passRetained(m._withUnsafeGuaranteedRef {
return _unsafeReferenceCast($0.mutableCopy(), to: WrappedSwiftNSType.MutableType.self)
})
_wrapped = WrappedSwiftNSType(unmanagedMutableObject: copy)
return try copy._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
} else {
return try m._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
}
}
}
}
| apache-2.0 | 0c24f822c20fafaf5bfe1128856a8fb1 | 38.678733 | 211 | 0.623446 | 5.369871 | false | false | false | false |
KevinYangGit/DYTV | DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift | 1 | 3074 | //
// RecommendViewController.swift
// DYZB
//
// Created by boxfishedu on 2016/10/15.
// Copyright © 2016年 杨琦. All rights reserved.
//
import UIKit
private let kCycleViewH = KScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
class RecommendViewController: BaseAnchorViewController {
//懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: KScreenW, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: KScreenW, height: kGameViewH);
return gameView
}()
}
extension RecommendViewController {
override func setupUI() {
super.setupUI()
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
extension RecommendViewController {
override func loadData() {
baseVM = recommendVM
//请求推荐数据
recommendVM.requestData {
//展示推荐数据
self.collectionView.reloadData()
var groups = self.recommendVM.anchorGroups
groups.removeFirst()
groups.removeFirst()
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
self.gameView.groups = groups
self.loadDataFinished()
}
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
prettyCell.anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
} else {
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
| mit | 38d47423af3c307c5bdcd7f4feb99c3e | 30.884211 | 160 | 0.646418 | 5.870155 | false | false | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Structs/MSSaleByProduct.swift | 1 | 1828 | //
// MSSaleByProduct.swift
// MoySkladSDK
//
// Created by Anton Efimenko on 11.01.17.
// Copyright © 2017 Andrey Parshakov. All rights reserved.
//
import Foundation
/**
Represents SalesByModification report result.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
*/
public class MSSaleByModification {
public let assortment: MSAssortment
public let sellQuantity: Double
public let sellPrice: Money
public let sellCost: Money
public let sellSum: Money
public let sellCostSum: Money
public let returnQuantity: Double
public let returnPrice: Money
public let returnCost: Money
public let returnSum: Money
public let returnCostSum: Money
public let profit: Money
public let margin: Double
public init(assortment: MSAssortment,
sellQuantity: Double,
sellPrice: Money,
sellCost: Money,
sellSum: Money,
sellCostSum: Money,
returnQuantity: Double,
returnPrice: Money,
returnCost: Money,
returnSum: Money,
returnCostSum: Money,
profit: Money,
margin: Double) {
self.assortment = assortment
self.sellQuantity = sellQuantity
self.sellPrice = sellPrice
self.sellCost = sellCost
self.sellSum = sellSum
self.sellCostSum = sellCostSum
self.returnQuantity = returnQuantity
self.returnPrice = returnPrice
self.returnCost = returnCost
self.returnSum = returnSum
self.returnCostSum = returnCostSum
self.profit = profit
self.margin = margin
}
}
| mit | 0e3fa24b4c798061b12a3828f54a02b8 | 30.298246 | 135 | 0.636211 | 4.257757 | false | false | false | false |
humeng12/DouYuZB | DouYuZB/DouYuZB/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 4805 | //
// RecommendViewModel.swift
// DouYuZB
//
// Created by 胡猛 on 2016/11/30.
// Copyright © 2016年 HuMeng. All rights reserved.
//
import UIKit
class RecommendViewModel : BaseViewModel{
lazy var cycleModels : [CycleModel] = [CycleModel]()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
}
extension RecommendViewModel {
@available(iOS 9.0, *)
func requestData(_ finishCallback :@escaping () ->()) {
// 0.定义参数
let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
//创建Group
let dGroup = DispatchGroup()
//1.发送第一组数据请求
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: parameters) {(result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchors.append(anchor)
}
dGroup.leave()
}
//2.发送第二组数据请求
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) {(result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
dGroup.leave()
}
//3.发送第三组数据请求
dGroup.enter()
// NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) {(result) in
//
// // 1.将result转成字典类型
// guard let resultDict = result as? [String : NSObject] else { return }
//
// // 2.根据data该key,获取数组
// guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
//
// // 3.遍历数组,获取字典,并且将字典转成模型对象
// for dict in dataArray {
// let group = AnchorGroup(dict: dict)
// self.anchorGroups.append(group)
// }
//
// dGroup.leave()
// }
loadAnchorData(isGroupData: true,URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) {
dGroup.leave()
}
//所有的数据都请求到,之后进行排序
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
func requestCycleData(_ finishCallback :@escaping () ->()) {
let parameters = ["version" : "2.300"]
NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: parameters) {(result) in
// 1.获取整体字典数据
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data的key获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}
}
| mit | 19d3a2d52b327bc302309ed8bc57fd33 | 30.884892 | 136 | 0.515569 | 4.714894 | false | false | false | false |
davidbjames/Unilib | Unilib/Sources/Ranges.swift | 1 | 4330 | //
// Ranges.swift
// C3
//
// Copyright © 2016-2021 David James. All rights reserved.
//
import Foundation
// NOTE: this file contains code that supports C3 theme
// operators which need the ability to set ordinal ranges
// so its interface must remain public.
// But it also exists in Unilib publically, so we add
// "public/**/" to prevent C3<->Unilib syncing from
// flipping it back to "internal".
/// Type erasure wrapper for RangeExpression in case it's not
/// practical for your API to provide the genericity necessary
/// to support RangeExpression (which has an associated type).
/// Primarily provides the ability to check if a range contains an item.
public/**/ struct AnyRangeExpression<B, C:Collection> : RangeExpression where B == C.Index {
private let _contains:(B)->Bool
private let _relativeTo:(C)->Range<B>
init<R:RangeExpression>(range:R) where R.Bound == B {
self._contains = { bound in
range.contains(bound)
}
self._relativeTo = { collection in
range.relative(to:collection)
}
}
public/**/ func contains(_ element: B) -> Bool {
_contains(element)
}
public/**/ func relative<_C:Collection>(to collection: _C) -> Range<B> where B == _C.Index {
guard _C.self == C.self else {
preconditionFailure("Attempt to use relative(to:) on type erased AnyRangeExpression fails because the collection element type provided is not the same as the element type on the type erased wrapper.")
}
return _relativeTo(collection as! C)
}
}
extension AnyRangeExpression : CustomStringConvertible where B == Int {
public/**/ var description: String {
// Since the type erasure is closing over (hiding) the concrete range,
// for integer type ranges, we need to use relative(to:) to map indices
// from 0 to the actual range with the return value representing the
// values of the actual range, e.g. 2...
// (The following Array created from any other range (e.g. 100...200)
// would have the same results because it's just used to for it's indices.)
// (see also relative(to:) documentation)
"\(relative(to:Array(0...100)))"
}
}
/// An array of RangeExpressions that itself can be
/// treated as a RangeExpression.
extension Array : RangeExpression where Element:RangeExpression {
public/**/ func contains(_ element: Element.Bound) -> Bool {
contains(where:{ $0.contains(element) })
}
public/**/ func relative<C>(to collection: C) -> Range<Element.Bound> where C : Collection, Self.Element.Bound == C.Index {
guard
let start = startIndex as? Element.Bound,
let end = endIndex as? Element.Bound
else {
preconditionFailure("Not implemented for Element types other than Int.")
}
// Since we know an array's indices are always a half-open range
// just return that range.
return start..<end
}
}
/// A type erased range expression that can be used in
/// places that must support heterogenous range types.
/// Example:
///
/// [+(0...5), +8, +(10...)]
public/**/ prefix func +<R:RangeExpression>(_ range:R) -> AnyRangeExpression<R.Bound, [R.Bound]> {
AnyRangeExpression(range:range)
}
private func proofOfConcept() {
// Example with the same range expression types.
_ = [0...3, 6...9].relative(to:["something"])
// Example with diverse range expression types
// by using AnyRangeExpression.
_ = [AnyRangeExpression<Int, [Int]>(range: 0...5), AnyRangeExpression<Int, [Int]>(range:8), AnyRangeExpression<Int, [Int]>(range:8...)].relative(to:[3])
// Example with diverse range expression types
// using prefix shorthand for AnyRangeExpression.
_ = [+(0...5), +10..., +(...8), +(..<8), +2].relative(to:[3])
// (closed range, partial from, partial through, partial up to, single int)
// Same examples passed to Theme API that takes RangeExpression
_ = >[0...3, 0...9]
// Select every ordinal except 6, 7 and 9...
_ = UIView.self & [+(0...5), +8, +(10...)]
// ... could alternatively be expressed as
_ = UIView.self - [6, 7, 9]
// Used for testing:
// func takesRange<R:RangeExpression>(_ range:R) where R.Bound == Int { }
}
| mit | 9dd87003b465bf0d61613c3dc055d283 | 40.228571 | 212 | 0.640795 | 4.166506 | false | false | false | false |
JamieScanlon/AugmentKit | AugmentKit/Managers/DeviceManager.swift | 1 | 2127 | //
// DeviceManager.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 UIKit
/**
Provides methods for geting information about the users device
*/
open class DeviceManager {
/**
Singleton instance
*/
public static var shared = DeviceManager()
/**
Gets the screen size in pixels
- Returns: A `CGSize` object containing the screen size in pixels
*/
public func screenSizeInPixels() -> CGSize {
let screen = UIScreen.main
let height = screen.nativeBounds.size.height
let width = screen.nativeBounds.size.width
return CGSize(width: width, height: height)
}
/**
Gets the screen size in points
- Returns: A `CGSize` object containing the screen size in points
*/
public func screenSizeInPoints() -> CGSize {
let screen = UIScreen.main
let height = screen.bounds.size.height
let width = screen.bounds.size.width
return CGSize(width: width, height: height)
}
}
| mit | bf893cb94f09e2e1ddabd7c5302f234b | 35.672414 | 82 | 0.700517 | 4.468487 | false | false | false | false |
aikizoku/SKLogDebugger-iOS | SKLogDebugger/Classes/Array+SKLD.swift | 1 | 997 | //
// Array+SKLD.swift
// SKLogDebuggerDemo
//
// Created by yukithehero on 2017/04/25.
// Copyright © 2017年 yukithehero. All rights reserved.
//
import Foundation
extension Array {
var lastIndex: Int {
get {
return count == 0 ? 0 : count - 1
}
}
func each(e closure: (_ element: Element) -> Void) {
for element in self {
closure(element)
}
}
func each(ie closure: (_ i: Int, _ element: Element) -> Void) {
let c = count
for i in 0 ..< c {
closure(i, self[i])
}
}
func each(fle closure: (_ first: Bool, _ last: Bool, _ element: Element) -> Void) {
let c = count
let li = lastIndex
for i in 0 ..< c {
let first = i == 0
let last = i == li
closure(first, last, self[i])
}
}
func unique() -> Array {
return NSOrderedSet(array: self).array as! Array<Element>
}
}
| mit | b3b526c6fa9aab49009ced370ac63062 | 21.088889 | 87 | 0.491952 | 3.750943 | false | false | false | false |
wesj/firefox-ios-1 | Client/Frontend/Reader/ReaderMode.swift | 1 | 8558 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
let ReaderModeProfileKeyStyle = "readermode.style"
enum ReaderModeMessageType: String {
case StateChange = "ReaderModeStateChange"
case PageEvent = "ReaderPageEvent"
}
enum ReaderPageEvent: String {
case PageShow = "PageShow"
}
enum ReaderModeState: String {
case Available = "Available"
case Unavailable = "Unavailable"
case Active = "Active"
}
enum ReaderModeTheme: String {
case Light = "light"
case Dark = "dark"
case Sepia = "sepia"
}
enum ReaderModeFontType: String {
case Serif = "serif"
case SansSerif = "sans-serif"
}
enum ReaderModeFontSize: Int {
case Smallest = 1
case Small
case Normal = 3
case Large = 4
case Largest = 5
}
struct ReaderModeStyle {
var theme: ReaderModeTheme
var fontType: ReaderModeFontType
var fontSize: ReaderModeFontSize
/// Encode the style to a JSON dictionary that can be passed to ReaderMode.js
func encode() -> String {
return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).toString(pretty: false)
}
/// Encode the style to a dictionary that can be stored in the profile
func encode() -> [String:AnyObject] {
return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]
}
init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) {
self.theme = theme
self.fontType = fontType
self.fontSize = fontSize
}
/// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded.
init?(dict: [String:AnyObject]) {
let themeRawValue = dict["theme"] as? String
let fontTypeRawValue = dict["fontType"] as? String
let fontSizeRawValue = dict["fontSize"] as? Int
if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil {
return nil
}
let theme = ReaderModeTheme(rawValue: themeRawValue!)
let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!)
let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!)
if theme == nil || fontType == nil || fontSize == nil {
return nil
}
self.theme = theme!
self.fontType = fontType!
self.fontSize = fontSize!
}
}
let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: .Normal)
/// This struct captures the response from the Readability.js code.
struct ReadabilityResult {
var domain = ""
var url = ""
var content = ""
var title = ""
var credits = ""
init?(object: AnyObject?) {
if let dict = object as? NSDictionary {
if let uri = dict["uri"] as? NSDictionary {
if let url = uri["spec"] as? String {
self.url = url
}
if let host = uri["host"] as? String {
self.domain = host
}
}
if let content = dict["content"] as? String {
self.content = content
}
if let title = dict["title"] as? String {
self.title = title
}
if let credits = dict["byline"] as? String {
self.credits = credits
}
} else {
return nil
}
}
/// Initialize from a JSON encoded string
init?(string: String) {
let object = JSON(string: string)
let domain = object["domain"].asString
let url = object["url"].asString
let content = object["content"].asString
let title = object["title"].asString
let credits = object["credits"].asString
if domain == nil || url == nil || content == nil || title == nil || credits == nil {
return nil
}
self.domain = domain!
self.url = url!
self.content = content!
self.title = title!
self.credits = credits!
}
/// Encode to a dictionary, which can then for example be json encoded
func encode() -> [String:AnyObject] {
return ["domain": domain, "url": url, "content": content, "title": title, "credits": credits]
}
/// Encode to a JSON encoded string
func encode() -> String {
return JSON(encode() as [String:AnyObject]).toString(pretty: false)
}
}
/// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate
protocol ReaderModeDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser)
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser)
}
let ReaderModeNamespace = "_firefox_ReaderMode"
class ReaderMode: BrowserHelper {
var delegate: ReaderModeDelegate?
private weak var browser: Browser?
var state: ReaderModeState = ReaderModeState.Unavailable
private var originalURL: NSURL?
class func name() -> String {
return "ReaderMode"
}
required init?(browser: Browser) {
self.browser = browser
// This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related.
if let path = NSBundle.mainBundle().pathForResource("Readability", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
// This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode.
if let path = NSBundle.mainBundle().pathForResource("ReaderMode", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "readerModeMessageHandler"
}
private func handleReaderPageEvent(readerPageEvent: ReaderPageEvent) {
switch readerPageEvent {
case .PageShow:
delegate?.readerMode(self, didDisplayReaderizedContentForBrowser: browser!)
}
}
private func handleReaderModeStateChange(state: ReaderModeState) {
self.state = state
delegate?.readerMode(self, didChangeReaderModeState: state, forBrowser: browser!)
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
println("DEBUG: readerModeMessageHandler message: \(message.body)")
if let msg = message.body as? Dictionary<String,String> {
if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") {
switch messageType {
case .PageEvent:
if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") {
handleReaderPageEvent(readerPageEvent)
}
break
case .StateChange:
if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") {
handleReaderModeStateChange(readerModeState)
}
break
}
}
}
}
var style: ReaderModeStyle = DefaultReaderModeStyle {
didSet {
if state == ReaderModeState.Active {
browser!.webView.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode()))", completionHandler: {
(object, error) -> Void in
return
})
}
}
}
} | mpl-2.0 | 44b0cd2663c10292af5cfca4ea89bc06 | 34.962185 | 172 | 0.622926 | 5.227856 | false | false | false | false |
nathankot/NKMultipeer | NKMultipeerTests/IntegrationSpec.swift | 1 | 8245 | import NKMultipeer
import Quick
import Nimble
import RxSwift
public class IntegrationSpec : QuickSpec {
override public func spec() {
var disposeBag = DisposeBag()
describe("two clients") {
var clientone: CurrentClient<MockIden, MockSession>!
var clienttwo: CurrentClient<MockIden, MockSession>!
beforeEach {
MockSession.reset()
disposeBag = DisposeBag()
clientone = CurrentClient(session: MockSession(name: "one"))
clienttwo = CurrentClient(session: MockSession(name: "two"))
}
describe("client two advertises") {
beforeEach {
// Advertise and always accept connections
clienttwo.startAdvertising()
clienttwo.incomingConnections()
.subscribeNext { (client, _, respond) in
respond(true) }
.addDisposableTo(disposeBag)
}
it("allows a client to find another even if browsing is begun before advertising") {
waitUntil { done in
clienttwo.stopAdvertising()
clienttwo.disconnect()
let clientthree = CurrentClient(session: MockSession(name: "two"))
clientone.startBrowsing()
defer { clientthree.startAdvertising() }
clientone.nearbyPeers()
.filter { $0.count > 0 }
.take(1).subscribeCompleted(done)
.addDisposableTo(disposeBag)
}
}
it("allows client one to browse for client two") {
waitUntil { done in
clientone.startBrowsing()
clientone.nearbyPeers()
.filter { $0.count > 0 }
.subscribeNext { clients in
expect(clients[0].0.iden).to(equal(clienttwo.iden))
done()
}
.addDisposableTo(disposeBag)
}
}
it("allows clients to connect with eachother") {
waitUntil { done in
clientone.connectedPeer()
.take(1)
.subscribeNext { _ in done() }
.addDisposableTo(disposeBag)
clientone.connect(clienttwo)
}
}
it("alters connections when clients connect") {
waitUntil { done in
Observable.combineLatest(
clientone.connections(),
clienttwo.connections()) { $0.count + $1.count }
.subscribeNext { if $0 == 2 { done() } }
.addDisposableTo(disposeBag)
clientone.connect(clienttwo)
}
}
it("notifies connections") {
waitUntil { done in
Observable.zip(clientone.connectedPeer(), clienttwo.connectedPeer()) { $0 }
.take(1)
.subscribeNext { (two, one) in
expect(two.iden).to(equal(clienttwo.iden))
expect(one.iden).to(equal(clientone.iden))
done()
}
.addDisposableTo(disposeBag)
clientone.connect(clienttwo)
}
}
it("notifies disconnections") {
waitUntil { done in
clientone.connect(clienttwo)
Observable.zip(clientone.disconnectedPeer(), clienttwo.disconnectedPeer()) { $0 }
.take(1)
.subscribeNext { (two, one) in
expect(two.iden).to(equal(clienttwo.iden))
expect(one.iden).to(equal(clientone.iden))
done()
}
.addDisposableTo(disposeBag)
clientone.disconnect()
}
}
describe("clients are connected") {
beforeEach {
waitUntil { done in
clientone.connectedPeer()
.take(1)
.subscribeNext { _ in done() }
.addDisposableTo(disposeBag)
clientone.connect(clienttwo)
}
}
it("allows client two to disconnect") {
waitUntil { done in
clientone.connections()
.skip(1).take(1)
.subscribeNext { (connections) in
expect(connections.count).to(equal(0))
done()
}
.addDisposableTo(disposeBag)
clienttwo.disconnect()
}
}
it("fires a next event when sending data") {
waitUntil { done in
clientone.send(clienttwo, "hello")
.subscribeNext { _ in done() }
.addDisposableTo(disposeBag)
}
}
it("lets clients send strings to eachother") {
waitUntil { done in
clienttwo.receive()
.subscribeNext { (client: Client, string: String) in
expect(client.iden).to(equal(clientone.iden))
expect(string).to(equal("hello"))
}
.addDisposableTo(disposeBag)
clientone.send(clienttwo, "hello")
.subscribeCompleted { done() }
.addDisposableTo(disposeBag)
}
}
it("lets clients send resource urls to each other") {
waitUntil { done in
clienttwo.receive()
.subscribeNext { (client: Client, name: String, url: NSURL) in
expect(client.iden).to(equal(clientone.iden))
expect(name).to(equal("txt file"))
let contents = NSString(data: NSData(contentsOfURL: url)!, encoding: NSUTF8StringEncoding)
expect(contents).to(equal("hello there this is random data"))
}
.addDisposableTo(disposeBag)
let url = NSBundle(forClass: self.dynamicType).URLForResource("Data", withExtension: "txt")
clientone.send(clienttwo, name: "txt file", url: url!)
.subscribeCompleted { done() }
.addDisposableTo(disposeBag)
}
}
it("lets clients send JSON data to each other via foundation objects") {
waitUntil { done in
clienttwo.receive()
.subscribeNext { (client: Client, json: [String: AnyObject]) in
expect(client.iden).to(equal(clientone.iden))
expect(json["one"] as? String).to(equal("two"))
expect(json["three"] as? Int).to(equal(4))
expect(json["five"] as? Bool).to(beTrue())
}
.addDisposableTo(disposeBag)
clientone.send(clienttwo, [
"one": "two", "three": 4, "five": true])
.subscribeCompleted { done() }
.addDisposableTo(disposeBag)
}
}
it("lets clients send streams of bytes to each other") {
waitUntil { done in
clienttwo.receive(clientone, streamName: "hello")
.take(1)
.subscribeNext { data in
expect(data).to(equal([0b00110011, 0b11111111]))
done()
}
.addDisposableTo(disposeBag)
let data: Observable<[UInt8]> = Observable.of(
[0b00110011, 0b11111111],
[0b00000000, 0b00000001])
Observable.zip(clientone.send(clienttwo, streamName: "hello"), data) { $0 }
.subscribeNext { (fetcher, data) in fetcher(data) }
.addDisposableTo(disposeBag)
}
}
it("limits stream reads to the `maxLength` passed in") {
waitUntil { done in
clienttwo.receive(clientone, streamName: "hello")
.take(2)
.reduce([], accumulator: { $0 + [$1] })
.subscribeNext { data in
expect(data[0].count).to(equal(512))
expect(data[1].count).to(equal(4))
done()
}
.addDisposableTo(disposeBag)
let data = Observable.just([UInt8](count: 516, repeatedValue: 0x4D))
Observable.zip(clientone.send(clienttwo, streamName: "hello"), data) { $0 }
.subscribeNext { (fetcher, data) in fetcher(data) }
.addDisposableTo(disposeBag)
}
}
}
}
}
}
}
| mit | 00f48c5dfe500584f131d6e882a10d85 | 31.848606 | 106 | 0.515949 | 5.146692 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/Resource Data/Language.swift | 1 | 1135 | //
// Language.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-10-24.
// Copyright © 2017 SIL International. All rights reserved.
//
import Foundation
/// Language object for Keyman Cloud API 4.0.
public struct Language: Codable {
/// Name of language.
public let name: String
/// BCP-47 language code.
public let id: String
/// Corresponding Keyboard objects.
public let keyboards: [Keyboard]?
/// Corresponding lexical models.
public let lexicalModels: [LexicalModel]?
/// Font for input fields (and OSK if `oskFont` is not present).
public let font: Font?
/// Font for the OSK.
public let oskFont: Font?
init(from kmpLanguage: KMPLanguage) {
self.name = kmpLanguage.name
self.id = kmpLanguage.languageId
keyboards = nil
lexicalModels = nil
font = nil
oskFont = nil
}
init(name: String, id: String, keyboards: [Keyboard]?, lexicalModels: [LexicalModel]?, font: Font?, oskFont: Font?) {
self.name = name
self.id = id
self.keyboards = keyboards
self.lexicalModels = lexicalModels
self.font = font
self.oskFont = oskFont
}
}
| apache-2.0 | 52915e02a88690f6cd0982182a29cd4c | 22.142857 | 119 | 0.67284 | 3.965035 | false | false | false | false |
nanthi1990/SwiftCharts | Examples/Examples/HelloWorld.swift | 2 | 3461 | //
// HelloWorld.swift
// SwiftCharts
//
// Created by ischuetz on 05/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class HelloWorld: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
// map model data to chart points
let chartPoints: [ChartPoint] = [(2, 2), (4, 4), (6, 6), (8, 10), (12, 14)].map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))}
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
// define x and y axis values (quick-demo way, see other examples for generation based on chartpoints)
let xValues = Array(stride(from: 0, through: 16, by: 2)).map {ChartAxisValueInt($0, labelSettings: labelSettings)}
let yValues = Array(stride(from: 0, through: 16, by: 2)).map {ChartAxisValueInt($0, labelSettings: labelSettings)}
// create axis models with axis values and axis title
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
// generate axes layers and calculate chart inner frame, based on the axis models
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
// create layer with guidelines
var guidelinesLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: guidelinesLayerSettings)
// view generator - this is a function that creates a view for each chartpoint
let viewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsViewsLayer, chart: Chart) -> UIView? in
let viewSize: CGFloat = Env.iPad ? 30 : 20
let center = chartPointModel.screenLoc
let label = UILabel(frame: CGRectMake(center.x - viewSize / 2, center.y - viewSize / 2, viewSize, viewSize))
label.backgroundColor = UIColor.greenColor()
label.textAlignment = NSTextAlignment.Center
label.text = "\(chartPointModel.chartPoint.y.text)"
label.font = ExamplesDefaults.labelFont
return label
}
// create layer that uses viewGenerator to display chartpoints
let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: viewGenerator)
// create chart instance with frame and layers
let chart = Chart(
frame: chartFrame,
layers: [
coordsSpace.xAxis,
coordsSpace.yAxis,
guidelinesLayer,
chartPointsLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | eebfdde08817a8afda2878069ef62647 | 47.746479 | 165 | 0.66946 | 5.236006 | false | false | false | false |
giapnh/TadiSDK | TadiSDK/Classes/Extensions/UIView+Extension.swift | 1 | 1259 | //
// UIView+Extension.swift
// TADI Shared SDK
// Version: 1.0
//
// Created by Duong Van Lam on 11/18/16.
// Copyright © 2016 TADI. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
func addTopBorder() {
if self.layer.value(forKey: TOP_BORDER_VIEW) != nil {
return
}
// add top border
let border = UIView(frame: CGRect(x: 0, y: 0, width: self.layer.frame.width, height: 1 / UIScreen.main.scale))
border.backgroundColor = UIColor(hex: 0xf0f0f0)
self.layer.setValue(border, forKey: TOP_BORDER_VIEW)
self.addSubview(border)
}
}
| mit | 2d16d9f93d1950f08bc3f06f4ce0f933 | 22.735849 | 118 | 0.54849 | 4.278912 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.