repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ztyjr888/WeChat | WeChat/Contact/Detail/ResourceDetailViewController.swift | 1 | 8282 | //
// ResourceDetailViewController.swift
// WeChat
//
// Created by Smile on 16/1/10.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
//详细资料页面
class ResourceDetailViewController: WeChatTableFooterBlankController{
//MARKS: Properties
@IBOutlet weak var photoView: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var weChatNumber: UILabel!
@IBOutlet weak var personLabel: UILabel!
@IBOutlet weak var phoneNumber: UILabel!
//MARKS; 发消息按钮事件
@IBAction func sendMessage(sender: UIButton) {
let weChatChatViewController = WeChatChatViewController()
weChatChatViewController.nagTitle = self.nameText
self.navigationController?.pushViewController(weChatChatViewController, animated: true)
}
var nameText:String?
var photoImage:UIImage?
var weChatNumberText:String?
var indexPath:NSIndexPath?
var photoNumberText:String?
var parentController:ContactViewController?
override func viewDidLoad() {
super.viewDidLoad()
initFrame()
initData()
initImages()
}
//MARKS: 初始化图片控件
func initImages(){
var images:[UIImage] = [UIImage]()
images.append(UIImage(named: "contact2")!)
images.append(UIImage(named: "contact3")!)
images.append(UIImage(named: "contact1")!)
images.append(UIImage(named: "contact2")!)
let indexPath = NSIndexPath(forRow: 1, inSection: 2)
let cell = tableView.cellForRowAtIndexPath(indexPath)
let weChatPhotoView = WeChatContactPhotoView(frame: CGRectMake(90, 0, UIScreen.mainScreen().bounds.width - 90 - 30, cell!.frame.height), images: images)
cell?.addSubview(weChatPhotoView)
}
func initFrame(){
self.navigationController?.navigationBarHidden = false
self.navigationItem.rightBarButtonItem?.enabled = false
//设置右侧按钮文字为三个点
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "● ● ●", style: UIBarButtonItemStyle.Plain, target: self, action: "moreBtnClick")
self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor(),NSFontAttributeName:UIFont(name: "Arial-BoldMT", size: 10)!], forState: UIControlState.Normal)
initTableView()
//MARKS: 去掉tableview底部空白
createFooterForTableView()
//添加点击事件
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "phoneClick:")
phoneNumber.userInteractionEnabled = true
phoneNumber.addGestureRecognizer(tap)
}
//MARKS: 电话拨号功能,短信是sms,telprompt弹出确认对话框
func phoneClick(gestrue: UITapGestureRecognizer){
//let url = NSURL(string: "tel://\(photoNumberText!)")
let url = NSURL(string: "telprompt://\(photoNumberText!)")
if UIApplication.sharedApplication().canOpenURL(url!){
UIApplication.sharedApplication().openURL(url!)
}
}
func initData(){
self.photoView.image = photoImage
self.name.text = nameText
self.weChatNumber.text = weChatNumberText
//替换 - 为空字符
if photoNumberText?.characters.count > 0 {
photoNumberText = photoNumberText!.stringByReplacingOccurrencesOfString("-", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
self.phoneNumber.text = photoNumberText
self.phoneNumber.textColor = UIColor(red: 51/255, green: 153/255, blue: 204/255, alpha: 1)
}
//右侧...点击事件
func moreBtnClick(){
print("more click...")
}
//MARKS: 取消tableview cell选中状态,使用尾部闭包
override func viewWillAppear(animated: Bool) {
setCellStyleNone()
}
func setCellStyleNone(){
for(var i = 0;i < tableView.numberOfSections; i++){
for(var j = 0;j < tableView.numberOfRowsInSection(i);j++){
let indexPath = NSIndexPath(forRow: j, inSection: i)
let cell = tableView.cellForRowAtIndexPath(indexPath)
if tableView.numberOfRowsInSection(i) == 1 && i != 3 {
//画线条
let shape = WeChatDrawView().drawLine(beginPointX: 0, beginPointY: 0, endPointX: UIScreen.mainScreen().bounds.width, endPointY: 0,color:UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 1))
cell!.layer.addSublayer(shape)
}
if (j == 0 || j == (tableView.numberOfRowsInSection(i) - 1)) && i != 3{
var beginY:CGFloat = 0
if j == (tableView.numberOfRowsInSection(i) - 1) {
beginY = cell!.frame.height
}
//画线条
let shape = WeChatDrawView().drawLine(beginPointX: 0, beginPointY: beginY, endPointX: UIScreen.mainScreen().bounds.width, endPointY: beginY,color:UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 1))
cell!.layer.addSublayer(shape)
}
if (i == 1 && j == 0) || (i == 2 && j == 1) || (i == 2 && j == 2){
continue
}
cell?.selectionStyle = .None
if i == 3 && j == 0 {
cell!.backgroundColor = UIColor.clearColor()
cell!.backgroundColor = self.getBackgroundColor()
//MARKS: 去掉最后一行cell的分割线
cell!.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell!.bounds.size.width);
}
}
}
}
//MARKS: 页面跳转,参数传递
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "socialInfo" {//跳转到社交资料页面
//let socialDetailController = segue.destinationViewController as! SocialDetailViewController
} else if segue.identifier == "markInfo"{//跳转到备注信息页面
let remarkTagController = segue.destinationViewController as! RemarkTagViewController
remarkTagController.remarkText = self.name.text
}else if segue.identifier == "personInfo" {
let persionInfoController = segue.destinationViewController as! PersonViewController
persionInfoController.navigationTitle = self.name.text
persionInfoController.headerImage = self.photoView.image
}
//取消选中状态
tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow!, animated: false)
}
//MARKS: 去掉tableview随scrollview滚动的黏性
/*override func scrollViewDidScroll(scrollView: UIScrollView) {
if (scrollView.contentOffset.y <= CELL_HEADER_HEIGHT && scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y >= CELL_HEADER_HEIGHT) {
scrollView.contentInset = UIEdgeInsetsMake(-CELL_HEADER_HEIGHT, 0, 0, 0);
}
}*/
/*
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
let drawView = DrawView(frame: CGRectMake(0,cell.frame.origin.y,self.view.bounds.width,self.view.bounds.height))
self.view.addSubview(drawView)
}
}
//画直线
func drawCellBorder(y:CGFloat){
let context:CGContextRef = UIGraphicsGetCurrentContext()!;//获取画笔上下文
CGContextSetAllowsAntialiasing(context, true) //抗锯齿设置
CGContextSetLineWidth(context, 5) //设置画笔宽度
CGContextMoveToPoint(context, 0, y);
CGContextAddLineToPoint(context, 0, self.view.bounds.width);
CGContextStrokePath(context)
}*/
}
| apache-2.0 | 86684a17089dde2b070bc11b25cc564a | 39.774359 | 229 | 0.619922 | 4.789759 | false | false | false | false |
JohnEstropia/CoreStore | Sources/FieldStorableType.swift | 1 | 5827 | //
// FieldStorableType.swift
// CoreStore
//
// Copyright © 2020 John Rommel Estropia
//
// 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 CoreData
import Foundation
import CoreGraphics
// MARK: - FieldStorableType
/**
Values to be used for `Field.Stored` properties.
*/
public protocol FieldStorableType {
/**
The `NSAttributeType` for this type
*/
associatedtype FieldStoredNativeType
/**
The `NSAttributeType` for this type. Used internally by CoreStore. Do not call directly.
*/
static var cs_rawAttributeType: NSAttributeType { get }
/**
Creates an instance of this type from raw native value. Used internally by CoreStore. Do not call directly.
*/
@inline(__always)
static func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self
/**
Creates `FieldStoredNativeType` value from this instance. Used internally by CoreStore. Do not call directly.
*/
@inline(__always)
func cs_toFieldStoredNativeType() -> Any?
}
// MARK: - FieldStorableType where Self: ImportableAttributeType, FieldStoredNativeType == QueryableNativeType
extension FieldStorableType where Self: ImportableAttributeType, FieldStoredNativeType == QueryableNativeType {
@inline(__always)
public static func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
@inline(__always)
public func cs_toFieldStoredNativeType() -> Any? {
return self.cs_toQueryableNativeType()
}
}
// MARK: - Bool
extension Bool: FieldStorableType {}
// MARK: - CGFloat
extension CGFloat: FieldStorableType {}
// MARK: - Data
extension Data: FieldStorableType {}
// MARK: - Date
extension Date: FieldStorableType {}
// MARK: - Double
extension Double: FieldStorableType {}
// MARK: - Float
extension Float: FieldStorableType {}
// MARK: - Int
extension Int: FieldStorableType {}
// MARK: - Int8
extension Int8: FieldStorableType {}
// MARK: - Int16
extension Int16: FieldStorableType {}
// MARK: - Int32
extension Int32: FieldStorableType {}
// MARK: - Int64
extension Int64: FieldStorableType {}
// MARK: - NSData
extension NSData: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - NSDate
extension NSDate: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - NSNumber
extension NSNumber: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - NSString
extension NSString: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - NSURL
extension NSURL: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - NSUUID
extension NSUUID: FieldStorableType {
@nonobjc @inline(__always)
public class func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
return self.cs_fromQueryableNativeType(value)!
}
}
// MARK: - String
extension String: FieldStorableType {}
// MARK: - URL
extension URL: FieldStorableType {}
// MARK: - UUID
extension UUID: FieldStorableType {}
// MARK: - Optional<FieldStorableType>
extension Optional: FieldStorableType where Wrapped: FieldStorableType {
// MARK: FieldStorableType
public typealias FieldStoredNativeType = Wrapped.FieldStoredNativeType?
public static var cs_rawAttributeType: NSAttributeType {
return Wrapped.cs_rawAttributeType
}
@inline(__always)
public static func cs_fromFieldStoredNativeType(_ value: FieldStoredNativeType) -> Self {
switch value {
case nil,
is NSNull:
return nil
case let value?:
return Wrapped.cs_fromFieldStoredNativeType(value)
}
}
@inline(__always)
public func cs_toFieldStoredNativeType() -> Any? {
switch self {
case nil,
is NSNull:
return nil
case let value?:
return value.cs_toFieldStoredNativeType()
}
}
}
| mit | 726f201a1066d1a05414f86150b5ed8a | 21.236641 | 119 | 0.697734 | 4.277533 | false | false | false | false |
KempinGe/LiveBroadcast | LIveBroadcast/LIveBroadcast/classes/Tools/Extension/UIBarButtonItem+Extension.swift | 1 | 1247 | //
// UIBarButtonItem+Extension.swift
// LIveBroadcast
//
// Created by 盖凯宾 on 16/11/22.
// Copyright © 2016年 盖凯宾. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/** 扩充的类方法
class func creatItem(imageName:String, highlightName:String, size : CGSize) {
let btn = UIButton()
btn.setImage(UIImage.init(named: imageName), for: UIControlState.normal)
btn.setImage(UIImage.init(named: highlightName), for: UIControlState.highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
*/
//便利构造方法 需要调用设计构造函数
convenience init(imageName:String, highlightName:String = "", size : CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage.init(named: imageName), for: UIControlState.normal)
if highlightName != "" {
btn.setImage(UIImage.init(named: highlightName), for: UIControlState.highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
print(btn.frame.size)
}else{
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView:btn)
}
}
| mit | e0d3fc777e4f5ee17b9516b93be786f6 | 27.97561 | 96 | 0.613636 | 4.027119 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/Moya/Sources/Moya/Plugins/NetworkLoggerPlugin.swift | 31 | 4305 | import Foundation
import Result
/// Logs network activity (outgoing requests and incoming responses).
public final class NetworkLoggerPlugin: PluginType {
fileprivate let loggerId = "Moya_Logger"
fileprivate let dateFormatString = "dd/MM/yyyy HH:mm:ss"
fileprivate let dateFormatter = DateFormatter()
fileprivate let separator = ", "
fileprivate let terminator = "\n"
fileprivate let cURLTerminator = "\\\n"
fileprivate let output: (_ separator: String, _ terminator: String, _ items: Any...) -> Void
fileprivate let responseDataFormatter: ((Data) -> (Data))?
/// If true, also logs response body data.
public let isVerbose: Bool
public let cURL: Bool
public init(verbose: Bool = false, cURL: Bool = false, output: @escaping (_ separator: String, _ terminator: String, _ items: Any...) -> Void = NetworkLoggerPlugin.reversedPrint, responseDataFormatter: ((Data) -> (Data))? = nil) {
self.cURL = cURL
self.isVerbose = verbose
self.output = output
self.responseDataFormatter = responseDataFormatter
}
public func willSend(_ request: RequestType, target: TargetType) {
if let request = request as? CustomDebugStringConvertible, cURL {
output(separator, terminator, request.debugDescription)
return
}
outputItems(logNetworkRequest(request.request as URLRequest?))
}
public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
if case .success(let response) = result {
outputItems(logNetworkResponse(response.response, data: response.data, target: target))
} else {
outputItems(logNetworkResponse(nil, data: nil, target: target))
}
}
fileprivate func outputItems(_ items: [String]) {
if isVerbose {
items.forEach { output(separator, terminator, $0) }
} else {
output(separator, terminator, items)
}
}
}
private extension NetworkLoggerPlugin {
var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.string(from: Date())
}
func format(_ loggerId: String, date: String, identifier: String, message: String) -> String {
return "\(loggerId): [\(date)] \(identifier): \(message)"
}
func logNetworkRequest(_ request: URLRequest?) -> [String] {
var output = [String]()
output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")]
if let headers = request?.allHTTPHeaderFields {
output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)]
}
if let bodyStream = request?.httpBodyStream {
output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)]
}
if let httpMethod = request?.httpMethod {
output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)]
}
if let body = request?.httpBody, let stringOutput = String(data: body, encoding: .utf8), isVerbose {
output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)]
}
return output
}
func logNetworkResponse(_ response: URLResponse?, data: Data?, target: TargetType) -> [String] {
guard let response = response else {
return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")]
}
var output = [String]()
output += [format(loggerId, date: date, identifier: "Response", message: response.description)]
if let data = data, let stringData = String(data: responseDataFormatter?(data) ?? data, encoding: String.Encoding.utf8), isVerbose {
output += [stringData]
}
return output
}
}
fileprivate extension NetworkLoggerPlugin {
static func reversedPrint(_ separator: String, terminator: String, items: Any...) {
for item in items {
print(item, separator: separator, terminator: terminator)
}
}
}
| mit | dd00d1aca21a22e1b69e5b7afc4fced0 | 37.783784 | 234 | 0.645528 | 4.772727 | false | false | false | false |
ali-zahedi/AZViewer | AZViewer/AZPopupPickerView.swift | 1 | 6485 | //
// AZPickerView.swift
// AZViewer
//
// Created by Ali Zahedi on 1/6/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import Foundation
public class AZPopupPickerView: AZView{
// MARK: Public
public var popup: AZPicker = AZPicker()
public var separatorSection: String = "/" {
didSet{
self.submitPopupView()
}
}
public var index: [Int: Int]{
get{
return self._index
}
}
public var data: [[(AnyObject, String)]] = [[]] {
didSet{
self.popup.data = self.data
self.input.text = ""
// for restor after load dynamic another component
let index = self._indexTemp
self._index = [:]
self._indexTemp = [:]
for (i, _) in self.data.enumerated(){
// check out of range
if self.data[i].count > 0{
// restore last position
if index.count > i, self.data[i].count > index[i]! {
self.selected(indexPath: IndexPath(row: index[i]!, section: i))
}else{
self.selected(indexPath: IndexPath(row: 0, section: i))
}
}
}
}
}
public var icon: UIImage! {
didSet{
self.input.leftIcon = icon
}
}
public var delegate: AZPopupViewDelegate?
public var titleFont: UIFont!{
didSet{
self.input.font = self.titleFont
}
}
public var pickerFont: UIFont!{
didSet{
self.popup.font = self.pickerFont
}
}
public var pickerColor: UIColor!{
didSet{
self.popup.color = self.pickerColor
}
}
// internal
internal var input: AZLabelIcon = AZLabelIcon()
// private
fileprivate var _index: [Int: Int] = [:]
fileprivate var _indexTemp: [Int: Int] = [:]
// override
override public init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
fileprivate func defaultInit(){
for v in [input] as [UIView]{
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
self.preparePickerView()
self.prepareInputPickerView()
}
}
// prepare
extension AZPopupPickerView{
// pickerview
// TODO: Check
fileprivate func preparePickerView(){
self.popup.delegate = self
self.popup.delegatePopupView = self
self.popup.translatesAutoresizingMaskIntoConstraints = true
let width: CGFloat = UIScreen.main.bounds.width
let height: CGFloat = 120
let position = CGPoint(x: 0, y: UIScreen.main.bounds.height - height)
self.popup.frame.size = CGSize(width: width, height: height)
self.popup.frame.origin = position
self.pickerColor = self.style.sectionPickerViewItemColor
self.pickerFont = self.style.sectionPickerViewItemFont
}
// input
fileprivate func prepareInputPickerView(){
//self.input.addTarget(self, action: #selector(inputPickerViewAction), for: .touchDown)
// add gesture
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(inputPickerViewAction(gr:)))
tap.delegate = self
self.input.addGestureRecognizer(tap)
self.input.isUserInteractionEnabled = true
self.titleFont = self.style.sectionInputFont
self.input.textAlignment = .center
self.input.tintColor = UIColor.clear
_ = self.input.aZConstraints.parent(parent: self).top().right().left().bottom()
self.input.leftIcon = AZAssets.expandImage
}
}
extension AZPopupPickerView: AZPickerViewDelegate {
public func aZPickerView(didSelectRow row: Int, inComponent component: Int) {
self._indexTemp[component] = row
}
public func selected(indexPath: IndexPath){
self.selectedWithoutSubmit(indexPath: indexPath)
self.submitPopupView()
}
fileprivate func selectedWithoutSubmit(indexPath: IndexPath){
self.popup.pickerView.selectRow(indexPath.row, inComponent: indexPath.section, animated: true)
self.popup.pickerView(self.popup.pickerView, didSelectRow: indexPath.row, inComponent: indexPath.section)
}
}
// popupview
extension AZPopupPickerView: AZPopupViewDelegate{
// submit
public func submitPopupView() {
// set index
self._index = self._indexTemp
// show on input
var string = ""
if self.data.count > 0 {
for i in (0...(self.data.count - 1)).reversed(){
// check array range
if let row = self.index[i], self.data[i].count > row{
string += self.data[i][row].1 + self.separatorSection
}
}
string = string.trimmingCharacters(in: CharacterSet(charactersIn: self.separatorSection))
self.input.text = string
// call delegate
self.delegate?.submitPopupView()
}
}
// cancel
public func cancelPopupView() {
// reset index
if self._index == self._indexTemp{
return
}
self._indexTemp = self._index
for (i, _) in self.data.enumerated(){
// check array range
if let row = self.index[i], self.data[i].count > row{
self.selectedWithoutSubmit(indexPath: IndexPath(row: row, section: i))
}
}
// call delegate
self.delegate?.cancelPopupView()
}
}
// gesture recognizer
extension AZPopupPickerView: UIGestureRecognizerDelegate{
// tap on input
func inputPickerViewAction(gr:UITapGestureRecognizer){
// check for load all data and then show
if self.index.count == self.data.count {
self.popup.show()
}else{
NSLog("AZPicker View data doesn't load ")
}
}
}
| apache-2.0 | 8ffd6f0faadd757d90412c1ec6be2b2c | 26.948276 | 124 | 0.557064 | 4.757153 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/IndexPath.swift | 1 | 28156 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
func _NSIndexPathCreateFromIndexes(_ idx1: Int, _ idx2: Int) -> NSObject {
var indexes = (idx1, idx2)
return withUnsafeBytes(of: &indexes) { (ptr) -> NSIndexPath in
return NSIndexPath.init(indexes: ptr.baseAddress!.assumingMemoryBound(to: Int.self), length: 2)
}
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
#endif
/**
`IndexPath` represents the path to a specific node in a tree of nested array collections.
Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node.
*/
public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableCollection, RandomAccessCollection, Comparable, ExpressibleByArrayLiteral {
public typealias ReferenceType = NSIndexPath
public typealias Element = Int
public typealias Index = Array<Int>.Index
public typealias Indices = DefaultIndices<IndexPath>
fileprivate enum Storage : ExpressibleByArrayLiteral {
typealias Element = Int
case empty
case single(Int)
case pair(Int, Int)
case array([Int])
init(arrayLiteral elements: Int...) {
self.init(elements)
}
init(_ elements: [Int]) {
switch elements.count {
case 0:
self = .empty
case 1:
self = .single(elements[0])
case 2:
self = .pair(elements[0], elements[1])
default:
self = .array(elements)
}
}
func dropLast() -> Storage {
switch self {
case .empty:
return .empty
case .single:
return .empty
case .pair(let first, _):
return .single(first)
case .array(let indexes):
switch indexes.count {
case 3:
return .pair(indexes[0], indexes[1])
default:
return .array(Array<Int>(indexes.dropLast()))
}
}
}
mutating func append(_ other: Int) {
switch self {
case .empty:
self = .single(other)
case .single(let first):
self = .pair(first, other)
case .pair(let first, let second):
self = .array([first, second, other])
case .array(let indexes):
self = .array(indexes + [other])
}
}
mutating func append(contentsOf other: Storage) {
switch self {
case .empty:
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .single(rhsIndex)
case .pair(let rhsFirst, let rhsSecond):
self = .pair(rhsFirst, rhsSecond)
case .array(let rhsIndexes):
self = .array(rhsIndexes)
}
case .single(let lhsIndex):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .pair(lhsIndex, rhsIndex)
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsIndex, rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array([lhsIndex] + rhsIndexes)
}
case .pair(let lhsFirst, let lhsSecond):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array([lhsFirst, lhsSecond, rhsIndex])
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsFirst, lhsSecond, rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array([lhsFirst, lhsSecond] + rhsIndexes)
}
case .array(let lhsIndexes):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array(lhsIndexes + [rhsIndex])
case .pair(let rhsFirst, let rhsSecond):
self = .array(lhsIndexes + [rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array(lhsIndexes + rhsIndexes)
}
}
}
mutating func append(contentsOf other: [Int]) {
switch self {
case .empty:
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .single(other[0])
case 2:
self = .pair(other[0], other[1])
default:
self = .array(other)
}
case .single(let first):
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .pair(first, other[0])
default:
self = .array([first] + other)
}
case .pair(let first, let second):
switch other.count {
case 0:
// DO NOTHING
break
default:
self = .array([first, second] + other)
}
case .array(let indexes):
self = .array(indexes + other)
}
}
subscript(_ index: Int) -> Int {
get {
switch self {
case .empty:
fatalError("index \(index) out of bounds of count 0")
case .single(let first):
precondition(index == 0, "index \(index) out of bounds of count 1")
return first
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "index \(index) out of bounds of count 2")
return index == 0 ? first : second
case .array(let indexes):
return indexes[index]
}
}
set {
switch self {
case .empty:
fatalError("index \(index) out of bounds of count 0")
case .single:
precondition(index == 0, "index \(index) out of bounds of count 1")
self = .single(newValue)
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "index \(index) out of bounds of count 2")
if index == 0 {
self = .pair(newValue, second)
} else {
self = .pair(first, newValue)
}
case .array(var indexes):
indexes[index] = newValue
self = .array(indexes)
}
}
}
subscript(range: Range<Index>) -> Storage {
get {
switch self {
case .empty:
switch (range.lowerBound, range.upperBound) {
case (0, 0):
return .empty
default:
fatalError("range \(range) is out of bounds of count 0")
}
case .single(let index):
switch (range.lowerBound, range.upperBound) {
case (0, 0): fallthrough
case (1, 1):
return .empty
case (0, 1):
return .single(index)
default:
fatalError("range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
fallthrough
case (1, 1):
fallthrough
case (2, 2):
return .empty
case (0, 1):
return .single(first)
case (1, 2):
return .single(second)
case (0, 2):
return self
default:
fatalError("range \(range) is out of bounds of count 2")
}
case .array(let indexes):
let slice = indexes[range]
switch slice.count {
case 0:
return .empty
case 1:
return .single(slice[0])
case 2:
return .pair(slice[0], slice[1])
default:
return .array(Array<Int>(slice))
}
}
}
set {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "range \(range) is out of bounds of count 0")
self = newValue
case .single(let index):
switch (range.lowerBound, range.upperBound, newValue) {
case (0, 0, .empty):
fallthrough
case (1, 1, .empty):
break
case (0, 0, .single(let other)):
self = .pair(other, index)
case (0, 0, .pair(let first, let second)):
self = .array([first, second, index])
case (0, 0, .array(let other)):
self = .array(other + [index])
case (0, 1, .empty):
fallthrough
case (0, 1, .single):
fallthrough
case (0, 1, .pair):
fallthrough
case (0, 1, .array):
self = newValue
case (1, 1, .single(let other)):
self = .pair(index, other)
case (1, 1, .pair(let first, let second)):
self = .array([index, first, second])
case (1, 1, .array(let other)):
self = .array([index] + other)
default:
fatalError("range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([other, first, second])
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, first, second])
case .array(let other):
self = .array(other + [first, second])
}
case (0, 1):
switch newValue {
case .empty:
self = .single(second)
case .single(let other):
self = .pair(other, second)
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, second])
case .array(let other):
self = .array(other + [second])
}
case (0, 2):
self = newValue
case (1, 2):
switch newValue {
case .empty:
self = .single(first)
case .single(let other):
self = .pair(first, other)
case .pair(let otherFirst, let otherSecond):
self = .array([first, otherFirst, otherSecond])
case .array(let other):
self = .array([first] + other)
}
case (2, 2):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([first, second, other])
case .pair(let otherFirst, let otherSecond):
self = .array([first, second, otherFirst, otherSecond])
case .array(let other):
self = .array([first, second] + other)
}
default:
fatalError("range \(range) is out of bounds of count 2")
}
case .array(let indexes):
var newIndexes = indexes
newIndexes.removeSubrange(range)
switch newValue {
case .empty:
break
case .single(let index):
newIndexes.insert(index, at: range.lowerBound)
case .pair(let first, let second):
newIndexes.insert(first, at: range.lowerBound)
newIndexes.insert(second, at: range.lowerBound + 1)
case .array(let other):
newIndexes.insert(contentsOf: other, at: range.lowerBound)
}
self = Storage(newIndexes)
}
}
}
var count: Int {
switch self {
case .empty:
return 0
case .single:
return 1
case .pair:
return 2
case .array(let indexes):
return indexes.count
}
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return count
}
var allValues: [Int] {
switch self {
case .empty: return []
case .single(let index): return [index]
case .pair(let first, let second): return [first, second]
case .array(let indexes): return indexes
}
}
func index(before i: Int) -> Int {
return i - 1
}
func index(after i: Int) -> Int {
return i + 1
}
var description: String {
switch self {
case .empty:
return "[]"
case .single(let index):
return "[\(index)]"
case .pair(let first, let second):
return "[\(first), \(second)]"
case .array(let indexes):
return indexes.description
}
}
func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Int>) throws -> R) rethrows -> R {
switch self {
case .empty:
return try body(UnsafeBufferPointer<Int>(start: nil, count: 0))
case .single(var index):
return try withUnsafePointer(to: &index) { (start) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: start, count: 1))
}
case .pair(let first, let second):
var pair = (first, second)
return try withUnsafeBytes(of: &pair) { (rawBuffer: UnsafeRawBufferPointer) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: rawBuffer.baseAddress?.assumingMemoryBound(to: Int.self), count: 2))
}
case .array(let indexes):
return try indexes.withUnsafeBufferPointer(body)
}
}
var debugDescription: String { return description }
static func +(_ lhs: Storage, _ rhs: Storage) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func +(_ lhs: Storage, _ rhs: [Int]) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func ==(_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.empty, .empty):
return true
case (.single(let lhsIndex), .single(let rhsIndex)):
return lhsIndex == rhsIndex
case (.pair(let lhsFirst, let lhsSecond), .pair(let rhsFirst, let rhsSecond)):
return lhsFirst == rhsFirst && lhsSecond == rhsSecond
case (.array(let lhsIndexes), .array(let rhsIndexes)):
return lhsIndexes == rhsIndexes
default:
return false
}
}
}
fileprivate var _indexes : Storage
/// Initialize an empty index path.
public init() {
_indexes = []
}
/// Initialize with a sequence of integers.
public init<ElementSequence : Sequence>(indexes: ElementSequence)
where ElementSequence.Iterator.Element == Element {
_indexes = Storage(indexes.map { $0 })
}
/// Initialize with an array literal.
public init(arrayLiteral indexes: Element...) {
_indexes = Storage(indexes)
}
/// Initialize with an array of elements.
public init(indexes: Array<Element>) {
_indexes = Storage(indexes)
}
fileprivate init(storage: Storage) {
_indexes = storage
}
/// Initialize with a single element.
public init(index: Element) {
_indexes = [index]
}
/// Return a new `IndexPath` containing all but the last element.
public func dropLast() -> IndexPath {
return IndexPath(storage: _indexes.dropLast())
}
/// Append an `IndexPath` to `self`.
public mutating func append(_ other: IndexPath) {
_indexes.append(contentsOf: other._indexes)
}
/// Append a single element to `self`.
public mutating func append(_ other: Element) {
_indexes.append(other)
}
/// Append an array of elements to `self`.
public mutating func append(_ other: Array<Element>) {
_indexes.append(contentsOf: other)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Element) -> IndexPath {
var result = _indexes
result.append(other)
return IndexPath(storage: result)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: IndexPath) -> IndexPath {
return IndexPath(storage: _indexes + other._indexes)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Array<Element>) -> IndexPath {
return IndexPath(storage: _indexes + other)
}
public subscript(index: Index) -> Element {
get {
return _indexes[index]
}
set {
_indexes[index] = newValue
}
}
public subscript(range: Range<Index>) -> IndexPath {
get {
return IndexPath(storage: _indexes[range])
}
set {
_indexes[range] = newValue._indexes
}
}
public func makeIterator() -> IndexingIterator<IndexPath> {
return IndexingIterator(_elements: self)
}
public var count: Int {
return _indexes.count
}
public var startIndex: Index {
return _indexes.startIndex
}
public var endIndex: Index {
return _indexes.endIndex
}
public func index(before i: Index) -> Index {
return _indexes.index(before: i)
}
public func index(after i: Index) -> Index {
return _indexes.index(after: i)
}
/// Sorting an array of `IndexPath` using this comparison results in an array representing nodes in depth-first traversal order.
public func compare(_ other: IndexPath) -> ComparisonResult {
let thisLength = count
let otherLength = other.count
let length = Swift.min(thisLength, otherLength)
for idx in 0..<length {
let otherValue = other[idx]
let value = self[idx]
if value < otherValue {
return .orderedAscending
} else if value > otherValue {
return .orderedDescending
}
}
if thisLength > otherLength {
return .orderedDescending
} else if thisLength < otherLength {
return .orderedAscending
}
return .orderedSame
}
public func hash(into hasher: inout Hasher) {
// Note: We compare all indices in ==, so for proper hashing, we must
// also feed them all to the hasher.
//
// To ensure we have unique hash encodings in nested hashing contexts,
// we combine the count of indices as well as the indices themselves.
// (This matches what Array does.)
switch _indexes {
case .empty:
hasher.combine(0)
case let .single(index):
hasher.combine(1)
hasher.combine(index)
case let .pair(first, second):
hasher.combine(2)
hasher.combine(first)
hasher.combine(second)
case let .array(indexes):
hasher.combine(indexes.count)
for index in indexes {
hasher.combine(index)
}
}
}
// MARK: - Bridging Helpers
fileprivate init(nsIndexPath: ReferenceType) {
let count = nsIndexPath.length
if count == 0 {
_indexes = []
} else if count == 1 {
_indexes = .single(nsIndexPath.index(atPosition: 0))
} else if count == 2 {
_indexes = .pair(nsIndexPath.index(atPosition: 0), nsIndexPath.index(atPosition: 1))
} else {
var indexes = Array<Int>(repeating: 0, count: count)
indexes.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int>) -> Void in
nsIndexPath.getIndexes(buffer.baseAddress!, range: NSRange(location: 0, length: count))
}
_indexes = .array(indexes)
}
}
fileprivate func makeReference() -> ReferenceType {
switch _indexes {
case .empty:
return ReferenceType()
case .single(let index):
return ReferenceType(index: index)
case .pair(let first, let second):
return _NSIndexPathCreateFromIndexes(first, second) as! ReferenceType
default:
return _indexes.withUnsafeBufferPointer {
return ReferenceType(indexes: $0.baseAddress, length: $0.count)
}
}
}
public static func ==(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs._indexes == rhs._indexes
}
public static func +(lhs: IndexPath, rhs: IndexPath) -> IndexPath {
return lhs.appending(rhs)
}
public static func +=(lhs: inout IndexPath, rhs: IndexPath) {
lhs.append(rhs)
}
public static func <(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
public static func <=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == .orderedAscending || order == .orderedSame
}
public static func >(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == .orderedDescending
}
public static func >=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == .orderedDescending || order == .orderedSame
}
}
extension IndexPath : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return _indexes.description
}
public var debugDescription: String {
return _indexes.debugDescription
}
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
extension IndexPath : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSIndexPath.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexPath {
return makeReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) {
result = IndexPath(nsIndexPath: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) -> Bool {
result = IndexPath(nsIndexPath: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexPath?) -> IndexPath {
guard let src = source else { return IndexPath() }
return IndexPath(nsIndexPath: src)
}
}
extension NSIndexPath : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(IndexPath(nsIndexPath: self))
}
}
extension IndexPath : Codable {
private enum CodingKeys : Int, CodingKey {
case indexes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var indexesContainer = try container.nestedUnkeyedContainer(forKey: .indexes)
var indexes = [Int]()
if let count = indexesContainer.count {
indexes.reserveCapacity(count)
}
while !indexesContainer.isAtEnd {
let index = try indexesContainer.decode(Int.self)
indexes.append(index)
}
self.init(indexes: indexes)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var indexesContainer = container.nestedUnkeyedContainer(forKey: .indexes)
switch self._indexes {
case .empty:
break
case .single(let index):
try indexesContainer.encode(index)
case .pair(let first, let second):
try indexesContainer.encode(first)
try indexesContainer.encode(second)
case .array(let indexes):
try indexesContainer.encode(contentsOf: indexes)
}
}
}
| apache-2.0 | d56f9a6481e35cd10b97d227edd2e217 | 35.005115 | 151 | 0.483414 | 5.372257 | false | false | false | false |
nickswalker/BubblesView | Example/BubblesView/ColorNeigborhoodDataSource.swift | 2 | 2496 | //
// Copyright (c) 2016 Nick Walker.
// 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 BubblesView
import HSLuvSwift
class BubblesViewHueSpaceDataSource: BubblesViewDataSource {
// Indices will be into an imaginary array of size sum 8]6^k for k in 0...h
var focused: Int = 50
init(levels: Int, divisions: Int) {
}
func focusedBubble() -> Int {
return focused
}
// This is a tree, so the related are children
func relatedForBubble(_ index: Int) -> Set<Int> {
var results = Set<Int>()
for i in -4...3 where i != 0{
let wrapped = { () -> Int in
var neighbor: Int = (index + i * 3) % 360
neighbor = neighbor < 0 ? 360 + neighbor : neighbor
return neighbor
}()
results.insert(wrapped)
}
return results
}
func configureBubble(_ index: Int) -> BubbleView {
let view = BubbleView()
view.backgroundColor = colorForPosition(index)
let hueDegrees = Float(index)
let hueString = String(format: "%.0f", hueDegrees)
//view.label.text = "\(hueString)°"
return view
}
fileprivate func colorForPosition(_ position: Int) -> UIColor {
return UIColor(hue: Double(position), saturation: 100.0, lightness: 60.0, alpha: 1.0)
}
func shouldAllowFocus(_ index: Int) -> Bool {
return true
}
}
| mit | 11111cf5d897ec1c3adb781dc9278045 | 33.652778 | 93 | 0.657315 | 4.32409 | false | false | false | false |
AaronMT/firefox-ios | Shared/Extensions/URLProtectionSpaceExtensions.swift | 10 | 1401 | /* 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
extension URLProtectionSpace {
public static func fromOrigin(_ origin: String) -> URLProtectionSpace {
// Break down the full url hostname into its scheme/protocol and host components
let hostnameURL = origin.asURL
let host = hostnameURL?.host ?? origin
let scheme = hostnameURL?.scheme ?? ""
// We should ignore any SSL or normal web ports in the URL.
var port = hostnameURL?.port ?? 0
if port == 443 || port == 80 {
port = 0
}
return URLProtectionSpace(host: host, port: port, protocol: scheme, realm: nil, authenticationMethod: nil)
}
public func urlString() -> String {
// If our host is empty, return nothing since it doesn't make sense to add the scheme or port.
guard !host.isEmpty else {
return ""
}
var urlString: String
if let p = `protocol` {
urlString = "\(p)://\(host)"
} else {
urlString = host
}
// Check for non-standard ports
if port != 0 && port != 443 && port != 80 {
urlString += ":\(port)"
}
return urlString
}
}
| mpl-2.0 | ec82c2c53b5ae0e53c69d5e7e4d8e827 | 31.581395 | 114 | 0.583155 | 4.548701 | false | false | false | false |
luvacu/swift-demo-app | PracticaFinal/Service/NetworkingService.swift | 1 | 3085 | //
// NetworkingService.swift
// PracticaFinal
//
// Created by Luis Valdés on 18/11/14.
// Copyright (c) 2014 Luis Valdés. All rights reserved.
//
import UIKit
class NetworkingService: NSObject {
class var sharedService: NetworkingService {
struct Static {
static let instance = NetworkingService()
}
return Static.instance
}
// Tries to retrieve a NSData object from the specified URL in a background thread.
// Note that the completion function will be executed on the main thread
func downloadData(fromUrl url: NSURL, withMainThreadCompletionBlock completionBlock: (NSData?) -> Void) {
self.downloadData(fromUrl: url, completionBlock: completionBlock, shouldExecuteCompletionBlockInMainThread: true)
}
// Tries to retrieve a NSData object from the specified URL in a background thread.
// Note that the completion function will be executed on the same background thread as the download process
func downloadData(fromUrl url: NSURL, withBackgroundThreadCompletionBlock completionBlock: (NSData?) -> Void) {
self.downloadData(fromUrl: url, completionBlock: completionBlock, shouldExecuteCompletionBlockInMainThread: false)
}
// MARK: - Private functions
// Tries to retrieve a NSData object from the specified URL in a background thread.
// Note that the completion function will be executed on the main thread or
// on the same background thread as the download process, depending on the parameter 'shouldExecuteCompletionBlockInMainThread'
func downloadData(fromUrl url: NSURL, completionBlock: (NSData?) -> Void, shouldExecuteCompletionBlockInMainThread: Bool) {
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { (dataUrl, response, error) in
var data: NSData?
if (error == nil && response != nil && (response as NSHTTPURLResponse).statusCode == 200) {
if (dataUrl != nil) {
// Create NSData
data = NSData(contentsOfURL:dataUrl)
if (data != nil && data!.length == 0) {
// Downloaded data is empty. Nullify
data = nil
}
}
} else {
if (error != nil) {
NSLog("Error downloading data. Error: %@", error)
}
if (response != nil) {
NSLog("Error downloading data. Response: %@", response)
}
}
if (data != nil) {
NSLog("Data downloaded successfully")
} else {
NSLog("Error downloading data or it was empty")
}
if (shouldExecuteCompletionBlockInMainThread) {
NSOperationQueue.mainQueue().addOperationWithBlock {
completionBlock(data)
}
} else {
completionBlock(data)
}
}
task.resume()
}
}
| mit | 35927c0e6e5e85c7c072861a3c472c64 | 40.662162 | 131 | 0.596821 | 5.408772 | false | false | false | false |
SquidKit/SquidKit | SquidKit/String+Utility.swift | 1 | 2667 | //
// String+Utility.swift
// SquidKit
//
// Created by Mike Leavy on 8/17/14.
// Copyright © 2017-2019 Squid Store, LLC. All rights reserved.
//
import UIKit
public extension String {
static func nonNilString(_ string:String?, stringForNil:String = "") -> String {
if let nonNilString = string {
return nonNilString
}
return stringForNil
}
static func guid() -> String {
let uuid:CFUUID = CFUUIDCreate(kCFAllocatorDefault)
let guid = CFUUIDCreateString(kCFAllocatorDefault, uuid) as NSString
return guid as String
}
static func deserializeJSON(_ jsonObject:AnyObject, pretty:Bool) -> String? {
var result:String?
if JSONSerialization.isValidJSONObject(jsonObject) {
let outputStream:OutputStream = OutputStream.toMemory()
outputStream.open()
var error:NSError?
let bytesWritten:Int = JSONSerialization.writeJSONObject(jsonObject, to: outputStream, options: pretty ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions(rawValue: 0), error: &error)
outputStream.close()
if bytesWritten > 0 {
if let data:Data = outputStream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) as? Data {
result = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String?
}
}
}
return result
}
func stringByTrimmingLeadingWhitespace() -> String {
if let range = self.range(of: "^\\s*", options:.regularExpression) {
let result = self.replacingCharacters(in: range, with: "")
return result
}
return self
}
func stringByTrimmingTrailingWhitespace() -> String {
if let range = self.range(of: "\\s*$", options:.regularExpression) {
let result = self.replacingCharacters(in: range, with: "")
return result
}
return self
}
func phoneDigitsString() -> String {
let characterSet = CharacterSet(charactersIn: "()- ")
let components = self.components(separatedBy: characterSet)
return components.joined(separator: "")
}
func phoneURL() -> URL {
return URL(string: "tel://\(self.phoneDigitsString())")!
}
func validEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
return predicate.evaluate(with: self)
}
}
| mit | 3dd9098237155ab21945fc794911fbd0 | 31.120482 | 227 | 0.602026 | 4.777778 | false | false | false | false |
adrfer/swift | test/IDE/complete_from_clang_importer_framework.swift | 20 | 4091 | // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CLANG_UNQUAL_1 > %t.compl.txt
// RUN: FileCheck %s -check-prefix=CLANG_CTYPES < %t.compl.txt
// RUN: FileCheck %s -check-prefix=CLANG_MACROS < %t.compl.txt
// RUN: FileCheck %s -check-prefix=CLANG_DARWIN < %t.compl.txt
// RUN: FileCheck %s -check-prefix=CLANG_DARWIN_NEG < %t.compl.txt
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CLANG_MEMBER1 > %t.compl.txt
// RUN: FileCheck %s -check-prefix=CLANG_MEMBERS1 < %t.compl.txt
import macros
import ctypes
import Darwin
// CLANG_CTYPES: Begin completions
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]/keyword[Foo1, Struct1]: FooStruct1[#FooStruct1#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]/keyword[Foo2]: FooStruct2[#FooStruct2#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]/recommended[Foo2, Foo1]: FooStruct3[#FooStruct3#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]/recommendedover[Foo3, Foo2]: FooStruct4[#FooStruct4#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]: FooStruct5[#FooStruct5#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[Struct]/OtherModule[ctypes]/recommendedover[ro1, ro2, ro3, ro4]/recommended[r1, r2, r3]/keyword[k1, k2, k3, k4]: FooStruct6[#FooStruct6#]{{; name=.+$}}
// CLANG_CTYPES-DAG: Decl[TypeAlias]/OtherModule[ctypes]: FooStructTypedef1[#FooStruct2#]{{; name=.+$}}
// CLANG_CTYPES: End completions
// CLANG_MACROS: Begin completions
// CLANG_MACROS-DAG: Decl[GlobalVar]/OtherModule[macros]: USES_MACRO_FROM_OTHER_MODULE_1[#Int32#]{{; name=.+$}}
// CLANG_MACROS: End completions
// CLANG_DARWIN: Begin completions
// CLANG_DARWIN-DAG: Decl[TypeAlias]/OtherModule[Darwin.MacTypes]: FourCharCode[#UInt32#]{{; name=.+$}}
// CLANG_DARWIN_NEG-NOT: FixedPtr
// CLANG_DARWIN_NEG-NOT: UniCharCoun
// CLANG_DARWIN: End completions
func testClangModule() {
#^CLANG_UNQUAL_1^#
}
func testCompleteModuleQualifiedMacros1() {
macros.#^CLANG_QUAL_MACROS_1^#
// CLANG_QUAL_MACROS_1: Begin completions, 16 items
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: A_PI[#CDouble#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: CF_STRING[#CString#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: EOF[#Int32#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: GL_FALSE[#Int32#]{{$}`}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: GL_RGBA[#CInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: GL_RGB[#CInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: INT64_MAX[#CLongLong#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: MACRO_FROM_IMPL[#CInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: MINUS_THREE[#CInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: M_PIf[#CFloat#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: OBJC_STRING[#String#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: UINT32_MAX[#CUnsignedInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: USES_MACRO_FROM_OTHER_MODULE_1[#CInt#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: UTF8_STRING[#CString#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1-DAG: Decl[GlobalVar]/OtherModule[macros]: VERSION_STRING[#CString#]{{; name=.+$}}
// CLANG_QUAL_MACROS_1: End completions
}
func testClangMember1() {
var FS = FooStruct1()
FS.#^CLANG_MEMBER1^#
// CLANG_MEMBERS1: Begin completions, 2 items
// CLANG_MEMBERS1-DAG: Decl[InstanceVar]/CurrNominal/keyword[x, Struct1]/recommended[y]: x[#Int32#]{{; name=.+$}}
// CLANG_MEMBERS1-DAG: Decl[InstanceVar]/CurrNominal/keyword[y, Struct1]/recommendedover[x]: y[#Double#]{{; name=.+$}}
}
| apache-2.0 | a29cc9bc99a7b63e2b4183562d2162ce | 61.938462 | 180 | 0.700562 | 3.22126 | false | true | false | false |
maximkhatskevich/MKHUniFlow | Sources/MutationDecriptors/3-ActualizationOf.swift | 1 | 1881 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([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.
*/
import Foundation /// for access to `Date` type
//---
/// Operation that has both old and new values.
public
struct ActualizationOf<V: SomeState>: SomeMutationDecriptor
{
public
let timestamp: Date
public
let oldValue: V
public
let newValue: V
public
init?(
from mutationReport: ByTypeStorage.HistoryElement
) {
guard
let oldValue = mutationReport.asActualization?.oldValue as? V,
let newValue = mutationReport.asActualization?.newValue as? V
else
{
return nil
}
//---
self.timestamp = mutationReport.timestamp
self.oldValue = oldValue
self.newValue = newValue
}
}
| mit | 5ae3ccb400187fe2e11becbedad2265f | 28.857143 | 79 | 0.701223 | 4.911227 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/azure-search-basics/azure-search-basics/AZSGeoSearchVC.swift | 1 | 4415 | //
// AZSGeoSearchVC.swift
// azure-search-basics
//
// Created by Mark Hamilton on 3/11/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import MapKit
class AZSGeoSearchVC: AZSViewController, GeoSearch, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
var regionRadius: CLLocationDistance = 1000
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
map.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
// MARK: - GeoSearch Protocol Methods
func locateWithCoordinates(Longitude lon: Double, Latitude lat: Double, locationTitle title: String?) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
let position = CLLocationCoordinate2DMake(lat, lon)
self.centerMapOnCoordinate2D(position)
}
}
// MARK: - Map and Annotations
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2, regionRadius * 2)
map.setRegion(coordinateRegion, animated: true)
}
func centerMapOnCoordinate2D(location: CLLocationCoordinate2D) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius * 2, regionRadius * 2)
map.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if let loc = userLocation.location {
centerMapOnLocation(loc)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKindOfClass(MKAnnotation) {
let annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Default")
annoView.pinTintColor = UIColor.blueColor()
annoView.animatesDrop = true
return annoView
} else if annotation.isKindOfClass(MKUserLocation) {
return nil
}
return nil
}
func createAnnotationFromAddress(location: CLLocation) {
let annotation = AZSMapAnnotation(coordinate: location.coordinate)
map.addAnnotation(annotation)
}
func getPlacemarkFromAddress(address: String) {
CLGeocoder().geocodeAddressString(address) {
(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
if let marks = placemarks where marks.count > 0 {
if let loc = marks[0].location {
// valid location with coordinates
self.createAnnotationFromAddress(loc)
}
}
}
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
| mit | 7c579fd40d327835bf5fed1e147c8bc2 | 26.079755 | 122 | 0.588582 | 6.105118 | false | false | false | false |
kusl/swift | test/SILGen/unowned.swift | 7 | 4750 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func takeClosure(fn: () -> Int) {}
class C {
func f() -> Int { return 42 }
}
struct A {
unowned var x: C
}
_ = A(x: C())
// CHECK-LABEL: sil hidden @_TFV7unowned1AC
// CHECK: bb0([[X:%.*]] : $C, %1 : $@thin A.Type):
// CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C
// CHECK: unowned_retain [[X_UNOWNED]]
// CHECK: strong_release [[X]]
// CHECK: [[A:%.*]] = struct $A ([[X_UNOWNED]] : $@sil_unowned C)
// CHECK: return [[A]]
// CHECK: }
protocol P {}
struct X: P {}
struct AddressOnly {
unowned var x: C
var p: P
}
_ = AddressOnly(x: C(), p: X())
// CHECK-LABEL: sil hidden @_TFV7unowned11AddressOnlyC
// CHECK: bb0([[RET:%.*]] : $*AddressOnly, [[X:%.*]] : $C, {{.*}}):
// CHECK: [[X_ADDR:%.*]] = struct_element_addr [[RET]] : $*AddressOnly, #AddressOnly.x
// CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C
// CHECK: unowned_retain [[X_UNOWNED]] : $@sil_unowned C
// CHECK: store [[X_UNOWNED]] to [[X_ADDR]]
// CHECK: strong_release [[X]]
// CHECK: }
// CHECK-LABEL: sil hidden @_TF7unowned5test0FT1cCS_1C_T_ : $@convention(thin) (@owned C) -> () {
func test0(c c: C) {
// CHECK: bb0(%0 : $C):
var a: A
// CHECK: [[A1:%.*]] = alloc_box $A
// CHECK: [[A:%.*]] = mark_uninitialized [var] [[A1]]#1
unowned var x = c
// CHECK: [[X:%.*]] = alloc_box $@sil_unowned C
// CHECK-NEXT: [[T2:%.*]] = ref_to_unowned %0 : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[T2]] : $@sil_unowned C
// CHECK-NEXT: store [[T2]] to [[X]]#1 : $*@sil_unowned C
a.x = c
// CHECK-NEXT: [[T1:%.*]] = struct_element_addr [[A]] : $*A, #A.x
// CHECK-NEXT: [[T2:%.*]] = ref_to_unowned %0 : $C
// CHECK-NEXT: unowned_retain [[T2]] : $@sil_unowned C
// CHECK-NEXT: assign [[T2]] to [[T1]] : $*@sil_unowned C
a.x = x
// CHECK-NEXT: [[T2:%.*]] = load [[X]]#1 : $*@sil_unowned C
// CHECK-NEXT: strong_retain_unowned [[T2]] : $@sil_unowned C
// CHECK-NEXT: [[T3:%.*]] = unowned_to_ref [[T2]] : $@sil_unowned C to $C
// CHECK-NEXT: [[XP:%.*]] = struct_element_addr [[A]] : $*A, #A.x
// CHECK-NEXT: [[T4:%.*]] = ref_to_unowned [[T3]] : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[T4]] : $@sil_unowned C
// CHECK-NEXT: assign [[T4]] to [[XP]] : $*@sil_unowned C
// CHECK-NEXT: strong_release [[T3]] : $C
}
// CHECK-LABEL: sil hidden @{{.*}}unowned_local
func unowned_local() -> C {
// CHECK: [[c:%.*]] = apply
let c = C()
// CHECK: [[uc:%.*]] = alloc_box $@sil_unowned C // let uc
// CHECK-NEXT: [[tmp1:%.*]] = ref_to_unowned [[c]] : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[tmp1]]
// CHECK-NEXT: store [[tmp1]] to [[uc]]#1
unowned let uc = c
// CHECK-NEXT: [[tmp2:%.*]] = load [[uc]]#1
// CHECK-NEXT: strong_retain_unowned [[tmp2]]
// CHECK-NEXT: [[tmp3:%.*]] = unowned_to_ref [[tmp2]]
return uc
// CHECK-NEXT: strong_release [[uc]]#0
// CHECK-NEXT: strong_release [[c]]
// CHECK-NEXT: return [[tmp3]]
}
// <rdar://problem/16877510> capturing an unowned let crashes in silgen
func test_unowned_let_capture(aC : C) {
unowned let bC = aC
takeClosure { bC.f() }
}
// CHECK-LABEL: sil shared @_TFF7unowned24test_unowned_let_captureFCS_1CT_U_FT_Si : $@convention(thin) (@owned @sil_unowned C) -> Int {
// CHECK: bb0([[ARG:%.*]] : $@sil_unowned C):
// CHECK-NEXT: debug_value %0 : $@sil_unowned C // let bC, argno: 1
// CHECK-NEXT: strong_retain_unowned [[ARG]] : $@sil_unowned C
// CHECK-NEXT: [[UNOWNED_ARG:%.*]] = unowned_to_ref [[ARG]] : $@sil_unowned C to $C
// CHECK-NEXT: [[FUN:%.*]] = class_method [[UNOWNED_ARG]] : $C, #C.f!1 : C -> () -> Int , $@convention(method) (@guaranteed C) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[UNOWNED_ARG]]) : $@convention(method) (@guaranteed C) -> Int
// CHECK-NEXT: strong_release [[UNOWNED_ARG]]
// CHECK-NEXT: unowned_release [[ARG]] : $@sil_unowned C
// CHECK-NEXT: return [[RESULT]] : $Int
// <rdar://problem/16880044> unowned let properties don't work as struct and class members
class TestUnownedMember {
unowned let member : C
init(inval: C) {
self.member = inval
}
}
// CHECK-LABEL: sil hidden @_TFC7unowned17TestUnownedMemberc
// CHECK: bb0(%0 : $C, %1 : $TestUnownedMember):
// CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] %1 : $TestUnownedMember
// CHECK: [[FIELDPTR:%.*]] = ref_element_addr [[SELF]] : $TestUnownedMember, #TestUnownedMember.member
// CHECK: [[INVAL:%.*]] = ref_to_unowned %0 : $C to $@sil_unowned C
// CHECK: unowned_retain [[INVAL]] : $@sil_unowned C
// CHECK: assign [[INVAL]] to [[FIELDPTR]] : $*@sil_unowned C
// CHECK: strong_release %0 : $C
// CHECK: return [[SELF]] : $TestUnownedMember
| apache-2.0 | a8116429170a0c062cd28f800280cdaa | 36.698413 | 135 | 0.573053 | 2.910539 | false | true | false | false |
rankun203/SwiftGround | SimpleTable/SimpleTable/ViewController.swift | 1 | 1640 | //
// ViewController.swift
// SimpleTable
//
// Created by Kun on 10/14/15.
// Copyright © 2015 Kun. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh’s Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantNames.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "tableCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = restaurantNames[indexPath.row]
let imgName = indexPath.row % 2 == 1 ? "restaurant" : "food"
cell.imageView?.image = UIImage(named: imgName)
return cell
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 346b25c936a0445481ce6037baf9cf67 | 33.104167 | 371 | 0.675626 | 4.424324 | false | false | false | false |
khizkhiz/swift | test/SILGen/coverage_closures.swift | 2 | 804 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_closures %s | FileCheck %s
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_closures.foo
func foo() {
// CHECK: [[@LINE+1]]:12 -> [[@LINE+1]]:59 : 1
let c1 = { (i1 : Int32, i2 : Int32) -> Bool in i1 < i2 }
func f1(closure : (Int32, Int32) -> Bool) -> Bool {
// CHECK: [[@LINE-1]]:53 -> [[@LINE+3]]:4 : 2
// CHECK: [[@LINE+1]]:29 -> [[@LINE+1]]:42 : 3
return closure(0, 1) && closure(1, 0)
}
f1(c1)
// CHECK: [[@LINE+1]]:6 -> [[@LINE+1]]:27 : 4
f1 { i1, i2 in i1 > i2 }
// CHECK: [[@LINE+2]]:6 -> [[@LINE+2]]:48 : 5
// CHECK: [[@LINE+1]]:36 -> [[@LINE+1]]:46 : 6
f1 { left, right in left == 0 || right == 1 }
}
foo()
| apache-2.0 | d3411b41b0259cbc8887d133e10591a8 | 35.545455 | 176 | 0.534826 | 2.697987 | false | false | false | false |
testpress/ios-app | ios-app/UI/SuccessViewController.swift | 1 | 2652 | //
// SuccessViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// 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 SuccessViewController: UIViewController {
@IBOutlet weak var successDescriptionLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
var successDescription: String?
var actionButtonText: String?
var actionButtonClickHandler: (() -> Void)?
var backButtonClickHandler: (() -> Void)!
func initSuccessViewController(successDescription: String,
actionButtonText: String? = nil,
backButtonClickHandler: @escaping (() -> Void),
actionButtonClickHandler: (() -> Void)? = nil) {
self.successDescription = successDescription
self.actionButtonText = actionButtonText
self.backButtonClickHandler = backButtonClickHandler
if actionButtonText != nil && actionButtonClickHandler == nil {
self.actionButtonClickHandler = backButtonClickHandler
} else {
self.actionButtonClickHandler = actionButtonClickHandler
}
}
override func viewDidLoad() {
super.viewDidLoad()
successDescriptionLabel.text = successDescription
actionButton.isHidden = (actionButtonClickHandler == nil)
}
@IBAction func onClickActionButton(_ sender: UIButton) {
actionButtonClickHandler!()
}
@IBAction func onClickBackButton() {
backButtonClickHandler()
}
}
| mit | 67138f8c8c462a861bca5e3df312badf | 37.985294 | 83 | 0.68427 | 5.228797 | false | false | false | false |
ringly/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Implementation/LegacyDFU/DFU/LegacyDFUServiceInitiator.swift | 1 | 2232 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
@objc public class LegacyDFUServiceInitiator : DFUServiceInitiator {
public override func start() -> DFUServiceController? {
// The firmware file must be specified before calling `start()`
if file == nil {
delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmware not specified")
return nil
}
let executor = LegacyDFUExecutor(self, controlPointCharacteristicUUID: controlPointCharacteristicUUID, packetCharacteristicUUID: packetCharacteristicUUID)
let controller = DFUServiceController()
controller.executor = executor
executor.start()
return controller
}
}
| bsd-3-clause | ea8ccfcb379a4276f901054ed1452fab | 54.8 | 162 | 0.764337 | 5.365385 | false | false | false | false |
Bishaljain/Weather-App | Weather App/Weather App/VCWeatherMaster.swift | 1 | 5976 | //
// VCWeatherMaster.swift
// Weather App
//
// Created by Bishal on 15/3/17.
// Copyright © 2017 Bishal. All rights reserved.
//
import UIKit
class CustomWeatherCell: UITableViewCell {
@IBOutlet weak var cityName: UILabel!
@IBOutlet weak var temperature: UILabel!
}
class VCWeatherMaster: UITableViewController {
let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView();
let tblRefreshControl = UIRefreshControl()
var VCWeatherDetail: VCWeatherDetail? = nil
var objects = [Any]()
// Update api key and city to your preferred value
let apiManager = APIManager(apiKey: "27558d9f07e3338742055836f8f5c46a", temperatureFormat: .Celsius, lang: .English)
let city = "4163971,2147714,2174003"
var weatherList = [WeatherJsonMapping]() {
didSet {
self.tableView.reloadData()
}
}
// MARK: - View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblRefreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
self.refreshControl = tblRefreshControl
let addButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshData(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.VCWeatherDetail = (controllers[controllers.count-1] as! UINavigationController).topViewController as? VCWeatherDetail
}
self.refreshData(nil)
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Data Manager
func refreshData(_ sender: Any?) {
self.startLoading()
apiManager.currentWeatherByIDAsJson(city, data: { (result) -> Void in
self.stopLoading()
switch result {
case .success(let json):
self.removeRefreshControl(true)
self.weatherList = json["list"].array!.map() { WeatherJsonMapping(json: $0) }
break
case .error(let errorMessage):
self.removeRefreshControl(false)
self.showErrorAlert(errorMessage)
break
}
})
}
func removeRefreshControl(_ updateLogTime: Bool) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {() -> Void in
if (self.refreshControl != nil) {
if updateLogTime {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d, h:mm a"
let title = "Updated on \(formatter.string(from: Date()))"
let attrsDictionary = [ NSForegroundColorAttributeName : UIColor.black ]
let attributedTitle = NSAttributedString(string: title, attributes: attrsDictionary)
self.tblRefreshControl.attributedTitle = attributedTitle
}
self.tblRefreshControl.endRefreshing()
}
})
}
func showErrorAlert(_ errorMessage: String) {
///Error message to be modified later for better presentation.
let alertController = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showWeatherDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = weatherList[indexPath.row] as AnyObject
let controller = (segue.destination as! UINavigationController).topViewController as! VCWeatherDetail
controller.detailItem = object as? WeatherJsonMapping
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weatherList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let weather = weatherList[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomWeatherCell
cell.cityName?.text = weather.cityname
cell.temperature?.text = weather.temperature + " C"
return cell
}
// MARK: - Activity Indicator Start stop
func startLoading(){
activityIndicator.center = self.view.center;
activityIndicator.hidesWhenStopped = true;
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray;
view.addSubview(activityIndicator);
activityIndicator.startAnimating();
UIApplication.shared.beginIgnoringInteractionEvents();
}
func stopLoading(){
activityIndicator.stopAnimating();
UIApplication.shared.endIgnoringInteractionEvents();
}
}
| gpl-3.0 | 5cfa8f025a9b4afe30e8fecc52efe1e7 | 36.34375 | 156 | 0.638494 | 5.456621 | false | false | false | false |
jongwonwoo/CodeSamples | Performance/signposts/LivePhotoPlayground/LivePhotoPlayground/LivePhotoCollectionViewCell.swift | 1 | 1765 | //
// LivePhotoCollectionViewCell.swift
// LivePhotoPlayground
//
// Created by jongwon woo on 2016. 10. 21..
// Copyright © 2016년 jongwonwoo. All rights reserved.
//
import UIKit
import PhotosUI
class LivePhotoCollectionViewCell: UICollectionViewCell {
private var livePhotoView: PHLivePhotoView?
var indexPath: IndexPath?
var livePhoto: PHLivePhoto? {
didSet {
if self.livePhotoView == nil {
makeLivePhotoView()
}
self.livePhotoView?.livePhoto = livePhoto
}
}
private func makeLivePhotoView() {
let livePhotoView = PHLivePhotoView.init(frame: self.contentView.bounds)
livePhotoView.contentMode = .scaleAspectFill
livePhotoView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(livePhotoView)
livePhotoView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 0).isActive = true
livePhotoView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: 0).isActive = true
livePhotoView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0).isActive = true
livePhotoView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0).isActive = true
self.livePhotoView = livePhotoView
}
func startPlayback() {
self.livePhotoView?.startPlayback(with: .full)
}
func stopPlayback() {
self.livePhotoView?.stopPlayback()
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
livePhotoView?.stopPlayback()
}
}
| mit | 7d6aaaf523354d51ba51c6c9db7e005c | 31.036364 | 118 | 0.676504 | 5.019943 | false | false | false | false |
sssbohdan/Design-Patterns-In-Swift | source/behavioral/chain_of_responsibility.swift | 2 | 2358 | /*:
🐝 Chain Of Responsibility
--------------------------
The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
### Example:
*/
class MoneyPile {
let value: Int
var quantity: Int
var nextPile: MoneyPile?
init(value: Int, quantity: Int, nextPile: MoneyPile?) {
self.value = value
self.quantity = quantity
self.nextPile = nextPile
}
func canWithdraw(v: Int) -> Bool {
var v = v
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var q = self.quantity
while canTakeSomeBill(v) {
if q == 0 {
break
}
v -= self.value
q -= 1
}
if v == 0 {
return true
} else if let next = self.nextPile {
return next.canWithdraw(v)
}
return false
}
}
class ATM {
private var hundred: MoneyPile
private var fifty: MoneyPile
private var twenty: MoneyPile
private var ten: MoneyPile
private var startPile: MoneyPile {
return self.hundred
}
init(hundred: MoneyPile,
fifty: MoneyPile,
twenty: MoneyPile,
ten: MoneyPile) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func canWithdraw(value: Int) -> String {
return "Can withdraw: \(self.startPile.canWithdraw(value))"
}
}
/*:
### Usage
*/
// Create piles of money and link them together 10 < 20 < 50 < 100.**
let ten = MoneyPile(value: 10, quantity: 6, nextPile: nil)
let twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten)
let fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty)
// Build ATM.
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.canWithdraw(310) // Cannot because ATM has only 300
atm.canWithdraw(100) // Can withdraw - 1x100
atm.canWithdraw(165) // Cannot withdraw because ATM doesn't has bill with value of 5
atm.canWithdraw(30) // Can withdraw - 1x20, 2x10
/*:
>**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility)
*/
| gpl-3.0 | 95116333d6f66fbb5e41c3a7a2eef74a | 24.597826 | 127 | 0.590658 | 3.873355 | false | false | false | false |
oper0960/GWExtensions | GWExtensions/Classes/CALayerExtension.swift | 1 | 2550 | //
// CALayerExtension.swift
// Pods
//
// Created by Ryu on 2017. 4. 18..
//
//
import UIKit
public extension CALayer {
// Create a border for each direction in the view
public func setBorder(_ arr_edge: [UIRectEdge], color: UIColor, thickness: CGFloat) {
for edge in arr_edge {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect.init(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect.init(x: 0, y: 0, width: thickness, height: frame.height)
break
case UIRectEdge.right:
border.frame = CGRect.init(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
public func setTopBorder(color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: thickness)
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
public func setBottomBorder(color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.frame = CGRect.init(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
public func setLeftBorder(color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.frame = CGRect.init(x: 0, y: 0, width: thickness, height: frame.height)
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
public func setRightBorder(color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.frame = CGRect.init(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
// Set border by Default library simplification
public func setBorderColor(_ width: CGFloat, color: UIColor) {
self.borderWidth = width
self.borderColor = color.cgColor
}
}
| mit | 43e11c56da95410be829f66c9bffd196 | 34.416667 | 116 | 0.596471 | 4.373928 | false | false | false | false |
hammy-dev-world/OnebyteSwiftNetwork | Example/OnebyteSwiftNetworkCycle/swift-api-cycle/Classes/VIewControllers/Main/Handler/ViewHandler.swift | 1 | 2835 | //
// ViewHandler.swift
// swift-api-cycle
//
// Created by Humayun Sohail on 1/11/17.
// Copyright © 2017 Humayun Sohail. All rights reserved.
//
import Foundation
import Alamofire
import OnebyteSwiftNetworkCycle
class ViewHandler: NSObject {
//MARK: Instance Variables
var viewController: ViewController!
var view: View!
//MARK: Init methods
required init(viewController: ViewController!) {
self.viewController = viewController
self.view = self.viewController.viewOutlet
}
//MARK: Callbacks
public var didRecieveErrorCallback : ((_ error: Error?) -> Void)?
public var didReceiveSuccessCallback : ((_ responseObject: AnyObject?) -> Void)?
//MARK: Public Methods
public func requestUnauthorizedAPI() -> Void {
self.handleUnauthorizedAPIRequest()
}
public func requestAuthorizedAPI() -> Void {
self.handleAuthorizedAPIRequest()
}
//MARK: Private Methods
//MARK: Requests
private func handleUnauthorizedAPIRequest() -> Void {
let apiOperation : UnauthorizedAPIOperation = UnauthorizedAPIOperation()
weak var weakSelf = self
apiOperation.didFinishSuccessfullyCallback = {response in
weakSelf?.handleSuccessfulAPIRequest(response: response)
weakSelf?.handleFinishRequest()
}
apiOperation.didFinishWithErrorCallback = {error in
weakSelf?.handleFailedAPIRequest(error: error)
weakSelf?.handleFinishRequest()
}
OnebyteNetworkOperationQueue.sharedInstance.addOperation(apiOperation)
}
private func handleAuthorizedAPIRequest() -> Void {
let apiOperation : AuthorizedAPIOperation = AuthorizedAPIOperation()
weak var weakSelf = self
apiOperation.didFinishSuccessfullyCallback = {response in
weakSelf?.handleSuccessfulAPIRequest(response: response)
weakSelf?.handleFinishRequest()
}
apiOperation.didFinishWithErrorCallback = {error in
weakSelf?.handleFailedAPIRequest(error: error)
weakSelf?.handleFinishRequest()
}
OnebyteNetworkOperationQueue.sharedInstance.addOperation(apiOperation)
}
//MARK: Common
private func handleFinishRequest() -> Void{
//Common operations for every case
}
//MARK: Successful
private func handleSuccessfulAPIRequest(response : AnyObject!) -> Void{
if self.didReceiveSuccessCallback != nil {
self.didReceiveSuccessCallback!(response)
}
}
//MARK: Error
private func handleFailedAPIRequest(error : Error!) -> Void{
if self.didRecieveErrorCallback != nil {
self.didRecieveErrorCallback!(error)
}
}
}
| mit | 27317565bde694415830f8e957b9579f | 28.831579 | 84 | 0.657022 | 5.228782 | false | false | false | false |
Jpoliachik/DroidconBoston-iOS | DroidconBoston/DroidconBoston/AppDelegate.swift | 1 | 2913 | //
// AppDelegate.swift
// DroidconBoston
//
// Created by Justin Poliachik on 3/16/17.
// Copyright © 2017 Droidcon Boston. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// UITabBar appearance
UITabBar.appearance().barTintColor = UIColor.themeWhiteAlmost
UITabBar.appearance().tintColor = UIColor.themeGreenAccent
// selected / unselected TabBarItem text colors
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.themeBlueMain], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.themeGreenAccent], for: .selected)
// UINavigationBar appearance
UINavigationBar.appearance().barTintColor = UIColor.themeBlueMain
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
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 | 250113b768b2c67cc412ab840a620553 | 48.355932 | 285 | 0.74897 | 5.870968 | false | false | false | false |
stulevine/firefox-ios | Client/Frontend/Browser/SearchViewController.swift | 1 | 23496 | /* 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 UIKit
import Shared
import Storage
private let SuggestionBackgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
private let SuggestionBorderColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
private let SuggestionBorderWidth: CGFloat = 0.5
private let SuggestionCornerRadius: CGFloat = 2
private let SuggestionFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 12)
private let SuggestionInsets = UIEdgeInsetsMake(5, 5, 5, 5)
private let SuggestionMargin: CGFloat = 4
private let SuggestionCellVerticalPadding: CGFloat = 8
private let SuggestionCellMaxRows = 2
private let PromptColor = UIColor(rgb: 0xeef0f3)
private let PromptFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 12)
private let PromptYesFont = UIFont(name: "HelveticaNeue-Bold", size: 15)
private let PromptNoFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 15)
private let PromptInsets = UIEdgeInsetsMake(15, 12, 15, 12)
private let PromptButtonColor = UIColor(rgb: 0x007aff)
private let SearchImage = "search"
// searchEngineScrollViewContent is the button container. It has a gray background color,
// so with insets applied to its buttons, the background becomes the button border.
private let EngineButtonInsets = UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5)
// TODO: This should use ToolbarHeight in BVC. Fix this when we create a shared theming file.
private let EngineButtonHeight: Float = 44
private let EngineButtonWidth = EngineButtonHeight * 1.5
private let PromptMessage = NSLocalizedString("Turn on search suggestions?", tableName: "search", comment: "Prompt shown before enabling provider search queries")
private let PromptYes = NSLocalizedString("Yes", tableName: "search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private let PromptNo = NSLocalizedString("No", tableName: "search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private enum SearchListSection: Int {
case SearchSuggestions
case BookmarksAndHistory
static let Count = 2
}
protocol SearchViewControllerDelegate: class {
func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL)
}
class SearchViewController: SiteTableViewController, KeyboardHelperDelegate, LoaderListener {
var searchDelegate: SearchViewControllerDelegate?
private var suggestClient: SearchSuggestClient?
// Views for displaying the bottom scrollable search engine list. searchEngineScrollView is the
// scrollable container; searchEngineScrollViewContent contains the actual set of search engine buttons.
private let searchEngineScrollView = ButtonScrollView()
private let searchEngineScrollViewContent = UIView()
// Cell for the suggestion flow layout. Since heightForHeaderInSection is called *before*
// cellForRowAtIndexPath, we create the cell to find its height before it's added to the table.
private let suggestionCell = SuggestionCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
private var suggestionPrompt: UIView?
convenience init() {
self.init(nibName: nil, bundle: nil)
}
required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
KeyboardHelper.defaultHelper.addDelegate(self)
searchEngineScrollView.layer.backgroundColor = tableView.backgroundColor?.CGColor
searchEngineScrollView.decelerationRate = UIScrollViewDecelerationRateFast
view.addSubview(searchEngineScrollView)
searchEngineScrollViewContent.layer.backgroundColor = tableView.separatorColor.CGColor
searchEngineScrollView.addSubview(searchEngineScrollViewContent)
layoutTable()
layoutSearchEngineScrollView()
searchEngineScrollViewContent.snp_makeConstraints { make in
make.center.equalTo(self.searchEngineScrollView).priorityLow()
make.left.greaterThanOrEqualTo(self.searchEngineScrollView).priorityHigh()
make.right.lessThanOrEqualTo(self.searchEngineScrollView).priorityHigh()
make.top.bottom.equalTo(self.searchEngineScrollView)
}
suggestionCell.delegate = self
}
private func layoutSearchEngineScrollView() {
let keyboardHeight = KeyboardHelper.defaultHelper.currentState?.height ?? 0
searchEngineScrollView.snp_remakeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view).offset(-keyboardHeight)
}
}
var searchEngines: SearchEngines! {
didSet {
suggestClient?.cancelPendingRequest()
// Query and reload the table with new search suggestions.
querySuggestClient()
// Show the default search engine first.
suggestClient = SearchSuggestClient(searchEngine: searchEngines.defaultEngine)
// Reload the footer list of search engines.
reloadSearchEngines()
layoutSuggestionsOptInPrompt()
}
}
private func layoutSuggestionsOptInPrompt() {
if !(searchEngines?.shouldShowSearchSuggestionsOptIn ?? false) {
view.layoutIfNeeded()
suggestionPrompt = nil
layoutTable()
UIView.animateWithDuration(0.2,
animations: {
self.view.layoutIfNeeded()
},
completion: { _ in
self.suggestionPrompt?.removeFromSuperview()
return
})
return
}
let prompt = UIView()
prompt.backgroundColor = PromptColor
// Insert behind the tableView so the tableView slides on top of it
// when the prompt is dismissed.
view.insertSubview(prompt, belowSubview: tableView)
suggestionPrompt = prompt
let promptImage = UIImageView()
promptImage.image = UIImage(named: SearchImage)
prompt.addSubview(promptImage)
let promptLabel = UILabel()
promptLabel.text = PromptMessage
promptLabel.font = PromptFont
promptLabel.numberOfLines = 0
promptLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
prompt.addSubview(promptLabel)
let promptYesButton = InsetButton()
promptYesButton.setTitle(PromptYes, forState: UIControlState.Normal)
promptYesButton.setTitleColor(PromptButtonColor, forState: UIControlState.Normal)
promptYesButton.titleLabel?.font = PromptYesFont
promptYesButton.titleEdgeInsets = PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptYesButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
promptYesButton.addTarget(self, action: "SELdidClickOptInYes", forControlEvents: UIControlEvents.TouchUpInside)
prompt.addSubview(promptYesButton)
let promptNoButton = InsetButton()
promptNoButton.setTitle(PromptNo, forState: UIControlState.Normal)
promptNoButton.setTitleColor(PromptButtonColor, forState: UIControlState.Normal)
promptNoButton.titleLabel?.font = PromptNoFont
promptNoButton.titleEdgeInsets = PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptNoButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
promptNoButton.addTarget(self, action: "SELdidClickOptInNo", forControlEvents: UIControlEvents.TouchUpInside)
prompt.addSubview(promptNoButton)
promptImage.snp_makeConstraints { make in
make.left.equalTo(prompt).offset(PromptInsets.left)
make.centerY.equalTo(prompt)
}
promptLabel.snp_makeConstraints { make in
make.left.equalTo(promptImage.snp_right).offset(PromptInsets.left)
make.top.bottom.equalTo(prompt).insets(PromptInsets)
make.right.lessThanOrEqualTo(promptYesButton.snp_left)
return
}
promptNoButton.snp_makeConstraints { make in
make.right.equalTo(prompt).insets(PromptInsets)
make.centerY.equalTo(prompt)
}
promptYesButton.snp_makeConstraints { make in
make.right.equalTo(promptNoButton.snp_leading).insets(PromptInsets)
make.centerY.equalTo(prompt)
}
prompt.snp_makeConstraints { make in
make.top.leading.trailing.equalTo(self.view)
return
}
layoutTable()
}
var searchQuery: String = "" {
didSet {
// Reload the tableView to show the updated text in each engine.
reloadData()
}
}
override func reloadData() {
querySuggestClient()
}
private func layoutTable() {
tableView.snp_remakeConstraints { make in
make.top.equalTo(self.suggestionPrompt?.snp_bottom ?? self.view.snp_top)
make.leading.trailing.equalTo(self.view)
make.bottom.equalTo(self.searchEngineScrollView.snp_top)
}
}
private func reloadSearchEngines() {
searchEngineScrollViewContent.subviews.map({ $0.removeFromSuperview() })
var leftEdge = searchEngineScrollViewContent.snp_left
for engine in searchEngines.quickSearchEngines {
let engineButton = UIButton()
engineButton.setImage(engine.image, forState: UIControlState.Normal)
engineButton.layer.backgroundColor = UIColor.whiteColor().CGColor
engineButton.addTarget(self, action: "SELdidSelectEngine:", forControlEvents: UIControlEvents.TouchUpInside)
engineButton.accessibilityLabel = String(format: NSLocalizedString("%@ search", comment: "Label for search engine buttons. The argument corresponds to the name of the search engine."), engine.shortName)
searchEngineScrollViewContent.addSubview(engineButton)
engineButton.snp_makeConstraints { make in
make.width.equalTo(EngineButtonWidth)
make.height.equalTo(EngineButtonHeight)
make.left.equalTo(leftEdge).offset(EngineButtonInsets.left)
make.top.bottom.equalTo(self.searchEngineScrollViewContent).insets(EngineButtonInsets)
if engine === self.searchEngines.quickSearchEngines.last {
make.right.equalTo(self.searchEngineScrollViewContent).offset(-EngineButtonInsets.right)
}
}
leftEdge = engineButton.snp_right
}
}
func SELdidSelectEngine(sender: UIButton) {
// The UIButtons are the same cardinality and order as the array of quick search engines.
for i in 0..<searchEngineScrollViewContent.subviews.count {
if let button = searchEngineScrollViewContent.subviews[i] as? UIButton {
if button === sender {
if let url = searchEngines.quickSearchEngines[i].searchURLForQuery(searchQuery) {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
}
}
func SELdidClickOptInYes() {
searchEngines.shouldShowSearchSuggestions = true
searchEngines.shouldShowSearchSuggestionsOptIn = false
querySuggestClient()
layoutSuggestionsOptInPrompt()
}
func SELdidClickOptInNo() {
searchEngines.shouldShowSearchSuggestions = false
searchEngines.shouldShowSearchSuggestionsOptIn = false
layoutSuggestionsOptInPrompt()
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
private func animateSearchEnginesWithKeyboard(keyboardState: KeyboardState) {
layoutSearchEngineScrollView()
UIView.animateWithDuration(keyboardState.animationDuration, animations: {
UIView.setAnimationCurve(keyboardState.animationCurve)
self.view.layoutIfNeeded()
})
}
private func querySuggestClient() {
suggestClient?.cancelPendingRequest()
if searchQuery.isEmpty || !searchEngines.shouldShowSearchSuggestions {
suggestionCell.suggestions = []
return
}
suggestClient?.query(searchQuery, callback: { suggestions, error in
if let error = error {
let isSuggestClientError = error.domain == SearchSuggestClientErrorDomain
switch error.code {
case NSURLErrorCancelled where error.domain == NSURLErrorDomain:
// Request was cancelled. Do nothing.
break
case SearchSuggestClientErrorInvalidEngine where isSuggestClientError:
// Engine does not support search suggestions. Do nothing.
break
case SearchSuggestClientErrorInvalidResponse where isSuggestClientError:
println("Error: Invalid search suggestion data")
default:
println("Error: \(error.description)")
}
} else {
self.suggestionCell.suggestions = suggestions!
}
// If there are no suggestions, just use whatever the user typed.
if suggestions?.isEmpty ?? true {
self.suggestionCell.suggestions = [self.searchQuery]
}
// Reload the tableView to show the new list of search suggestions.
self.tableView.reloadData()
})
}
func loader(dataLoaded data: Cursor) {
self.data = data
tableView.reloadData()
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = SearchListSection(rawValue: indexPath.section)!
if section == SearchListSection.BookmarksAndHistory {
if let site = data[indexPath.row] as? Site {
if let url = NSURL(string: site.url) {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let currentSection = SearchListSection(rawValue: indexPath.section) {
switch currentSection {
case .SearchSuggestions:
// heightForRowAtIndexPath is called *before* the cell is created, so to get the height,
// force a layout pass first.
suggestionCell.layoutIfNeeded()
return suggestionCell.frame.height
default:
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
return 0
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
}
extension SearchViewController: UITableViewDataSource {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch SearchListSection(rawValue: indexPath.section)! {
case .SearchSuggestions:
suggestionCell.imageView?.image = searchEngines.defaultEngine.image
return suggestionCell
case .BookmarksAndHistory:
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let site = data[indexPath.row] as? Site {
if let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
if let img = site.icon {
let imgUrl = NSURL(string: img.url)
cell.imageView?.sd_setImageWithURL(imgUrl, placeholderImage: self.profile.favicons.defaultIcon)
} else {
cell.imageView?.image = self.profile.favicons.defaultIcon
}
}
}
return cell
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch SearchListSection(rawValue: section)! {
case .SearchSuggestions:
return searchEngines.shouldShowSearchSuggestions ? 1 : 0
case .BookmarksAndHistory:
return data.count
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return SearchListSection.Count
}
}
extension SearchViewController: SuggestionCellDelegate {
private func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) {
var url = URIFixup().getURL(suggestion)
if url == nil {
// Assume that only the default search engine can provide search suggestions.
url = searchEngines?.defaultEngine.searchURLForQuery(suggestion)
}
if let url = url {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
/**
* UIScrollView that prevents buttons from interfering with scroll.
*/
private class ButtonScrollView: UIScrollView {
private override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
return true
}
}
private protocol SuggestionCellDelegate: class {
func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String)
}
/**
* Cell that wraps a list of search suggestion buttons.
*/
private class SuggestionCell: UITableViewCell {
weak var delegate: SuggestionCellDelegate?
let container = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = false
accessibilityLabel = nil
layoutMargins = UIEdgeInsetsZero
separatorInset = UIEdgeInsetsZero
selectionStyle = UITableViewCellSelectionStyle.None
contentView.addSubview(container)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var suggestions: [String] = [] {
didSet {
for view in container.subviews {
view.removeFromSuperview()
}
for suggestion in suggestions {
let button = SuggestionButton()
button.setTitle(suggestion, forState: UIControlState.Normal)
button.addTarget(self, action: "SELdidSelectSuggestion:", forControlEvents: UIControlEvents.TouchUpInside)
// If this is the first image, add the search icon.
if container.subviews.isEmpty {
let image = UIImage(named: SearchImage)
button.setImage(image, forState: UIControlState.Normal)
button.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0)
}
container.addSubview(button)
}
setNeedsLayout()
}
}
@objc
func SELdidSelectSuggestion(sender: UIButton) {
delegate?.suggestionCell(self, didSelectSuggestion: sender.titleLabel!.text!)
}
private override func layoutSubviews() {
super.layoutSubviews()
// The left bounds of the suggestions align with where text would be displayed.
let textLeft: CGFloat = 44
// The maximum width of the container, after which suggestions will wrap to the next line.
let maxWidth = contentView.frame.width
// The height of the suggestions container (minus margins), used to determine the frame.
var height: CGFloat = 0
var currentLeft = textLeft
var currentTop = SuggestionCellVerticalPadding
var currentRow = 0
for view in container.subviews {
let button = view as! UIButton
var buttonSize = button.intrinsicContentSize()
if height == 0 {
height = buttonSize.height
}
var width = currentLeft + buttonSize.width + SuggestionMargin
if width > maxWidth {
// Only move to the next row if there's already a suggestion on this row.
// Otherwise, the suggestion is too big to fit and will be resized below.
if currentLeft > textLeft {
currentRow++
if currentRow >= SuggestionCellMaxRows {
// Don't draw this button if it doesn't fit on the row.
button.frame = CGRectZero
continue
}
currentLeft = textLeft
currentTop += buttonSize.height + SuggestionMargin
height += buttonSize.height + SuggestionMargin
width = currentLeft + buttonSize.width + SuggestionMargin
}
// If the suggestion is too wide to fit on its own row, shrink it.
if width > maxWidth {
buttonSize.width = maxWidth - currentLeft - SuggestionMargin
}
}
button.frame = CGRectMake(currentLeft, currentTop, buttonSize.width, buttonSize.height)
currentLeft += buttonSize.width + SuggestionMargin
}
frame.size.height = height + 2 * SuggestionCellVerticalPadding
contentView.frame = frame
container.frame = frame
let imageY = (frame.size.height - 24) / 2
imageView!.frame = CGRectMake(10, imageY, 24, 24)
}
}
/**
* Rounded search suggestion button that highlights when selected.
*/
private class SuggestionButton: InsetButton {
override init(frame: CGRect) {
super.init(frame: frame)
setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
titleLabel?.font = SuggestionFont
backgroundColor = SuggestionBackgroundColor
layer.borderColor = SuggestionBackgroundColor.CGColor
layer.borderWidth = SuggestionBorderWidth
layer.cornerRadius = SuggestionCornerRadius
contentEdgeInsets = SuggestionInsets
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.grayColor() : SuggestionBackgroundColor
}
}
}
| mpl-2.0 | 3133d5644f7ac316518e8114b1dfccb9 | 39.164103 | 214 | 0.664454 | 5.466729 | false | false | false | false |
zhuhaow/NEKit | src/Messages/HTTPHeader.swift | 2 | 6690 | import Foundation
open class HTTPHeader {
public enum HTTPHeaderError: Error {
case malformedHeader, invalidRequestLine, invalidHeaderField, invalidConnectURL, invalidConnectPort, invalidURL, missingHostField, invalidHostField, invalidHostPort, invalidContentLength, illegalEncoding
}
open var HTTPVersion: String
open var method: String
open var isConnect: Bool = false
open var path: String
open var foundationURL: Foundation.URL?
open var homemadeURL: HTTPURL?
open var host: String
open var port: Int
// just assume that `Content-Length` is given as of now.
// Chunk is not supported yet.
open var contentLength: Int = 0
open var headers: [(String, String)] = []
open var rawHeader: Data?
public init(headerString: String) throws {
let lines = headerString.components(separatedBy: "\r\n")
guard lines.count >= 3 else {
throw HTTPHeaderError.malformedHeader
}
let request = lines[0].components(separatedBy: " ")
guard request.count == 3 else {
throw HTTPHeaderError.invalidRequestLine
}
method = request[0]
path = request[1]
HTTPVersion = request[2]
for line in lines[1..<lines.count-2] {
let header = line.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false)
guard header.count == 2 else {
throw HTTPHeaderError.invalidHeaderField
}
headers.append((String(header[0]).trimmingCharacters(in: CharacterSet.whitespaces), String(header[1]).trimmingCharacters(in: CharacterSet.whitespaces)))
}
if method.uppercased() == "CONNECT" {
isConnect = true
let urlInfo = path.components(separatedBy: ":")
guard urlInfo.count == 2 else {
throw HTTPHeaderError.invalidConnectURL
}
host = urlInfo[0]
guard let port = Int(urlInfo[1]) else {
throw HTTPHeaderError.invalidConnectPort
}
self.port = port
self.contentLength = 0
} else {
var resolved = false
host = ""
port = 80
if let _url = Foundation.URL(string: path) {
foundationURL = _url
if foundationURL!.host != nil {
host = foundationURL!.host!
port = foundationURL!.port ?? 80
resolved = true
}
} else {
guard let _url = HTTPURL(string: path) else {
throw HTTPHeaderError.invalidURL
}
homemadeURL = _url
if homemadeURL!.host != nil {
host = homemadeURL!.host!
port = homemadeURL!.port ?? 80
resolved = true
}
}
if !resolved {
var url: String = ""
for (key, value) in headers {
if "Host".caseInsensitiveCompare(key) == .orderedSame {
url = value
break
}
}
guard url != "" else {
throw HTTPHeaderError.missingHostField
}
let urlInfo = url.components(separatedBy: ":")
guard urlInfo.count <= 2 else {
throw HTTPHeaderError.invalidHostField
}
if urlInfo.count == 2 {
host = urlInfo[0]
guard let port = Int(urlInfo[1]) else {
throw HTTPHeaderError.invalidHostPort
}
self.port = port
} else {
host = urlInfo[0]
port = 80
}
}
for (key, value) in headers {
if "Content-Length".caseInsensitiveCompare(key) == .orderedSame {
guard let contentLength = Int(value) else {
throw HTTPHeaderError.invalidContentLength
}
self.contentLength = contentLength
break
}
}
}
}
public convenience init(headerData: Data) throws {
guard let headerString = String(data: headerData, encoding: .utf8) else {
throw HTTPHeaderError.illegalEncoding
}
try self.init(headerString: headerString)
rawHeader = headerData
}
open subscript(index: String) -> String? {
get {
for (key, value) in headers {
if index.caseInsensitiveCompare(key) == .orderedSame {
return value
}
}
return nil
}
}
open func toData() -> Data {
return toString().data(using: String.Encoding.utf8)!
}
open func toString() -> String {
var strRep = "\(method) \(path) \(HTTPVersion)\r\n"
for (key, value) in headers {
strRep += "\(key): \(value)\r\n"
}
strRep += "\r\n"
return strRep
}
open func addHeader(_ key: String, value: String) {
headers.append((key, value))
}
open func rewriteToRelativePath() {
if path[path.startIndex] != "/" {
guard let rewrotePath = URL.matchRelativePath(path) else {
return
}
path = rewrotePath
}
}
open func removeHeader(_ key: String) -> String? {
for i in 0..<headers.count {
if headers[i].0.caseInsensitiveCompare(key) == .orderedSame {
let (_, value) = headers.remove(at: i)
return value
}
}
return nil
}
open func removeProxyHeader() {
let ProxyHeader = ["Proxy-Authenticate", "Proxy-Authorization", "Proxy-Connection"]
for header in ProxyHeader {
_ = removeHeader(header)
}
}
struct URL {
// swiftlint:disable:next force_try
static let relativePathRegex = try! NSRegularExpression(pattern: "http.?:\\/\\/.*?(\\/.*)", options: NSRegularExpression.Options.caseInsensitive)
static func matchRelativePath(_ url: String) -> String? {
if let result = relativePathRegex.firstMatch(in: url, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: url.count)) {
return (url as NSString).substring(with: result.range(at: 1))
} else {
return nil
}
}
}
}
| bsd-3-clause | 8894036159fd176a628c8c76bf38a551 | 32.45 | 211 | 0.519283 | 5.075873 | false | false | false | false |
mindbody/Conduit | Tests/ConduitTests/Networking/Images/ImageDownloaderTests.swift | 1 | 6797 | //
// ImageDownloaderTests.swift
// ConduitTests
//
// Created by John Hammerlund on 7/10/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
import Conduit
private class MonitoringURLSessionClient: URLSessionClientType {
private let sessionClient = URLSessionClient()
var requestMiddleware: [RequestPipelineMiddleware] = []
var responseMiddleware: [ResponsePipelineMiddleware] = []
var numRequestsSent: Int = 0
func begin(request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse) {
numRequestsSent += 1
return try sessionClient.begin(request: request)
}
func begin(request: URLRequest, completion: @escaping SessionTaskCompletion) -> SessionTaskProxyType {
numRequestsSent += 1
return sessionClient.begin(request: request, completion: completion)
}
}
class ImageDownloaderTests: XCTestCase {
func testOnlyHitsNetworkOncePerRequest() throws {
let monitoringSessionClient = MonitoringURLSessionClient()
let sut = ImageDownloader(cache: AutoPurgingURLImageCache(), sessionClient: monitoringSessionClient)
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
for _ in 0..<100 {
sut.downloadImage(for: imageRequest) { _ in }
}
XCTAssert(monitoringSessionClient.numRequestsSent == 1)
}
func testMarksImagesAsCachedAfterDownloaded() throws {
let attemptedAllImageRetrievalsExpectation = expectation(description: "attempted all image retrievals")
let sut = ImageDownloader(cache: AutoPurgingURLImageCache())
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
sut.downloadImage(for: imageRequest) { response in
XCTAssert(response.isFromCache == false)
let dispatchGroup = DispatchGroup()
for _ in 0..<100 {
dispatchGroup.enter()
DispatchQueue.global().async {
sut.downloadImage(for: imageRequest) { response in
XCTAssert(response.isFromCache == true)
dispatchGroup.leave()
}
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
attemptedAllImageRetrievalsExpectation.fulfill()
}
}
waitForExpectations(timeout: 5)
}
func testHandlesSimultaneousRequestsForDifferentImages() {
let imageURLs = (0..<10).compactMap {
URL(string: "https://httpbin.org/image/jpeg?id=\($0)")
}
let sut = ImageDownloader(cache: AutoPurgingURLImageCache())
let fetchedAllImagesExpectation = expectation(description: "fetched all images")
let dispatchGroup = DispatchGroup()
for url in imageURLs {
dispatchGroup.enter()
sut.downloadImage(for: URLRequest(url: url)) { response in
XCTAssertNotNil(response.image)
XCTAssertNil(response.error)
XCTAssertFalse(response.isFromCache)
XCTAssertEqual(response.urlResponse?.statusCode, 200)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
fetchedAllImagesExpectation.fulfill()
}
waitForExpectations(timeout: 5)
}
func testPersistsWhileOperationsAreRunning() throws {
let imageDownloadedExpectation = expectation(description: "image downloaded")
var sut: ImageDownloader? = ImageDownloader(cache: AutoPurgingURLImageCache())
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
weak var weakImageDownloader = sut
sut?.downloadImage(for: imageRequest) { _ in
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
XCTAssert(weakImageDownloader == nil)
imageDownloadedExpectation.fulfill()
}
}
sut = nil
XCTAssert(weakImageDownloader != nil)
waitForExpectations(timeout: 5)
}
func testMainOperationQueue() throws {
// GIVEN a main operation queue
let expectedQueue = OperationQueue.main
// AND a configured Image Downloader instance
let imageDownloadedExpectation = expectation(description: "image downloaded")
let sut = ImageDownloader(cache: AutoPurgingURLImageCache())
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
// WHEN downloading an image
sut.downloadImage(for: imageRequest) { _ in
// THEN the completion handler is called in the expected queue
XCTAssertEqual(OperationQueue.current, expectedQueue)
imageDownloadedExpectation.fulfill()
}
waitForExpectations(timeout: 5)
}
func testCurrentOperationQueue() throws {
// GIVEN an operation queue
let expectedQueue = OperationQueue()
// AND a configured Image Downloader instance
let imageDownloadedExpectation = expectation(description: "image downloaded")
let sut = ImageDownloader(cache: AutoPurgingURLImageCache())
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
// WHEN downloading an image from our background queue
expectedQueue.addOperation {
sut.downloadImage(for: imageRequest) { _ in
// THEN the completion handler is called in the expected queue
XCTAssertEqual(OperationQueue.current, expectedQueue)
imageDownloadedExpectation.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testCustomOperationQueue() throws {
// GIVEN a custom operation queue
let customQueue = OperationQueue()
// AND a configured Image Downloader instance with our custom completion queue
let imageDownloadedExpectation = expectation(description: "image downloaded")
let sut = ImageDownloader(cache: AutoPurgingURLImageCache(), completionQueue: customQueue)
let url = try URL(absoluteString: "https://httpbin.org/image/jpeg")
let imageRequest = URLRequest(url: url)
// WHEN downloading an image
sut.downloadImage(for: imageRequest) { _ in
// THEN the completion handler is called in our custom queue
XCTAssertEqual(OperationQueue.current, customQueue)
imageDownloadedExpectation.fulfill()
}
waitForExpectations(timeout: 5)
}
}
| apache-2.0 | 2122c3f72019c945b623384613a2abf9 | 36.96648 | 111 | 0.65053 | 5.309375 | false | true | false | false |
february29/Learning | swift/Fch_Contact/Fch_Contact/AppClasses/View/LoginView.swift | 1 | 4573 | //
// LoginView.swift
// Fch_Contact
//
// Created by bai on 2018/4/20.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
import RxCocoa
import BAlertView
typealias completeHandler = (Bool)->Void
class LoginView: UIView {
var viewModel:LoginViewModel?
let disposeBag = DisposeBag();
var loginCompleteHandler:completeHandler?
lazy var userName: UITextField = {
let tf = UITextField();
tf.font = UIFont.systemFont(ofSize: UIFont.systemFontSize);
tf.font = UIFont.systemFont(ofSize: UIFont.systemFontSize);
tf.placeholder = "用户名";
tf.layer.cornerRadius = 3;
tf.layer.borderWidth = 0.8;
tf.layer.borderColor = BRGBColor(r: 237, g: 237, b: 237, a: 1).cgColor;
tf.textAlignment = .center;
// tf.layer.cornerRadius = 5;
tf.background = UIImage.init(named: "bg_guide_text");
return tf;
}();
lazy var passWord: UITextField = {
let tf = UITextField();
tf.font = UIFont.systemFont(ofSize: UIFont.systemFontSize);
tf.placeholder = "密码";
tf.layer.cornerRadius = 3;
tf.layer.borderWidth = 0.8;
tf.layer.borderColor = BRGBColor(r: 237, g: 237, b: 237, a: 1).cgColor;
tf.isSecureTextEntry = true;
tf.textAlignment = .center;
// tf.layer.cornerRadius = 5;
tf.background = UIImage.init(named: "bg_guide_text");
return tf;
}();
lazy var loginBtn: UIButton = {
let btn = UIButton();
btn.setTitle("登录", for: .normal)
// btn.setTitleColor(ThemeColorType.navBarTitle);
// btn.setBackgroundColor(ThemeColorType.navBar);
btn.backgroundColor = rgb("D2373B");
btn.setTitleColor(UIColor.white, for: .normal);
btn.layer.cornerRadius = 3;
// btn.layer.borderWidth = 0.8;
// btn.layer.borderColor = BRGBColor(r: 237, g: 237, b: 237, a: 1).cgColor;
btn.titleLabel?.font = UIFont.systemFont(ofSize: UIFont.systemFontSize);
return btn;
}();
override init(frame: CGRect) {
super .init(frame: frame);
self.backgroundColor = UIColor.white;
self.layer.cornerRadius = 5;
self.addSubview(self.userName);
self.addSubview(self.passWord)
self.addSubview(self.loginBtn);
self.userName.snp.makeConstraints { (make) in
make.top.equalTo(self).offset(25);
make.centerX.equalTo(self);
make.width.equalTo(self).multipliedBy(0.75);
make.height.equalTo(35);
}
self.passWord.snp.makeConstraints { (make) in
make.top.equalTo(self.userName.snp.bottom).offset(10);
make.centerX.equalTo(self);
make.width.equalTo(self.userName);
make.height.equalTo(self.userName);
}
self.loginBtn.snp.makeConstraints { (make) in
make.top.equalTo(self.passWord.snp.bottom).offset(10);
make.centerX.equalTo(self);
make.width.equalTo(self.userName);
make.height.equalTo(self.userName);
}
viewModel = LoginViewModel(usernameDriver: self.userName.rx.text.orEmpty.asDriver(), passwordDriver: self.passWord.rx.text.orEmpty.asDriver(), loginTaps: self.loginBtn.rx.tap.asDriver())
self.bundingViewModel();
}
func bundingViewModel() {
viewModel?.signupEnabled.drive(onNext: { (loginable) in
self.loginBtn.isEnabled = loginable
self.loginBtn.alpha = loginable ? 1.0 : 0.5
}) .disposed(by: disposeBag)
viewModel?.signedIn
.drive(onNext: { signedIn in
print("User signed in \(signedIn)")
if signedIn {
if self.loginCompleteHandler != nil{
self.loginCompleteHandler!(true);
}
}else{
if self.loginCompleteHandler != nil{
self.loginCompleteHandler!(false);
}
}
})
.disposed(by: disposeBag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 816b4fbff58068df91ce5d7c87f5df85 | 28.815789 | 194 | 0.555384 | 4.404276 | false | false | false | false |
jjatie/Charts | Source/Charts/Highlight/Highlight.swift | 1 | 6258 | //
// Highlight.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
open class Highlight: CustomStringConvertible {
/// the x-value of the highlighted value
fileprivate var _x = Double.nan
/// the y-value of the highlighted value
fileprivate var _y = Double.nan
/// the x-pixel of the highlight
private var _xPx = CGFloat.nan
/// the y-pixel of the highlight
private var _yPx = CGFloat.nan
/// the index of the data object - in case it refers to more than one
open var dataIndex = Int(-1)
/// the index of the dataset the highlighted value is in
fileprivate var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
///
/// **default**: -1
fileprivate var _stackIndex = Int(-1)
/// the axis the highlighted value belongs to
private var _axis = YAxis.AxisDependency.left
/// the x-position (pixels) on which this highlight object was last drawn
open var drawX: CGFloat = 0.0
/// the y-position (pixels) on which this highlight object was last drawn
open var drawY: CGFloat = 0.0
public init() {}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataIndex: the index of the Data the highlighted value belongs to
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataIndex: Int,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency
) {
_x = x
_y = y
_xPx = xPx
_yPx = yPx
self.dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
_axis = axis
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public convenience init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency
) {
self.init(x: x, y: y, xPx: xPx, yPx: yPx,
dataIndex: 0,
dataSetIndex: dataSetIndex,
stackIndex: stackIndex,
axis: axis)
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataIndex: the index of the Data the highlighted value belongs to
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
axis: YAxis.AxisDependency
) {
_x = x
_y = y
_xPx = xPx
_yPx = yPx
_dataSetIndex = dataSetIndex
_axis = axis
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
public init(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1) {
_x = x
_y = y
_dataSetIndex = dataSetIndex
self.dataIndex = dataIndex
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(x: Double, dataSetIndex: Int, stackIndex: Int) {
self.init(x: x, y: Double.nan, dataSetIndex: dataSetIndex)
_stackIndex = stackIndex
}
open var x: Double { return _x }
open var y: Double { return _y }
open var xPx: CGFloat { return _xPx }
open var yPx: CGFloat { return _yPx }
open var dataSetIndex: Int { return _dataSetIndex }
open var stackIndex: Int { return _stackIndex }
open var axis: YAxis.AxisDependency { return _axis }
open var isStacked: Bool { return _stackIndex >= 0 }
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(x: CGFloat, y: CGFloat) {
drawX = x
drawY = y
}
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(pt: CGPoint) {
drawX = pt.x
drawY = pt.y
}
// MARK: CustomStringConvertible
open var description: String {
return "Highlight, x: \(_x), y: \(_y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"
}
}
// MARK: Equatable
extension Highlight: Equatable {
public static func == (lhs: Highlight, rhs: Highlight) -> Bool {
if lhs === rhs {
return true
}
return lhs._x == rhs._x
&& lhs._y == rhs._y
&& lhs.dataIndex == rhs.dataIndex
&& lhs._dataSetIndex == rhs._dataSetIndex
&& lhs._stackIndex == rhs._stackIndex
}
}
| apache-2.0 | 6639f570f6e042d4a55e15e314d2d8d5 | 32.645161 | 173 | 0.608341 | 4.225523 | false | false | false | false |
fwagner/WPJsonAPI | Source/WPJOAuth2Token.swift | 1 | 1299 | //
// WPJOAuth2Token.swift
// WordpressJSONApi
//
// Created by Flo on 10.09.15.
// Copyright (c) 2015 Florian Wagner. All rights reserved.
//
import Foundation
public class WPJOAuth2Token {
private static let kTokenKey : String = "kWPJOAuth2TokenKey";
private static let kTokenExpiryDateKey : String = "kWPJOAuth2TokenExpiryDateKey"
public var token : String;
private var expiryDate : NSDate;
public init(token : String, expiresIn : Int) {
self.token = token;
self.expiryDate = NSDate(timeIntervalSinceNow: Double(expiresIn));
}
public init(data : NSData) {
var dict : [String : AnyObject] = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [String : AnyObject];
self.token = dict[WPJOAuth2Token.kTokenKey] as! String;
self.expiryDate = dict[WPJOAuth2Token.kTokenExpiryDateKey] as! NSDate;
}
public func isExpired() -> Bool {
return NSDate().timeIntervalSinceDate(self.expiryDate) >= 0;
}
public func encodedData() -> NSData {
var data = Dictionary<String, AnyObject>();
data[WPJOAuth2Token.kTokenKey] = self.token;
data[WPJOAuth2Token.kTokenExpiryDateKey] = self.expiryDate;
return NSKeyedArchiver.archivedDataWithRootObject(data);
}
} | mit | e4e0864299b2e5a7e50260ccb7f927ef | 32.333333 | 115 | 0.677444 | 4.097792 | false | false | false | false |
Flixpicks/Flixpicks | Sources/App/Models/User.swift | 1 | 2538 | //
// User.swift
// flixpicks
//
// Created by Camden Voigt on 7/1/17.
//
//
import Foundation
import FluentProvider
import AuthProvider
final class User: Model {
/// General implementation should just be `let storage = Storage()`
let storage = Storage()
var name: String
var email: String
var password: String?
init(name: String, email: String, password: String? = nil) {
self.name = name
self.email = email
self.password = password
}
init(row: Row) throws {
self.name = try row.get("name")
self.email = try row.get("email")
self.password = try row.get("password")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("email", email)
try row.set("password", password)
return row
}
}
// MARK: Preparation
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("name")
builder.string("email")
builder.string("password")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSONConvertible
extension User: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
name: json.get("name"),
email: json.get("email")
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("name", name)
try json.set("email", email)
return json
}
}
// MARK: HTTP
extension User: ResponseRepresentable {}
// MARK: PasswordAuthenticatable
extension User: PasswordAuthenticatable {
var hashedPassword: String? {
return password
}
public static var passwordVerifier: PasswordVerifier? {
get { return _userPasswordVerifier }
set { _userPasswordVerifier = newValue }
}
}
// store private variable since storage in extensions
// is not yet allowed in Swift
private var _userPasswordVerifier: PasswordVerifier? = nil
// MARK: Persist Session
extension User: SessionPersistable {}
// MARK: Request
extension Request {
func user() throws -> User {
return try auth.assertAuthenticated()
}
func jsonUser() throws -> User {
guard let json = json else { throw Abort.badRequest }
return try User(json: json)
}
}
| mit | 262804d79e87a7043aed9c3ca39a8b4d | 22.284404 | 71 | 0.600079 | 4.287162 | false | false | false | false |
jedlewison/PrettyGoodKVO | PrettyGoodKVO/ObservationRequests.swift | 1 | 4991 | //
// ObservationRequests.swift
// PrettyGoodKVO
//
// Created by Jed Lewison on 2/6/16.
// Copyright © 2016 Magic App Factory. All rights reserved.
//
import Foundation
internal enum KeyPathObservationAction {
case none
case unobserve(Set<String>)
case observe(String, NSKeyValueObservingOptions)
}
/// Models the requests for a single proxy observing an object on behalf of clients
internal struct ObservationRequests {
private var count: Int {
return _requests.count
}
var allKeyPaths: Set<String> {
return Set(_requests.map { $0.keyPath } )
}
private var _requests = Set<ObservationRequest>()
private var _requestsForClient: [ WeakClientBox : Set<ObservationRequest> ] = [ : ]
private var _requestsForKeyPath: [ String : Set<ObservationRequest> ] = [ : ]
// MARK: - Getting requests for handling observations
@warn_unused_result(message="You must use the returned requests")
func requestsForKeyPath(keyPath: String, changeKeys: [String]) -> [ObservationRequest] {
let hasNewValue = changeKeys.contains(NSKeyValueChangeNewKey)
let hasOldValue = changeKeys.contains(NSKeyValueChangeOldKey)
let hasPriorValue = changeKeys.contains(NSKeyValueChangeNotificationIsPriorKey) // This is wrong-ish
var options: [NSKeyValueObservingOptions] = []
if hasNewValue { options += [.Prior, .New] }
if hasOldValue { options += [.Old] }
if hasPriorValue { options += [.Prior] }
return _requestsForKeyPath[keyPath]?.filter { !$0.options.intersect(NSKeyValueObservingOptions(options)).isEmpty } ?? []
}
// MARK: - Dropping requests
/// Drops requests that have been canceled or with nil clients and returns keypaths that are no longer being observed, if any
@warn_unused_result(message="You must unobserve the returned keypaths")
mutating func dropNilClients() -> KeyPathObservationAction {
return dropRequests(_requests.filter { $0.clientBox.isNilClient } )
}
@warn_unused_result(message="You must unobserve the returned keypaths")
mutating func dropForClient(client: AnyObject, keyPath: String?, options: NSKeyValueObservingOptions?) -> KeyPathObservationAction {
func isMatchingRequest(request: ObservationRequest) -> Bool {
switch (keyPath, options) {
case let (keyPath?, options?):
return request.keyPath == keyPath
&& request.options == options
case (nil, let options?):
return request.options == options
case (let keyPath?, nil):
return request.keyPath == keyPath
case (nil, nil):
return true
}
}
let clientBox = WeakClientBox(client)
return dropRequests(_requestsForClient[clientBox]?.filter(isMatchingRequest) ?? [])
}
@warn_unused_result(message="You must unobserve the returned keypaths")
private mutating func dropRequests(requestsToDrop: [ObservationRequest]) -> KeyPathObservationAction {
guard requestsToDrop.count > 0 else { return .none }
_requests.subtractInPlace(requestsToDrop)
var requestsForClient: [ WeakClientBox : Set<ObservationRequest> ] = [ : ]
var requestsForKeyPath: [ String : Set<ObservationRequest> ] = [ : ]
for request in _requests {
requestsForKeyPath.transformValueForKey(request.keyPath) { $0?.inserting(request) ?? Set([request]) }
requestsForClient.transformValueForKey(request.clientBox) { $0?.inserting(request) ?? Set([request]) }
}
_requestsForClient = requestsForClient
_requestsForKeyPath = requestsForKeyPath
var keypathsToRemove = Set<String>()
requestsToDrop.forEach { keypathsToRemove.insert($0.keyPath) }
return .unobserve(keypathsToRemove.subtract(allKeyPaths))
}
// MARK: - Adding requests
mutating func addForClient(client: AnyObject, keyPath: String, options: NSKeyValueObservingOptions, closure: PGKVOObservationClosure) -> KeyPathObservationAction {
func needsObserverForRequest(request: ObservationRequest) -> Bool {
return _requestsForKeyPath[keyPath]?
.reduce(NSKeyValueObservingOptions()) { $0.union($1.options) }
.intersect(options).isEmpty
?? true
}
let request = ObservationRequest(clientBox: WeakClientBox(client), keyPath: keyPath, options: options, closure: closure)
let action: KeyPathObservationAction = needsObserverForRequest(request) ? .observe(keyPath, options) : .none
_requests.insert(request)
_requestsForKeyPath.transformValueForKey(keyPath) {
$0?.inserting(request) ?? Set([request])
}
_requestsForClient.transformValueForKey(request.clientBox) {
$0?.inserting(request) ?? Set([request])
}
return action
}
}
| mit | 79b33d1850f466b04642447a37523c59 | 37.682171 | 167 | 0.665731 | 4.743346 | false | false | false | false |
DungeonKeepers/DnDInventoryManager | DnDInventoryManager/DnDInventoryManager/CampaignsTableViewController.swift | 1 | 2411 | //
// CampaignsTableViewController.swift
// DnDInventoryManager
//
// Created by Adrian Kenepah-Martin on 4/12/17.
// Copyright © 2017 Mike Miksch. All rights reserved.
//
import UIKit
import CloudKit
class CampaignsTableViewController: UITableViewController {
var campaignsList: Array<CKRecord> = []
@IBOutlet weak var campaignsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fetchCampaigns()
}
// MARK: fetchCampaigns Function
func fetchCampaigns() {
campaignsList = Array<CKRecord>()
let publicDatabase = CKContainer.default().publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Campaigns", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
publicDatabase.perform(query, inZoneWith: nil) { (results, error) in
if error != nil {
OperationQueue.main.addOperation {
print("Error: \(error.debugDescription)")
}
} else {
if let results = results {
for result in results {
self.campaignsList.append(result)
}
}
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return campaignsList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CampaignCell", for: indexPath) as UITableViewCell
let noteRecord: CKRecord = campaignsList[(indexPath.row)]
cell.textLabel?.text = noteRecord.value(forKey: "name") as? String
cell.imageView?.image = noteRecord.value(forKey: "img") as? UIImage
return cell
}
}
| mit | e557dbb8c5fa91f53507fc823d097cda | 32.013699 | 115 | 0.612033 | 5.285088 | false | false | false | false |
i-schuetz/rest_client_ios | clojushop_client_ios/CartItem.swift | 1 | 2908 | //
// CartItem.swift
// clojushop_client_ios
//
// Created by ischuetz on 06/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import Foundation
let JSON_KEY_CART_ITEM_ID = "id"
let JSON_KEY_CART_ITEM_NAME = "na"
let JSON_KEY_CART_IMAGE = "pic"
let JSON_KEY_CART_ITEM_DESCRIPTION = "des"
let JSON_KEY_CART_ITEM_PRICE = "pr"
let JSON_KEY_CART_ITEM_PRICE_VALUE = "v"
let JSON_KEY_CART_ITEM_PRICE_CURRENCY = "c"
let JSON_KEY_CART_ITEM_SELLER = "se"
let JSON_KEY_CART_ITEM_QUANTITY = "qt"
let JSON_KEY_CART_LIST = "pl"
let JSON_KEY_CART_DETAILS = "pd"
@objc
class CartItem {
let id:String!, name:String!, descr:String!, seller:String!, price:Double!, currency:String!, imgList:String!, imgDetails:String!
var quantity:Int!
init(id:String, name:String, descr:String, seller:String, price:Double, currency:String, quantity:Int, imgList:String, imgDetails:String) {
self.id = id
self.name = name
self.descr = descr
self.seller = seller
self.price = price
self.quantity = quantity
self.currency = currency
self.imgList = imgList
self.imgDetails = imgDetails
}
convenience init(dict: NSDictionary) {
let priceDictionary: NSDictionary = dict.objectForKey(JSON_KEY_CART_ITEM_PRICE) as NSDictionary
let imgDictionary: NSDictionary = dict.objectForKey(JSON_KEY_CART_IMAGE) as NSDictionary
let priceNSStr = priceDictionary.objectForKey(JSON_KEY_CART_ITEM_PRICE_VALUE) as NSString
let priceDouble:Double = (priceNSStr).doubleValue
self.init(
id: dict.objectForKey(JSON_KEY_CART_ITEM_ID) as NSString as String,
name: dict.objectForKey(JSON_KEY_CART_ITEM_NAME) as NSString as String,
descr: dict.objectForKey(JSON_KEY_DESCRIPTION) as NSString as String,
seller: dict.objectForKey(JSON_KEY_SELLER) as NSString as String,
price: priceDouble,
currency: priceDictionary.objectForKey(JSON_KEY_CART_ITEM_PRICE_CURRENCY) as NSString as String,
quantity: (dict.objectForKey(JSON_KEY_CART_ITEM_QUANTITY) as NSNumber).integerValue,
imgList: imgDictionary.objectForKey(JSON_KEY_CART_LIST) as NSString as String,
imgDetails: imgDictionary.objectForKey(JSON_KEY_CART_DETAILS) as NSString as String
)
}
//workaround for runtime error when calling the contructor from objective c
class func initWithDictHelper(dict: NSDictionary) -> CartItem {
return CartItem(dict: dict)
}
class func createFromDictArray (dictArray: NSArray) -> Array<CartItem> {
var itemsArray:[CartItem] = []
for dict: AnyObject in dictArray {
let a:NSDictionary = dict as NSDictionary
itemsArray.append(CartItem(dict: a))
}
return itemsArray
}
} | apache-2.0 | 31b047aaaba201fd5d7d4ba46325cd91 | 35.822785 | 143 | 0.665406 | 3.690355 | false | false | false | false |
FutureKit/FutureKit | FutureKit/Utils/Tuples.swift | 1 | 15528 | //
// Tuples.swift
// FutureKit
//
// Created by Michael Gray on 10/21/15.
// Copyright © 2015 Michael Gray. All rights reserved.
//
import Foundation
// This will extend 'indexable' collections, like Arrays to allow some conviences tuple implementations
public extension Sequence where Self:Collection, Self.Index : ExpressibleByIntegerLiteral {
fileprivate func _get_element<T>(_ index : Index) -> T {
let x = self[index]
let t = x as? T
assert(t != nil, "did not find type \(T.self) at index \(index) of \(Self.self)")
return t!
}
public func toTuple<A,B>() -> (A,B) {
return
(self._get_element(0),
self._get_element(1))
}
public func toTuple<A, B, C>() -> (A, B, C) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2))
}
public func toTuple<A, B, C, D>() -> (A, B, C, D) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3))
}
public func toTuple<A, B, C, D, E>() -> (A, B, C, D, E) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4))
}
public func toTuple<A, B, C, D, E, F>() -> (A, B, C, D, E, F) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5))
}
public func toTuple<A, B, C, D, E, F, G>() -> (A, B, C, D, E, F, G) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6))
}
public func toTuple<A, B, C, D, E, F, G, H>() -> (A, B, C, D, E, F, G, H) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6),
self._get_element(7))
}
public func toTuple<A, B, C, D, E, F, G, H, I>() -> (A, B, C, D, E, F, G, H, I) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6),
self._get_element(7),
self._get_element(8))
}
public func toTuple<A, B, C, D, E, F, G, H, I, J>() -> (A, B, C, D, E, F, G, H, I, J) {
return (self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6),
self._get_element(7),
self._get_element(8),
self._get_element(9))
}
public func toTuple<A, B, C, D, E, F, G, H, I, J, K>() -> (A, B, C, D, E, F, G, H, I, J, K) {
return (
self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6),
self._get_element(7),
self._get_element(8),
self._get_element(9),
self._get_element(10))
}
public func toTuple<A, B, C, D, E, F, G, H, I, J, K, L>() -> (A, B, C, D, E, F, G, H, I, J, K, L) {
return (self._get_element(0),
self._get_element(1),
self._get_element(2),
self._get_element(3),
self._get_element(4),
self._get_element(5),
self._get_element(6),
self._get_element(7),
self._get_element(8),
self._get_element(9),
self._get_element(10),
self._get_element(11))
}
}
public extension Sequence { // Some sequences don't have integer indexes, so we will use generators.
fileprivate func _get_element<T>(_ generator : inout Iterator) -> T {
let x = generator.next()
assert(x != nil, "toTuple() did not find enough values inside \(Self.self)")
let t = x! as? T
assert(t != nil, "toTuple() did not find type \(T.self) inside \(Self.self)")
return t!
}
public func toTuple<A,B>() -> (A,B) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
return (a,b)
}
public func toTuple<A, B, C>() -> (A, B, C) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
return (a,b,c)
}
public func toTuple<A, B, C, D>() -> (A, B, C, D) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
return (a,b,c,d)
}
public func toTuple<A, B, C, D, E>() -> (A, B, C, D, E) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
return (a,b,c,d,e)
}
public func toTuple<A, B, C, D, E, F>() -> (A, B, C, D, E, F) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
return (a,b,c,d,e,f)
}
public func toTuple<A, B, C, D, E, F, G>() -> (A, B, C, D, E, F, G) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
return (a,b,c,d,e,f,g)
}
public func toTuple<A, B, C, D, E, F, G, H>() -> (A, B, C, D, E, F, G, H) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
let h: H = self._get_element(&generator)
return (a,b,c,d,e,f,g,h)
}
public func toTuple<A, B, C, D, E, F, G, H, I>() -> (A, B, C, D, E, F, G, H, I) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
let h: H = self._get_element(&generator)
let i: I = self._get_element(&generator)
return (a,b,c,d,e,f,g,h,i)
}
public func toTuple<A, B, C, D, E, F, G, H, I, J>() -> (A, B, C, D, E, F, G, H, I, J) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
let h: H = self._get_element(&generator)
let i: I = self._get_element(&generator)
let j: J = self._get_element(&generator)
return (a,b,c,d,e,f,g,h,i,j)
}
public func toTuple<A, B, C, D, E, F, G, H, I, J, K>() -> (A, B, C, D, E, F, G, H, I, J, K) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
let h: H = self._get_element(&generator)
let i: I = self._get_element(&generator)
let j: J = self._get_element(&generator)
let k: K = self._get_element(&generator)
return (a,b,c,d,e,f,g,h,i,j,k)
}
public func toTuple<A, B, C, D, E, F, G, H, I, J, K, L>() -> (A, B, C, D, E, F, G, H, I, J, K, L) {
var generator = self.makeIterator()
let a: A = self._get_element(&generator)
let b: B = self._get_element(&generator)
let c: C = self._get_element(&generator)
let d: D = self._get_element(&generator)
let e: E = self._get_element(&generator)
let f: F = self._get_element(&generator)
let g: G = self._get_element(&generator)
let h: H = self._get_element(&generator)
let i: I = self._get_element(&generator)
let j: J = self._get_element(&generator)
let k: K = self._get_element(&generator)
let l: L = self._get_element(&generator)
return (a,b,c,d,e,f,g,h,i,j,k,l)
}
}
#if !swift(>=3.2)
extension ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = Element
}
#endif
public func tupleToArray<T : ExpressibleByArrayLiteral, A>(_ tuple:(A)) -> T {
return [tuple as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A,B>(_ tuple:(A,B)) -> T {
return [tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C>(_ tuple:(A, B, C)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D>(_ tuple:(A, B, C, D)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E>(_ tuple:(A, B, C, D, E)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F>(_ tuple:(A, B, C, D, E, F)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G>(_ tuple:(A, B, C, D, E, F, G)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G, H>(_ tuple:(A, B, C, D, E, F, G, H)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement,
tuple.7 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G, H, I>(_ tuple:(A, B, C, D, E, F, G, H, I)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement,
tuple.7 as! T.ArrayLiteralElement,
tuple.8 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G, H, I, J>(_ tuple:(A, B, C, D, E, F, G, H, I, J)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement,
tuple.7 as! T.ArrayLiteralElement,
tuple.8 as! T.ArrayLiteralElement,
tuple.9 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G, H, I, J, K>(_ tuple:(A, B, C, D, E, F, G, H, I, J, K)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement,
tuple.7 as! T.ArrayLiteralElement,
tuple.8 as! T.ArrayLiteralElement,
tuple.9 as! T.ArrayLiteralElement,
tuple.10 as! T.ArrayLiteralElement]
}
public func tupleToArray<T : ExpressibleByArrayLiteral,A, B, C, D, E, F, G, H, I, J, K, L>(_ tuple:(A, B, C, D, E, F, G, H, I, J, K, L)) -> T {
return
[tuple.0 as! T.ArrayLiteralElement,
tuple.1 as! T.ArrayLiteralElement,
tuple.2 as! T.ArrayLiteralElement,
tuple.3 as! T.ArrayLiteralElement,
tuple.4 as! T.ArrayLiteralElement,
tuple.5 as! T.ArrayLiteralElement,
tuple.6 as! T.ArrayLiteralElement,
tuple.7 as! T.ArrayLiteralElement,
tuple.8 as! T.ArrayLiteralElement,
tuple.9 as! T.ArrayLiteralElement,
tuple.10 as! T.ArrayLiteralElement,
tuple.11 as! T.ArrayLiteralElement]
}
| mit | 4cd4896e6467a73e76883bcae92cc036 | 38.012563 | 143 | 0.534875 | 3.349223 | false | false | false | false |
KikurageChan/SimpleConsoleView | SimpleConsoleView/Classes/Extensions/UIColorExt.swift | 1 | 838 | //
// ColorExtension.swift
// Glasgow
//
// Created by 木耳ちゃん on 2016/10/08.
// Copyright © 2016年 NetGroup. All rights reserved.
//
import UIKit
extension UIColor {
open class var random: UIColor {
return UIColor(Int(arc4random_uniform(256)),Int(arc4random_uniform(256)),Int(arc4random_uniform(256)))
}
convenience init(_ r:Int,_ g:Int,_ b:Int,a:CGFloat = 1.0) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0,alpha: a)
}
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat(hex & 0xFF) / 255.0
let a = alpha
self.init(red: red, green: green, blue: blue, alpha: a)
}
}
| mit | fd21f27b440b64dcbc1ae4e16f7fcc40 | 28.464286 | 110 | 0.591515 | 3.033088 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/Converters/StringAttributesToAttributes/Utility/HTMLStyleToggler.swift | 2 | 2143 | import Foundation
/// This is a utility class that contains some common logic for toggling styles in
/// an array of element nodes.
///
open class HTMLStyleToggler {
private let cssAttributeMatcher: CSSAttributeMatcher
private let defaultElement: Element
init(
defaultElement: Element,
cssAttributeMatcher: CSSAttributeMatcher) {
self.cssAttributeMatcher = cssAttributeMatcher
self.defaultElement = defaultElement
}
// MARK: - Enabling & Disabling
open func disable(in elementNodes: [ElementNode]) -> [ElementNode] {
let elementNodes = elementNodes.compactMap { (elementNode) -> ElementNode? in
let elementRepresentsStyle = defaultElement.equivalentNames.contains(elementNode.type)
guard elementRepresentsStyle else {
return elementNode
}
if elementNode.attributes.count > 0 {
return ElementNode(type: .span, attributes: elementNode.attributes, children: elementNode.children)
} else {
return nil
}
}
for elementNode in elementNodes {
elementNode.removeCSSAttributes(matching: cssAttributeMatcher)
}
return elementNodes
}
open func enable(in elementNodes: [ElementNode]) -> [ElementNode] {
var elementNodes = elementNodes
// We can now check if we have any CSS attribute that triggers the matcher. If that's the case we can completely skip
// adding the element.
//
for elementNode in elementNodes {
let elementRepresentsStyle = defaultElement.equivalentNames.contains(elementNode.type)
if elementRepresentsStyle || elementNode.containsCSSAttribute(matching: cssAttributeMatcher) {
return elementNodes
}
}
// Since there's no existing representation of the style, we will add the default one.
elementNodes.append(ElementNode(type: defaultElement))
return elementNodes
}
}
| mpl-2.0 | 335d7e8e75480bd69fa13d03d3c356ff | 34.131148 | 126 | 0.629958 | 5.466837 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Home/Cells/Dining/HomeDiningCellItem.swift | 1 | 1233 | //
// HomeDiningCellItem.swift
// PennMobile
//
// Created by Josh Doman on 3/5/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import Foundation
import SwiftyJSON
final class HomeDiningCellItem: HomeCellItem {
static var jsonKey: String {
return "dining"
}
static var associatedCell: ModularTableViewCell.Type {
return HomeDiningCell.self
}
var venues: [DiningVenue]
init(for venues: [DiningVenue]) {
self.venues = venues
}
func equals(item: ModularTableViewItem) -> Bool {
guard let item = item as? HomeDiningCellItem else { return false }
return venues == item.venues
}
static func getHomeCellItem(_ completion: @escaping((_ items: [HomeCellItem]) -> Void)) {
UserDBManager.shared.fetchDiningPreferences { result in
if let venues = try? result.get() {
if venues.count == 0 {
completion([HomeDiningCellItem(for: DiningAPI.instance.getVenues(with: DiningVenue.defaultVenueIds))])
} else {
completion([HomeDiningCellItem(for: venues)])
}
} else {
completion([])
}
}
}
}
| mit | 21bef85e317511f040c8bada06005dd5 | 25.782609 | 122 | 0.596591 | 4.463768 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Foundation/ExtraStringAPIs.swift | 1 | 1208 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
extension String.UTF16View.Index {
/// Construct from an integer offset.
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public init(_ offset: Int) {
_precondition(offset >= 0, "Negative UTF16 index offset not allowed")
self.init(encodedOffset: offset)
}
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public func distance(to other: String.UTF16View.Index?) -> Int {
return _offset.distance(to: other!._offset)
}
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public func advanced(by n: Int) -> String.UTF16View.Index {
return String.UTF16View.Index(_offset.advanced(by: n))
}
}
| apache-2.0 | 9b1e4599a17ec3a4a3bd0bb1489f7217 | 35.606061 | 80 | 0.615066 | 4.094915 | false | false | false | false |
InAppPurchase/InAppPurchase | InAppPurchase/InAppPurchase.swift | 1 | 12022 | // The MIT License (MIT)
//
// Copyright (c) 2015 Chris Davis
//
// 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.
//
// InAppPurchase.swift
// InAppPurchase
//
// Created by Chris Davis on 15/12/2015.
// Email: [email protected]
// Copyright © 2015 nthState. All rights reserved.
//
import Foundation
import StoreKit
// MARK: Block Definitions
/**
Type definitions for block response
*/
public typealias IAPDataResponse = (IAPModel?, NSError?) -> ()
// MARK: Class
public class InAppPurchase
{
// MARK: Properties
internal var networkService:IAPNetworkService // The networking service, for HTTP calls
internal var isInitalized:Bool? // Has the framework been initalized
public private(set) var apiKey:String! // ApiKey per app
public private(set) var userId:String! // UserId for association
// MARK: Initalizers
/**
Shared Instance
Singleton
*/
public class var sharedInstance: InAppPurchase {
struct Static {
static var instance: InAppPurchase?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = InAppPurchase()
}
return Static.instance!
}
/**
Initalizer.
Initalizes the InAppPurchase Framework
*/
private init()
{
networkService = IAPNetworkService()
}
/**
Convenience Initalizer.
*/
public convenience init(apiKey:String, userId:String)
{
self.init()
self.Initalize(apiKey, userId: userId)
}
/**
Initalize the framework with the correct keys
- parameter apiKey: Api Key for the app
- parameter userId: User Id for association
*/
public func Initalize(apiKey:String, userId:String)
{
if
apiKey.isEmpty ||
userId.isEmpty
{
let error = createError(kIAP_Error_Code_FrameworkNotInitalizedCorrectly,
reason: Localize("iap.apikeyuserkeyempty.reason"),
suggestion: Localize("iap.apikeyuserkeyempty.suggestion"))
IAPLogError(error)
return
}
self.apiKey = apiKey
self.userId = userId
self.isInitalized = true
networkService.apiKey = apiKey
networkService.userId = userId
}
// MARK: Actions
/**
Validates the receipt stored on disk
Does NOT save receipt to the API
- parameter response: The block which is called asynchronously with the result
*/
public func validateReceipt(response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Gather Data
let parameters:[NSObject:AnyObject] = [
"receiptData": self.getPaymentData()
]
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/receipt/validate"), method: .POST, parameters: parameters) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Saves the receipt stored on disk to the API
Uploads the receipt to server.
Processes receipt as per productId|data match,
Creates entitlements
- parameter response: The block which is called asynchronously with the result
*/
public func saveReceipt(response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Gather Data
let parameters:[NSObject:AnyObject] = [
"receiptData": self.getPaymentData()
]
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/receipt/save"), method: .POST, parameters: parameters) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Use a Consumable item
handlePartial? - I want to use 6, but only have 4 left.
- [entitlementId] - Unique id for each scalar item
error:
- product Id does not exist
- no items left to use.
- parameter productId: productId to use
- parameter scalar: Quanity to use
- parameter response: The block which is called asynchronously with the result
*/
public func use(productId:String, scalar:Int? = nil, onProductId:String? = nil, response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Validate Input
if productId.isEmpty
{
let error = createError(kIAP_Error_Code_MissingParameter,
reason: Localize("iap.parameterrequired.reason", parameters: "productId"),
suggestion: Localize("iap.parameterrequired.suggestion", parameters: "productId"))
IAPLogError(error)
return response(nil, error)
}
// Gather Data
var parameters:[NSObject:AnyObject] = [
"receiptData": self.getPaymentData(),
"productId": productId
]
if
let _scalar = scalar
{
if _scalar < 0
{
let error = createError(kIAP_Error_Code_OutOfRange,
reason: Localize("iap.parameteroutofrange.reason", parameters: "scalar"),
suggestion: Localize("iap.parameteroutofrange.suggestion", parameters: "scalar"))
IAPLogError(error)
return response(nil, error)
} else {
parameters["scalar"] = _scalar
}
}
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/product/use"), method: .PUT, parameters: parameters) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Allows ad-hoc items to be given to a user
- parameter hookId: hookId to use
- parameter response: The block which is called asynchronously with the result
*/
public func give(hookId:String, response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Validate Input
if hookId.isEmpty
{
let error = createError(kIAP_Error_Code_MissingParameter,
reason: Localize("iap.parameterrequired.reason", parameters: "hookId"),
suggestion: Localize("iap.parameterrequired.suggestion", parameters: "hookId"))
IAPLogError(error)
return response(nil, error)
}
// Gather Data
let parameters:[NSObject:AnyObject] = [
"receiptData": self.getPaymentData(),
"hookId": hookId
]
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/product/give"), method: .PUT, parameters: parameters) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Return all entitlements for a user
[
{
"entitlementId": "sdfsdfds",
"used": true|false
"dateUsed": nil|date,
"productId": "egertb",
"purchaseTransactionId": "345gerfs"
},...
]
- parameter response: The block which is called asynchronously with the result
*/
public func listEntitlements(response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/entitlement/list"), method: .GET, parameters: nil) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Has a specific entitlement been used?,
- parameter response: The block which is called asynchronously with the result
*/
public func validateEntitlement(entitlementId:String, response:IAPDataResponse)
{
// Check framework has been initalized
guard let _ = self.isInitalized else {
let error = frameworkNotInitalizedError
IAPLogError(error)
return response(nil, error)
}
// Validate Input
if entitlementId.isEmpty
{
let error = createError(kIAP_Error_Code_MissingParameter,
reason: Localize("iap.parameterrequired.reason", parameters: "entitlementId"),
suggestion: Localize("iap.parameterrequired.suggestion", parameters: "entitlementId"))
IAPLogError(error)
return response(nil, error)
}
// Gather Data
let parameters:[NSObject:AnyObject] = [
"receiptData": self.getPaymentData(),
"entitlementId": entitlementId
]
// Send Data
networkService.json(urlForMethod(.API, endPoint: "sdk/entitlement/validate"), method: .POST, parameters: parameters) { (model:IAPModel?, error:NSError?) -> () in
response(model, error)
}
}
/**
Checks the status of the api
- parameter response: The block which is called asynchronously with the result
*/
public func status(response:(Bool, IAPTupleModel?, NSError?) -> ())
{
// Send Data
networkService.json(urlForMethod(.STATUS, endPoint: "status"), method: .GET, parameters: nil) { (model:IAPTupleModel?, error:NSError?) -> () in
var running:Bool = false
if let isRunning = model?.status
where isRunning == 200
{
running = true
}
response(running, model, error)
}
}
// MARK: Helpers
/**
Gets the payment data as a string
- returns: String
*/
private func getPaymentData() -> String
{
let paymentDetails = IAPPaymentTransaction()
return paymentDetails.getReceiptDataAsBase64()
}
}
| mit | fedc2280682ccc82d7d1a1b54c11a0a1 | 30.386423 | 169 | 0.590883 | 4.860898 | false | false | false | false |
tgu/HAP | Sources/HAP/Security/ChaCha20Poly1305.swift | 1 | 2094 | // swiftlint:disable identifier_name line_length
import CLibSodium
import Foundation
class ChaCha20Poly1305 {
enum Error: Swift.Error {
case couldNotDecrypt, couldNotEncrypt
}
private static func upgradeNonce(_ nonce: Data) -> Data {
switch nonce.count {
case 12: return nonce
case 8: return Data(count: 4) + nonce
default: abort()
}
}
static func encrypt(message: Data, additional: Data = Data(), nonce: Data, key: Data) throws -> Data {
let nonce = upgradeNonce(nonce)
var cipher = Data(count: message.count + Int(crypto_aead_chacha20poly1305_ABYTES))
let result = cipher.withUnsafeMutableBytes { c in
message.withUnsafeBytes { m in
additional.withUnsafeBytes { ad in
nonce.withUnsafeBytes { npub in
key.withUnsafeBytes { k in
crypto_aead_chacha20poly1305_ietf_encrypt(c, nil, m, UInt64(message.count), ad, UInt64(additional.count), nil, npub, k)
}
}
}
}
}
guard result == 0 else {
throw Error.couldNotEncrypt
}
return cipher
}
static func decrypt(cipher: Data, additional: Data = Data(), nonce: Data, key: Data) throws -> Data {
let nonce = upgradeNonce(nonce)
var message = Data(count: cipher.count - Int(crypto_aead_chacha20poly1305_ietf_ABYTES))
let result = message.withUnsafeMutableBytes { m in
cipher.withUnsafeBytes { c in
additional.withUnsafeBytes { ad in
nonce.withUnsafeBytes { npub in
key.withUnsafeBytes { k in
crypto_aead_chacha20poly1305_ietf_decrypt(m, nil, nil, c, UInt64(cipher.count), ad, UInt64(additional.count), npub, k)
}
}
}
}
}
guard result == 0 else {
throw Error.couldNotDecrypt
}
return message
}
}
| mit | b8c0b5cbce42ef0b164d74ae42081eb2 | 35.736842 | 147 | 0.552053 | 4.622517 | false | false | false | false |
RxSwiftCommunity/RxAnimated | Example/Example for RxAnimated AppleTV/ViewController.swift | 1 | 4239 | //
// ViewController.swift
// RxAnimated-Example-AppleTV
//
// Created by Kristaps Grinbergs on 13/11/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxAnimated
class ViewController: UIViewController {
@IBOutlet var labelFade: UILabel!
@IBOutlet var labelFlip: UILabel!
@IBOutlet var labelCustom: UILabel!
@IBOutlet var imageFlip: UIImageView!
@IBOutlet var imageBlock: UIImageView!
@IBOutlet var labelAlpha: UILabel!
@IBOutlet var imageAlpha: UIImageView!
@IBOutlet var labelIsHidden: UILabel!
@IBOutlet var imageIsHidden: UIImageView!
@IBOutlet var leftConstraint: NSLayoutConstraint!
@IBOutlet var rightConstraint: NSLayoutConstraint!
private let timer = Observable<Int>.timer(0, period: 1, scheduler: MainScheduler.instance).share(replay: 1)
private let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Animate `text` with a crossfade
timer
.map { "Text + fade [\($0)]" }
.bind(animated: labelFade.rx.animated.fade(duration: 0.33).text)
.disposed(by: bag)
// Animate `text` with a top flip
timer
.delay(0.33, scheduler: MainScheduler.instance)
.map { "Text + flip [\($0)]" }
.bind(animated: labelFlip.rx.animated.flip(.top, duration: 0.33).text)
.disposed(by: bag)
// Animate `text` with a custom animation `tick`, as driver
timer
.delay(0.67, scheduler: MainScheduler.instance)
.map { "Text + custom [\($0)]" }
.asDriver(onErrorJustReturn: "error")
.bind(animated: labelCustom.rx.animated.tick(.left, duration: 0.75).text)
.disposed(by: bag)
// Animate `image` with a custom animation `tick`
timer
.scan("adorable1") { _, count in
return count % 2 == 0 ? "adorable1" : "adorable2"
}
.map { name in
return UIImage(named: name)!
}
.bind(animated: imageFlip.rx.animated.tick(.right, duration: 1.0).image)
.disposed(by: bag)
var angle: CGFloat = 0.0
// Animate `image` with a custom block
timer
.scan("adorable1") { _, count in
return count % 2 == 0 ? "adorable1" : "adorable2"
}
.map { name in
return UIImage(named: name)!
}
.bind(animated: imageBlock.rx.animated.animation(duration: 0.5, animations: { [weak self] in
angle += 0.2
self?.imageBlock.transform = CGAffineTransform(rotationAngle: angle)
}).image )
.disposed(by: bag)
// Animate layout constraint
timer
.scan(0) { acc, _ in
return acc == 0 ? 105 : 0
}
.bind(animated: leftConstraint.rx.animated.layout(duration: 0.33).constant )
.disposed(by: bag)
// Activate/Deactivate a constraint
timer
.scan(true) { acc, _ in
return !acc
}
.bind(animated: rightConstraint.rx.animated.layout(duration: 0.33).isActive )
.disposed(by: bag)
// Animate `alpha` with a flip
let timerAlpha = timer
.scan(1) { acc, _ in
return acc > 2 ? 1 : acc + 1
}
.map { CGFloat(1.0 / $0 ) }
timerAlpha
.bind(animated: imageAlpha.rx.animated.flip(.left, duration: 0.45).alpha)
.disposed(by: bag)
timerAlpha
.map { "alpha: \($0)" }
.bind(to: labelAlpha.rx.text)
.disposed(by: bag)
// Animate `isHidden` with a flip
let timerHidden = timer
.scan(false) { _, count in
return count % 2 == 0 ? true : false
}
timerHidden
.bind(animated: imageIsHidden.rx.animated.flip(.bottom, duration: 0.45).isHidden)
.disposed(by: bag)
timerHidden
.map { "hidden: \($0)" }
.bind(to: labelIsHidden.rx.text)
.disposed(by: bag)
// disable animations when the device is working hard or user is motion sensitive
RxAnimated.enableDefaultPerformanceHeuristics()
// disable animations manually
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
RxAnimated.areAnimationsEnabled.accept(false)
})
DispatchQueue.main.asyncAfter(deadline: .now() + 15.0, execute: {
RxAnimated.areAnimationsEnabled.accept(true)
})
}
}
| mit | 8abcee1fae53d682d78384add3af6a5a | 28.84507 | 109 | 0.623407 | 3.849228 | false | false | false | false |
psharanda/adocgen | Carthage/Checkouts/GRMustache.swift/Tests/Public/DocumentationTests/MustacheRenderableGuideTests.swift | 1 | 8398 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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 XCTest
import Mustache
class MustacheRenderableGuideTests: XCTestCase {
func testExample1() {
let render = { (info: RenderingInfo) -> Rendering in
switch info.tag.type {
case .variable:
return Rendering("I'm rendering a {{ variable }} tag.")
case .section:
return Rendering("I'm rendering a {{# section }}...{{/ }} tag.")
}
}
var rendering = try! Template(string: "{{.}}").render(render)
XCTAssertEqual(rendering, "I'm rendering a {{ variable }} tag.")
rendering = try! Template(string: "{{#.}}{{/}}").render(render)
XCTAssertEqual(rendering, "I'm rendering a {{# section }}...{{/ }} tag.")
}
func textExample2() {
let render = { (info: RenderingInfo) -> Rendering in
return Rendering("Arthur & Cie")
}
let rendering = try! Template(string: "{{.}}|{{{.}}}").render(render)
XCTAssertEqual(rendering, "Arthur & Cie|Arthur & Cie")
}
func textExample3() {
let render = { (info: RenderingInfo) -> Rendering in
let rendering = try! info.tag.render(info.context)
return Rendering("<strong>\(rendering.string)</strong>", rendering.contentType)
}
let value: [String: Any] = [
"strong": render,
"name": "Arthur"]
let rendering = try! Template(string: "{{#strong}}{{name}}{{/strong}}").render(value)
XCTAssertEqual(rendering, "<strong>Arthur</strong>")
}
func textExample4() {
let render = { (info: RenderingInfo) -> Rendering in
let rendering = try! info.tag.render(info.context)
return Rendering(rendering.string + rendering.string, rendering.contentType)
}
let value = ["twice": render]
let rendering = try! Template(string: "{{#twice}}Success{{/twice}}").render(value)
XCTAssertEqual(rendering, "SuccessSuccess")
}
func textExample5() {
let render = { (info: RenderingInfo) -> Rendering in
let template = try! Template(string: "<a href=\"{{url}}\">\(info.tag.innerTemplateString)</a>")
return try template.render(info.context)
}
let value: [String: Any] = [
"link": render,
"name": "Arthur",
"url": "/people/123"]
let rendering = try! Template(string: "{{# link }}{{ name }}{{/ link }}").render(value)
XCTAssertEqual(rendering, "<a href=\"/people/123\">Arthur</a>")
}
func testExample6() {
let repository = TemplateRepository(templates: [
"movieLink": "<a href=\"{{url}}\">{{title}}</a>",
"personLink": "<a href=\"{{url}}\">{{name}}</a>"])
let link1 = try! repository.template(named: "movieLink")
let item1: [String: Any] = [
"title": "Citizen Kane",
"url": "/movies/321",
"link": link1]
let link2 = try! repository.template(named: "personLink")
let item2: [String: Any] = [
"name": "Orson Welles",
"url": "/people/123",
"link": link2]
let value = ["items": [item1, item2]]
let rendering = try! Template(string: "{{#items}}{{link}}{{/items}}").render(value)
XCTAssertEqual(rendering, "<a href=\"/movies/321\">Citizen Kane</a><a href=\"/people/123\">Orson Welles</a>")
}
func testExample7() {
struct Person : MustacheBoxable {
let firstName: String
let lastName: String
var mustacheBox: MustacheBox {
let keyedSubscript = { (key: String) -> Any? in
switch key {
case "firstName":
return self.firstName
case "lastName":
return self.lastName
default:
return nil
}
}
let render = { (info: RenderingInfo) -> Rendering in
let template = try! Template(named: "Person", bundle: Bundle(for: MustacheRenderableGuideTests.self))
let context = info.context.extendedContext(self)
return try template.render(context)
}
return MustacheBox(
value: self,
keyedSubscript: keyedSubscript,
render: render)
}
}
struct Movie : MustacheBoxable {
let title: String
let director: Person
var mustacheBox: MustacheBox {
let keyedSubscript = { (key: String) -> Any? in
switch key {
case "title":
return self.title
case "director":
return self.director
default:
return nil
}
}
let render = { (info: RenderingInfo) -> Rendering in
let template = try! Template(named: "Movie", bundle: Bundle(for: MustacheRenderableGuideTests.self))
let context = info.context.extendedContext(self)
return try template.render(context)
}
return MustacheBox(
value: self,
keyedSubscript: keyedSubscript,
render: render)
}
}
let director = Person(firstName: "Orson", lastName: "Welles")
let movie = Movie(title:"Citizen Kane", director: director)
let template = try! Template(string: "{{ movie }}")
let rendering = try! template.render(["movie": movie])
XCTAssertEqual(rendering, "Citizen Kane by Orson Welles")
}
func testExample8() {
let listFilter = { (box: MustacheBox, info: RenderingInfo) -> Rendering in
guard let items = box.arrayValue else {
return Rendering("")
}
var buffer = "<ul>"
for item in items {
let itemContext = info.context.extendedContext(item)
let itemRendering = try! info.tag.render(itemContext)
buffer += "<li>\(itemRendering.string)</li>"
}
buffer += "</ul>"
return Rendering(buffer, .html)
}
let template = try! Template(string: "{{#list(nav)}}<a href=\"{{url}}\">{{title}}</a>{{/}}")
template.baseContext = template.baseContext.extendedContext(["list": Filter(listFilter)])
let item1 = [
"url": "http://mustache.github.io",
"title": "Mustache"]
let item2 = [
"url": "http://github.com/groue/GRMustache.swift",
"title": "GRMustache.swift"]
let value = ["nav": [item1, item2]]
let rendering = try! template.render(value)
XCTAssertEqual(rendering, "<ul><li><a href=\"http://mustache.github.io\">Mustache</a></li><li><a href=\"http://github.com/groue/GRMustache.swift\">GRMustache.swift</a></li></ul>")
}
}
| mit | edc20140516d54509329ed5c9c9ad84d | 40.776119 | 187 | 0.544123 | 4.760204 | false | false | false | false |
Asura19/SwiftAlgorithm | SwiftAlgorithm/SwiftAlgorithm/LC203.swift | 1 | 751 | //
// LeetCode203.swift
// SwiftAlgorithm
//
// Created by Phoenix on 2019/5/27.
// Copyright © 2019 Phoenix. All rights reserved.
//
import Foundation
extension LeetCode {
// LeetCode 203 https://leetcode.com/problems/remove-linked-list-elements/
static func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
guard let head = head else {
return nil
}
let fakeHead = ListNode(0)
fakeHead.next = head
var cur: ListNode? = fakeHead
while cur != nil {
if cur!.next?.value == val {
cur?.next = cur?.next?.next
}
else {
cur = cur?.next
}
}
return fakeHead.next
}
}
| mit | 7267065f11d68d4af92d53ccae5a0f2d | 23.193548 | 78 | 0.532 | 4.189944 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ZoomAndPanAChart/PanAndZoomChartView.swift | 1 | 3346 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// PanAndZoomChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class PanAndZoomChartView: SingleChartLayout {
override func initExample() {
let xAxis = SCINumericAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(3), max: SCIGeneric(6))
let yAxis = SCINumericAxis()
yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
let ds1 = SCIXyDataSeries(xType: .double, yType: .double)
let ds2 = SCIXyDataSeries(xType: .double, yType: .double)
let ds3 = SCIXyDataSeries(xType: .double, yType: .double)
let data1 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.01, pointCount: 1000, freq: 10)
let data2 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.024, pointCount: 1000, freq: 10)
let data3 = DataManager.getDampedSinewave(withPad: 300, amplitude: 1.0, phase: 0.0, dampingFactor: 0.049, pointCount: 1000, freq: 10)
ds1.appendRangeX(data1!.xValues, y: data1!.yValues, count: data1!.size)
ds2.appendRangeX(data2!.xValues, y: data2!.yValues, count: data2!.size)
ds3.appendRangeX(data3!.xValues, y: data3!.yValues, count: data3!.size)
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds1, brushColor: 0x77279B27, strokeColor: 0xFF177B17))
self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds2, brushColor: 0x77FF1919, strokeColor: 0xFFDD0909))
self.surface.renderableSeries.add(self.getRenderableSeriesWith(ds3, brushColor: 0x771964FF, strokeColor: 0xFF0944CF))
self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()])
}
}
fileprivate func getRenderableSeriesWith(_ dataSeries: SCIXyDataSeries, brushColor: UInt32, strokeColor: UInt32) -> SCIFastMountainRenderableSeries {
let rSeries = SCIFastMountainRenderableSeries()
rSeries.strokeStyle = SCISolidPenStyle(colorCode: strokeColor, withThickness: 1)
rSeries.areaStyle = SCISolidBrushStyle(colorCode: brushColor)
rSeries.dataSeries = dataSeries
rSeries.addAnimation(SCIWaveRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
return rSeries
}
}
| mit | 918d94a49655cc9e9af7f116f667dc78 | 56.637931 | 158 | 0.674843 | 4.18398 | false | false | false | false |
tache/SwifterSwift | Sources/Extensions/Foundation/DateExtensions.swift | 1 | 31733 | //
// DateExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
import Foundation
public extension Date {
/// SwifterSwift: Day name format.
///
/// - threeLetters: 3 letter day abbreviation of day name.
/// - oneLetter: 1 letter day abbreviation of day name.
/// - full: Full day name.
public enum DayNameStyle {
case threeLetters
case oneLetter
case full
}
/// SwifterSwift: Month name format.
///
/// - threeLetters: 3 letter month abbreviation of month name.
/// - oneLetter: 1 letter month abbreviation of month name.
/// - full: Full month name.
public enum MonthNameStyle {
case threeLetters
case oneLetter
case full
}
}
// MARK: - Properties
public extension Date {
/// SwifterSwift: User’s current calendar.
public var calendar: Calendar {
return Calendar.current
}
/// SwifterSwift: Era.
///
/// Date().era -> 1
///
public var era: Int {
return Calendar.current.component(.era, from: self)
}
/// SwifterSwift: Quarter.
///
/// Date().quarter -> 3 // date in third quarter of the year.
///
public var quarter: Int {
let month = Double(Calendar.current.component(.month, from: self))
let numberOfMonths = Double(Calendar.current.monthSymbols.count)
let numberOfMonthsInQuarter = numberOfMonths / 4
return Int(ceil(month/numberOfMonthsInQuarter))
}
/// SwifterSwift: Week of year.
///
/// Date().weekOfYear -> 2 // second week in the year.
///
public var weekOfYear: Int {
return Calendar.current.component(.weekOfYear, from: self)
}
/// SwifterSwift: Week of month.
///
/// Date().weekOfMonth -> 3 // date is in third week of the month.
///
public var weekOfMonth: Int {
return Calendar.current.component(.weekOfMonth, from: self)
}
/// SwifterSwift: Year.
///
/// Date().year -> 2017
///
/// var someDate = Date()
/// someDate.year = 2000 // sets someDate's year to 2000
///
public var year: Int {
get {
return Calendar.current.component(.year, from: self)
}
set {
guard newValue > 0 else { return }
let currentYear = Calendar.current.component(.year, from: self)
let yearsToAdd = newValue - currentYear
if let date = Calendar.current.date(byAdding: .year, value: yearsToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Month.
///
/// Date().month -> 1
///
/// var someDate = Date()
/// someDate.month = 10 // sets someDate's month to 10.
///
public var month: Int {
get {
return Calendar.current.component(.month, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .month, in: .year, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentMonth = Calendar.current.component(.month, from: self)
let monthsToAdd = newValue - currentMonth
if let date = Calendar.current.date(byAdding: .month, value: monthsToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Day.
///
/// Date().day -> 12
///
/// var someDate = Date()
/// someDate.day = 1 // sets someDate's day of month to 1.
///
public var day: Int {
get {
return Calendar.current.component(.day, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentDay = Calendar.current.component(.day, from: self)
let daysToAdd = newValue - currentDay
if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Weekday.
///
/// Date().weekday -> 5 // fifth day in the current week.
///
public var weekday: Int {
return Calendar.current.component(.weekday, from: self)
}
/// SwifterSwift: Hour.
///
/// Date().hour -> 17 // 5 pm
///
/// var someDate = Date()
/// someDate.hour = 13 // sets someDate's hour to 1 pm.
///
public var hour: Int {
get {
return Calendar.current.component(.hour, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .hour, in: .day, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentHour = Calendar.current.component(.hour, from: self)
let hoursToAdd = newValue - currentHour
if let date = Calendar.current.date(byAdding: .hour, value: hoursToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Minutes.
///
/// Date().minute -> 39
///
/// var someDate = Date()
/// someDate.minute = 10 // sets someDate's minutes to 10.
///
public var minute: Int {
get {
return Calendar.current.component(.minute, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .minute, in: .hour, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentMinutes = Calendar.current.component(.minute, from: self)
let minutesToAdd = newValue - currentMinutes
if let date = Calendar.current.date(byAdding: .minute, value: minutesToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Seconds.
///
/// Date().second -> 55
///
/// var someDate = Date()
/// someDate.second = 15 // sets someDate's seconds to 15.
///
public var second: Int {
get {
return Calendar.current.component(.second, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .second, in: .minute, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentSeconds = Calendar.current.component(.second, from: self)
let secondsToAdd = newValue - currentSeconds
if let date = Calendar.current.date(byAdding: .second, value: secondsToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Nanoseconds.
///
/// Date().nanosecond -> 981379985
///
/// var someDate = Date()
/// someDate.nanosecond = 981379985 // sets someDate's seconds to 981379985.
///
public var nanosecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self)
}
set {
let allowedRange = Calendar.current.range(of: .nanosecond, in: .second, for: self)!
guard allowedRange.contains(newValue) else { return }
let currentNanoseconds = Calendar.current.component(.nanosecond, from: self)
let nanosecondsToAdd = newValue - currentNanoseconds
if let date = Calendar.current.date(byAdding: .nanosecond, value: nanosecondsToAdd, to: self) {
self = date
}
}
}
/// SwifterSwift: Milliseconds.
///
/// Date().millisecond -> 68
///
/// var someDate = Date()
/// someDate.millisecond = 68 // sets someDate's nanosecond to 68000000.
///
public var millisecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self) / 1000000
}
set {
let ns = newValue * 1000000
let allowedRange = Calendar.current.range(of: .nanosecond, in: .second, for: self)!
guard allowedRange.contains(ns) else { return }
if let date = Calendar.current.date(bySetting: .nanosecond, value: ns, of: self) {
self = date
}
}
}
/// SwifterSwift: Check if date is in future.
///
/// Date(timeInterval: 100, since: Date()).isInFuture -> true
///
public var isInFuture: Bool {
return self > Date()
}
/// SwifterSwift: Check if date is in past.
///
/// Date(timeInterval: -100, since: Date()).isInPast -> true
///
public var isInPast: Bool {
return self < Date()
}
/// SwifterSwift: Check if date is within today.
///
/// Date().isInToday -> true
///
public var isInToday: Bool {
return Calendar.current.isDateInToday(self)
}
/// SwifterSwift: Check if date is within yesterday.
///
/// Date().isInYesterday -> false
///
public var isInYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
/// SwifterSwift: Check if date is within tomorrow.
///
/// Date().isInTomorrow -> false
///
public var isInTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
/// SwifterSwift: Check if date is within a weekend period.
public var isInWeekend: Bool {
return Calendar.current.isDateInWeekend(self)
}
/// SwifterSwift: Check if date is within a weekday period.
public var isWorkday: Bool {
return !Calendar.current.isDateInWeekend(self)
}
/// SwifterSwift: Check if date is within the current week.
public var isInCurrentWeek: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .weekOfYear)
}
/// SwifterSwift: Check if date is within the current month.
public var isInCurrentMonth: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .month)
}
/// SwifterSwift: Check if date is within the current year.
public var isInCurrentYear: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .year)
}
/// SwifterSwift: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSS) from date.
///
/// Date().iso8601String -> "2017-01-12T14:51:29.574Z"
///
public var iso8601String: String {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.string(from: self).appending("Z")
}
/// SwifterSwift: Nearest five minutes to date.
///
/// var date = Date() // "5:54 PM"
/// date.minute = 32 // "5:32 PM"
/// date.nearestFiveMinutes // "5:30 PM"
///
/// date.minute = 44 // "5:44 PM"
/// date.nearestFiveMinutes // "5:45 PM"
///
public var nearestFiveMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: self)
let min = components.minute!
components.minute! = min % 5 < 3 ? min - min % 5 : min + 5 - (min % 5)
components.second = 0
components.nanosecond = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest ten minutes to date.
///
/// var date = Date() // "5:57 PM"
/// date.minute = 34 // "5:34 PM"
/// date.nearestTenMinutes // "5:30 PM"
///
/// date.minute = 48 // "5:48 PM"
/// date.nearestTenMinutes // "5:50 PM"
///
public var nearestTenMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: self)
let min = components.minute!
components.minute? = min % 10 < 6 ? min - min % 10 : min + 10 - (min % 10)
components.second = 0
components.nanosecond = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest quarter hour to date.
///
/// var date = Date() // "5:57 PM"
/// date.minute = 34 // "5:34 PM"
/// date.nearestQuarterHour // "5:30 PM"
///
/// date.minute = 40 // "5:40 PM"
/// date.nearestQuarterHour // "5:45 PM"
///
public var nearestQuarterHour: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: self)
let min = components.minute!
components.minute! = min % 15 < 8 ? min - min % 15 : min + 15 - (min % 15)
components.second = 0
components.nanosecond = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest half hour to date.
///
/// var date = Date() // "6:07 PM"
/// date.minute = 41 // "6:41 PM"
/// date.nearestHalfHour // "6:30 PM"
///
/// date.minute = 51 // "6:51 PM"
/// date.nearestHalfHour // "7:00 PM"
///
public var nearestHalfHour: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: self)
let min = components.minute!
components.minute! = min % 30 < 15 ? min - min % 30 : min + 30 - (min % 30)
components.second = 0
components.nanosecond = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest hour to date.
///
/// var date = Date() // "6:17 PM"
/// date.nearestHour // "6:00 PM"
///
/// date.minute = 36 // "6:36 PM"
/// date.nearestHour // "7:00 PM"
///
public var nearestHour: Date {
let min = Calendar.current.component(.minute, from: self)
let components: Set<Calendar.Component> = [.year, .month, .day, .hour]
let date = Calendar.current.date(from: Calendar.current.dateComponents(components, from: self))!
if min < 30 {
return date
}
return Calendar.current.date(byAdding: .hour, value: 1, to: date)!
}
/// SwifterSwift: Time zone used currently by system.
///
/// Date().timeZone -> Europe/Istanbul (current)
///
public var timeZone: TimeZone {
return Calendar.current.timeZone
}
/// SwifterSwift: UNIX timestamp from date.
///
/// Date().unixTimestamp -> 1484233862.826291
///
public var unixTimestamp: Double {
return timeIntervalSince1970
}
}
// MARK: - Methods
public extension Date {
/// SwifterSwift: Date by adding multiples of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:07 PM"
/// let date2 = date.adding(.minute, value: -10) // "Jan 12, 2017, 6:57 PM"
/// let date3 = date.adding(.day, value: 4) // "Jan 16, 2017, 7:07 PM"
/// let date4 = date.adding(.month, value: 2) // "Mar 12, 2017, 7:07 PM"
/// let date5 = date.adding(.year, value: 13) // "Jan 12, 2030, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of components to add.
/// - Returns: original date + multiples of component added.
public func adding(_ component: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: component, value: value, to: self)!
}
/// SwifterSwift: Add calendar component to date.
///
/// var date = Date() // "Jan 12, 2017, 7:07 PM"
/// date.add(.minute, value: -10) // "Jan 12, 2017, 6:57 PM"
/// date.add(.day, value: 4) // "Jan 16, 2017, 7:07 PM"
/// date.add(.month, value: 2) // "Mar 12, 2017, 7:07 PM"
/// date.add(.year, value: 13) // "Jan 12, 2030, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of compnenet to add.
public mutating func add(_ component: Calendar.Component, value: Int) {
if let date = Calendar.current.date(byAdding: component, value: value, to: self) {
self = date
}
}
/// SwifterSwift: Date by changing value of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:07 PM"
/// let date2 = date.changing(.minute, value: 10) // "Jan 12, 2017, 6:10 PM"
/// let date3 = date.changing(.day, value: 4) // "Jan 4, 2017, 7:07 PM"
/// let date4 = date.changing(.month, value: 2) // "Feb 12, 2017, 7:07 PM"
/// let date5 = date.changing(.year, value: 2000) // "Jan 12, 2000, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: new value of compnenet to change.
/// - Returns: original date after changing given component to given value.
public func changing(_ component: Calendar.Component, value: Int) -> Date? {
switch component {
case .nanosecond:
let allowedRange = Calendar.current.range(of: .nanosecond, in: .second, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentNanoseconds = Calendar.current.component(.nanosecond, from: self)
let nanosecondsToAdd = value - currentNanoseconds
return Calendar.current.date(byAdding: .nanosecond, value: nanosecondsToAdd, to: self)
case .second:
let allowedRange = Calendar.current.range(of: .second, in: .minute, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentSeconds = Calendar.current.component(.second, from: self)
let secondsToAdd = value - currentSeconds
return Calendar.current.date(byAdding: .second, value: secondsToAdd, to: self)
case .minute:
let allowedRange = Calendar.current.range(of: .minute, in: .hour, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentMinutes = Calendar.current.component(.minute, from: self)
let minutesToAdd = value - currentMinutes
return Calendar.current.date(byAdding: .minute, value: minutesToAdd, to: self)
case .hour:
let allowedRange = Calendar.current.range(of: .hour, in: .day, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentHour = Calendar.current.component(.hour, from: self)
let hoursToAdd = value - currentHour
return Calendar.current.date(byAdding: .hour, value: hoursToAdd, to: self)
case .day:
let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentDay = Calendar.current.component(.day, from: self)
let daysToAdd = value - currentDay
return Calendar.current.date(byAdding: .day, value: daysToAdd, to: self)
case .month:
let allowedRange = Calendar.current.range(of: .month, in: .year, for: self)!
guard allowedRange.contains(value) else { return nil }
let currentMonth = Calendar.current.component(.month, from: self)
let monthsToAdd = value - currentMonth
return Calendar.current.date(byAdding: .month, value: monthsToAdd, to: self)
case .year:
guard value > 0 else { return nil }
let currentYear = Calendar.current.component(.year, from: self)
let yearsToAdd = value - currentYear
return Calendar.current.date(byAdding: .year, value: yearsToAdd, to: self)
default:
return Calendar.current.date(bySetting: component, value: value, of: self)
}
}
/// SwifterSwift: Data at the beginning of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:14 PM"
/// let date2 = date.beginning(of: .hour) // "Jan 12, 2017, 7:00 PM"
/// let date3 = date.beginning(of: .month) // "Jan 1, 2017, 12:00 AM"
/// let date4 = date.beginning(of: .year) // "Jan 1, 2017, 12:00 AM"
///
/// - Parameter component: calendar component to get date at the beginning of.
/// - Returns: date at the beginning of calendar component (if applicable).
public func beginning(of component: Calendar.Component) -> Date? {
if component == .day {
return Calendar.current.startOfDay(for: self)
}
var components: Set<Calendar.Component> {
switch component {
case .second:
return [.year, .month, .day, .hour, .minute, .second]
case .minute:
return [.year, .month, .day, .hour, .minute]
case .hour:
return [.year, .month, .day, .hour]
case .weekOfYear, .weekOfMonth:
return [.yearForWeekOfYear, .weekOfYear]
case .month:
return [.year, .month]
case .year:
return [.year]
default:
return []
}
}
guard !components.isEmpty else { return nil }
return Calendar.current.date(from: Calendar.current.dateComponents(components, from: self))
}
/// SwifterSwift: Date at the end of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:27 PM"
/// let date2 = date.end(of: .day) // "Jan 12, 2017, 11:59 PM"
/// let date3 = date.end(of: .month) // "Jan 31, 2017, 11:59 PM"
/// let date4 = date.end(of: .year) // "Dec 31, 2017, 11:59 PM"
///
/// - Parameter component: calendar component to get date at the end of.
/// - Returns: date at the end of calendar component (if applicable).
public func end(of component: Calendar.Component) -> Date? {
switch component {
case .second:
var date = adding(.second, value: 1)
date = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date))!
date.add(.second, value: -1)
return date
case .minute:
var date = adding(.minute, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date))!
date = after.adding(.second, value: -1)
return date
case .hour:
var date = adding(.hour, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour], from: date))!
date = after.adding(.second, value: -1)
return date
case .day:
var date = adding(.day, value: 1)
date = Calendar.current.startOfDay(for: date)
date.add(.second, value: -1)
return date
case .weekOfYear, .weekOfMonth:
var date = self
let beginningOfWeek = Calendar.current.date(from:
Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date))!
date = beginningOfWeek.adding(.day, value: 7).adding(.second, value: -1)
return date
case .month:
var date = adding(.month, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month], from: date))!
date = after.adding(.second, value: -1)
return date
case .year:
var date = adding(.year, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year], from: date))!
date = after.adding(.second, value: -1)
return date
default:
return nil
}
}
/// SwifterSwift: Check if date is in current given calendar component.
///
/// Date().isInCurrent(.day) -> true
/// Date().isInCurrent(.year) -> true
///
/// - Parameter component: calendar component to check.
/// - Returns: true if date is in current given calendar component.
public func isInCurrent(_ component: Calendar.Component) -> Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: component)
}
/// SwifterSwift: Date string from date.
///
/// Date().string(withFormat: "dd/MM/yyyy") -> "1/12/17"
/// Date().string(withFormat: "HH:mm") -> "23:50"
/// Date().string(withFormat: "dd/MM/yyyy HH:mm") -> "1/12/17 23:50"
///
/// - Parameter format: Date format (default is "dd/MM/yyyy").
/// - Returns: date string.
public func string(withFormat format: String = "dd/MM/yyyy HH:mm") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
/// SwifterSwift: Date string from date.
///
/// Date().dateString(ofStyle: .short) -> "1/12/17"
/// Date().dateString(ofStyle: .medium) -> "Jan 12, 2017"
/// Date().dateString(ofStyle: .long) -> "January 12, 2017"
/// Date().dateString(ofStyle: .full) -> "Thursday, January 12, 2017"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date string.
public func dateString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Date and time string from date.
///
/// Date().dateTimeString(ofStyle: .short) -> "1/12/17, 7:32 PM"
/// Date().dateTimeString(ofStyle: .medium) -> "Jan 12, 2017, 7:32:00 PM"
/// Date().dateTimeString(ofStyle: .long) -> "January 12, 2017 at 7:32:00 PM GMT+3"
/// Date().dateTimeString(ofStyle: .full) -> "Thursday, January 12, 2017 at 7:32:00 PM GMT+03:00"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date and time string.
public func dateTimeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Time string from date
///
/// Date().timeString(ofStyle: .short) -> "7:37 PM"
/// Date().timeString(ofStyle: .medium) -> "7:37:02 PM"
/// Date().timeString(ofStyle: .long) -> "7:37:02 PM GMT+3"
/// Date().timeString(ofStyle: .full) -> "7:37:02 PM GMT+03:00"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: time string.
public func timeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = .none
return dateFormatter.string(from: self)
}
/// SwifterSwift: Day name from date.
///
/// Date().dayName(ofStyle: .oneLetter) -> "T"
/// Date().dayName(ofStyle: .threeLetters) -> "Thu"
/// Date().dayName(ofStyle: .full) -> "Thursday"
///
/// - Parameter Style: style of day name (default is DayNameStyle.full).
/// - Returns: day name string (example: W, Wed, Wednesday).
public func dayName(ofStyle style: DayNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "EEEEE"
case .threeLetters:
return "EEE"
case .full:
return "EEEE"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
/// SwifterSwift: Month name from date.
///
/// Date().monthName(ofStyle: .oneLetter) -> "J"
/// Date().monthName(ofStyle: .threeLetters) -> "Jan"
/// Date().monthName(ofStyle: .full) -> "January"
///
/// - Parameter Style: style of month name (default is MonthNameStyle.full).
/// - Returns: month name string (example: D, Dec, December).
public func monthName(ofStyle style: MonthNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "MMMMM"
case .threeLetters:
return "MMM"
case .full:
return "MMMM"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
/// SwifterSwift: get number of seconds between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of seconds between self and given date.
public func secondsSince(_ date: Date) -> Double {
return timeIntervalSince(date)
}
/// SwifterSwift: get number of minutes between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of minutes between self and given date.
public func minutesSince(_ date: Date) -> Double {
return timeIntervalSince(date)/60
}
/// SwifterSwift: get number of hours between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of hours between self and given date.
public func hoursSince(_ date: Date) -> Double {
return timeIntervalSince(date)/3600
}
/// SwifterSwift: get number of days between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of days between self and given date.
public func daysSince(_ date: Date) -> Double {
return timeIntervalSince(date)/(3600*24)
}
/// SwifterSwift: check if a date is between two other dates
///
/// - Parameters:
/// - startDate: start date to compare self to.
/// - endDate: endDate date to compare self to.
/// - includeBounds: true if the start and end date should be included (default is false)
/// - Returns: true if the date is between the two given dates.
public func isBetween(_ startDate: Date, _ endDate: Date, includeBounds: Bool = false) -> Bool {
if includeBounds {
return startDate.compare(self).rawValue * compare(endDate).rawValue >= 0
}
return startDate.compare(self).rawValue * compare(endDate).rawValue > 0
}
/// SwifterSwift: check if a date is a number of date components of another date
///
/// - Parameters:
/// - value: number of times component is used in creating range
/// - component: Calendar.Component to use.
/// - date: Date to compare self to.
/// - Returns: true if the date is within a number of components of another date
public func isWithin(_ value: UInt, _ component: Calendar.Component, of date: Date) -> Bool {
let components = Calendar.current.dateComponents([component], from: self, to: date)
let componentValue = components.value(for: component)!
return abs(componentValue) <= value
}
/// SwifterSwift: Random date between two dates.
///
/// Date.random()
/// Date.random(from: Date())
/// Date.random(upTo: Date())
/// Date.random(from: Date(), upTo: Date())
///
/// - Parameters:
/// - fromDate: minimum date (default is Date.distantPast)
/// - toDate: maximum date (default is Date.distantFuture)
/// - Returns: random date between two dates.
public static func random(from fromDate: Date = Date.distantPast,
upTo toDate: Date = Date.distantFuture) -> Date {
guard fromDate != toDate else {
return fromDate
}
let diff = llabs(Int64(toDate.timeIntervalSinceReferenceDate - fromDate.timeIntervalSinceReferenceDate))
var randomValue: Int64 = 0
arc4random_buf(&randomValue, MemoryLayout<Int64>.size)
randomValue = llabs(randomValue%diff)
let startReferenceDate = toDate > fromDate ? fromDate : toDate
return startReferenceDate.addingTimeInterval(TimeInterval(randomValue))
}
}
// MARK: - Initializers
public extension Date {
/// SwifterSwift: Create a new date form calendar components.
///
/// let date = Date(year: 2010, month: 1, day: 12) // "Jan 12, 2010, 7:45 PM"
///
/// - Parameters:
/// - calendar: Calendar (default is current).
/// - timeZone: TimeZone (default is current).
/// - era: Era (default is current era).
/// - year: Year (default is current year).
/// - month: Month (default is current month).
/// - day: Day (default is today).
/// - hour: Hour (default is current hour).
/// - minute: Minute (default is current minute).
/// - second: Second (default is current second).
/// - nanosecond: Nanosecond (default is current nanosecond).
public init?(
calendar: Calendar? = Calendar.current,
timeZone: TimeZone? = TimeZone.current,
era: Int? = Date().era,
year: Int? = Date().year,
month: Int? = Date().month,
day: Int? = Date().day,
hour: Int? = Date().hour,
minute: Int? = Date().minute,
second: Int? = Date().second,
nanosecond: Int? = Date().nanosecond) {
var components = DateComponents()
components.calendar = calendar
components.timeZone = timeZone
components.era = era
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
if let date = calendar?.date(from: components) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create date object from ISO8601 string.
///
/// let date = Date(iso8601String: "2017-01-12T16:48:00.959Z") // "Jan 12, 2017, 7:48 PM"
///
/// - Parameter iso8601String: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
public init?(iso8601String: String) {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: iso8601String) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create new date object from UNIX timestamp.
///
/// let date = Date(unixTimestamp: 1484239783.922743) // "Jan 12, 2017, 7:49 PM"
///
/// - Parameter unixTimestamp: UNIX timestamp.
public init(unixTimestamp: Double) {
self.init(timeIntervalSince1970: unixTimestamp)
}
/// SwifterSwift: Create date object from Int literal
///
/// let date = Date(integerLiteral: 2017_12_25) // "2017-12-25 00:00:00 +0000"
/// - Parameter value: Int value, e.g. 20171225, or 2017_12_25 etc.
public init?(integerLiteral value: Int) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
guard let date = formatter.date(from: String(value)) else { return nil }
self = date
}
}
| mit | 52c2cb4563144f2cbd96c887c3c5e92d | 31.914938 | 123 | 0.658336 | 3.337541 | false | false | false | false |
Prosumma/Guise | Sources/Guise/Common/Container.swift | 1 | 2715 | //
// Container.swift
// Guise
//
// Created by Gregory Higley on 2022-09-20.
//
import Foundation
import OrderedCollections
public class Container {
public let parent: Container?
private let lock = DispatchQueue(label: "Guise Container Entry Lock", attributes: .concurrent)
private var entries: [Key: any Resolvable] = [:]
public init(parent: Container? = nil) {
self.parent = parent
}
}
extension Container: Resolver {
public func resolve(criteria: Criteria) -> [Key: any Resolvable] {
lock.sync {
let result: [Key: any Resolvable]
if let parent {
let parentEntries = parent.resolve(criteria: criteria)
let childEntries = entries.filter { criteria ~= $0 }
// Entries in this container override entries in its parent.
result = parentEntries.merging(childEntries, uniquingKeysWith: { _, new in new })
} else {
result = entries.filter { criteria ~= $0 }
}
return result
}
}
}
extension Container: Registrar {
public func register<T, A>(
_ type: T.Type,
tags: Set<AnyHashable>,
lifetime: Lifetime,
factory: @escaping SyncFactory<T, A>
) -> Key {
let key = Key(type, tags: tags, args: A.self)
let entry = Entry(key: key, lifetime: lifetime, factory: factory)
register(key: key, resolvable: entry)
return key
}
public func register<T, A>(
_ type: T.Type,
tags: Set<AnyHashable>,
lifetime: Lifetime,
factory: @escaping AsyncFactory<T, A>
) -> Key {
let key = Key(type, tags: tags, args: A.self)
let entry = Entry(key: key, lifetime: lifetime, factory: factory)
register(key: key, resolvable: entry)
return key
}
public func unregister(keys: Set<Key>) {
lock.sync(flags: .barrier) {
entries = entries.filter { !keys.contains($0.key) }
}
}
private func register(key: Key, resolvable: any Resolvable) {
lock.sync(flags: .barrier) {
entries[key] = resolvable
}
}
}
extension Container: Assembler {
public func assemble(_ assembly: some Assembly) {
var assemblies: OrderedDictionary<String, any Assembly> = [:]
add(assembly: assembly, to: &assemblies)
for assembly in assemblies.values {
assembly.register(in: self)
}
for assembly in assemblies.values {
assembly.registered(to: self)
}
}
private func add(assembly: any Assembly, to assemblies: inout OrderedDictionary<String, any Assembly>) {
let key = String(reflecting: type(of: assembly))
guard !assemblies.keys.contains(key) else { return }
for dependentAssembly in assembly.dependentAssemblies {
add(assembly: dependentAssembly, to: &assemblies)
}
assemblies[key] = assembly
}
}
| mit | 09826b97d184a0f2b09eaee8787ddb55 | 27.28125 | 106 | 0.656722 | 3.86202 | false | false | false | false |
sonnygauran/trailer | PocketTrailer/ServerDetailViewController.swift | 1 | 6596 |
import SafariServices
import CoreData
final class ServerDetailViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var apiPath: UITextField!
@IBOutlet weak var webFrontEnd: UITextField!
@IBOutlet weak var authToken: UITextField!
@IBOutlet weak var reportErrors: UISwitch!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var authTokenLabel: UILabel!
@IBOutlet weak var testButton: UIButton!
var serverId: NSManagedObjectID?
private var focusedField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
var a: ApiServer
if let sid = serverId {
a = existingObjectWithID(sid) as! ApiServer
} else {
a = ApiServer.addDefaultGithubInMoc(mainObjectContext)
try! mainObjectContext.save()
serverId = a.objectID
}
name.text = a.label
apiPath.text = a.apiPath
webFrontEnd.text = a.webPath
authToken.text = a.authToken
reportErrors.on = a.reportRefreshFailures.boolValue
if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad {
let n = NSNotificationCenter.defaultCenter()
n.addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
n.addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object:nil)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setToolbarHidden(false, animated: true)
processTokenStateFrom(authToken.text)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setToolbarHidden(true, animated: true)
}
@IBAction func testConnectionSelected(sender: UIButton) {
if let a = updateServerFromForm() {
sender.enabled = false
api.testApiToServer(a) { error in
sender.enabled = true
showMessage(error != nil ? "Failed" : "Success", error?.localizedDescription)
}
}
}
private func updateServerFromForm() -> ApiServer? {
if let sid = serverId {
let a = existingObjectWithID(sid) as! ApiServer
a.label = name.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
a.apiPath = apiPath.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
a.webPath = webFrontEnd.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
a.authToken = authToken.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
a.reportRefreshFailures = reportErrors.on
a.lastSyncSucceeded = true
app.preferencesDirty = true
processTokenStateFrom(a.authToken)
return a
} else {
return nil
}
}
private func processTokenStateFrom(tokenText: String?) {
if (tokenText ?? "").isEmpty {
authTokenLabel.textColor = UIColor.redColor()
testButton.enabled = false
testButton.alpha = 0.6
} else {
authTokenLabel.textColor = UIColor.blackColor()
testButton.enabled = true
testButton.alpha = 1.0
}
}
@IBAction func reportChanged(sender: UISwitch) {
updateServerFromForm()
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
updateServerFromForm()
return true
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
focusedField = textField
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string == "\n" {
textField.resignFirstResponder()
return false
}
if textField == authToken {
let newToken = textField.text?.stringByReplacingCharactersInRange(range, withString: string)
processTokenStateFrom(newToken)
}
return true
}
@IBAction func watchListSelected(sender: UIBarButtonItem) {
openGitHub("/watching")
}
@IBAction func createTokenSelected(sender: UIBarButtonItem) {
openGitHub("/settings/tokens/new")
}
@IBAction func existingTokensSelected(sender: UIBarButtonItem) {
openGitHub("/settings/applications")
}
private func checkForValidPath() -> NSURL? {
if let text = webFrontEnd.text, u = NSURL(string: text) {
return u
} else {
showMessage("Need a valid web server", "Please specify a valid URL for the 'Web Front End' for this server in order to visit it")
return nil
}
}
private func openGitHub(url: String) {
if let u = checkForValidPath()?.absoluteString {
let s = SFSafariViewController(URL: NSURL(string: u + url)!)
s.view.tintColor = self.view.tintColor
self.presentViewController(s, animated: true, completion: nil)
}
}
@IBAction func deleteSelected(sender: UIBarButtonItem) {
let a = UIAlertController(title: "Delete API Server",
message: "Are you sure you want to remove this API server from your list?",
preferredStyle: UIAlertControllerStyle.Alert)
a.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
a.addAction(UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: { [weak self] action in
self!.deleteServer()
}))
presentViewController(a, animated: true, completion: nil)
}
private func deleteServer() {
if let a = existingObjectWithID(serverId!) {
mainObjectContext.deleteObject(a)
DataManager.saveDB()
}
serverId = nil
navigationController?.popViewControllerAnimated(true)
}
///////////////////////// keyboard
func keyboardWillShow(notification: NSNotification) {
if focusedField?.superview == nil { return }
if let info = notification.userInfo as [NSObject : AnyObject]?, keyboardFrameValue = info[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardFrame = keyboardFrameValue.CGRectValue()
let keyboardHeight = max(0, view.bounds.size.height-keyboardFrame.origin.y)
let firstResponderFrame = view.convertRect(focusedField!.frame, fromView: focusedField!.superview)
let bottomOfFirstResponder = (firstResponderFrame.origin.y + firstResponderFrame.size.height) + 36
let topOfKeyboard = view.bounds.size.height - keyboardHeight
if bottomOfFirstResponder > topOfKeyboard {
let distance = bottomOfFirstResponder - topOfKeyboard
scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y + distance)
}
}
}
func keyboardWillHide(notification: NSNotification) {
if !scrollView.dragging {
scrollView.scrollRectToVisible(CGRectMake(0,
min(scrollView.contentOffset.y, scrollView.contentSize.height - scrollView.bounds.size.height),
scrollView.bounds.size.width, scrollView.bounds.size.height), animated: false)
}
}
}
| mit | fa311d2ef7ca157101d23263447b7409 | 32.482234 | 136 | 0.754851 | 4.15627 | false | false | false | false |
turbolinks/turbolinks-ios | Turbolinks/WebView.swift | 1 | 7807 | import WebKit
protocol WebViewDelegate: class {
func webView(_ webView: WebView, didProposeVisitToLocation location: URL, withAction action: Action)
func webViewDidInvalidatePage(_ webView: WebView)
func webView(_ webView: WebView, didFailJavaScriptEvaluationWithError error: NSError)
}
protocol WebViewPageLoadDelegate: class {
func webView(_ webView: WebView, didLoadPageWithRestorationIdentifier restorationIdentifier: String)
}
protocol WebViewVisitDelegate: class {
func webView(_ webView: WebView, didStartVisitWithIdentifier identifier: String, hasCachedSnapshot: Bool)
func webView(_ webView: WebView, didStartRequestForVisitWithIdentifier identifier: String)
func webView(_ webView: WebView, didCompleteRequestForVisitWithIdentifier identifier: String)
func webView(_ webView: WebView, didFailRequestForVisitWithIdentifier identifier: String, statusCode: Int)
func webView(_ webView: WebView, didFinishRequestForVisitWithIdentifier identifier: String)
func webView(_ webView: WebView, didRenderForVisitWithIdentifier identifier: String)
func webView(_ webView: WebView, didCompleteVisitWithIdentifier identifier: String, restorationIdentifier: String)
}
class WebView: WKWebView {
weak var delegate: WebViewDelegate?
weak var pageLoadDelegate: WebViewPageLoadDelegate?
weak var visitDelegate: WebViewVisitDelegate?
init(configuration: WKWebViewConfiguration) {
super.init(frame: CGRect.zero, configuration: configuration)
let bundle = Bundle(for: type(of: self))
let source = try! String(contentsOf: bundle.url(forResource: "WebView", withExtension: "js")!, encoding: String.Encoding.utf8)
let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
configuration.userContentController.addUserScript(userScript)
configuration.userContentController.add(self, name: "turbolinks")
translatesAutoresizingMaskIntoConstraints = false
scrollView.decelerationRate = UIScrollView.DecelerationRate.normal
if #available(iOS 11, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func visitLocation(_ location: URL, withAction action: Action, restorationIdentifier: String?) {
callJavaScriptFunction("webView.visitLocationWithActionAndRestorationIdentifier", withArguments: [location.absoluteString as Optional<AnyObject>, action.rawValue as Optional<AnyObject>, restorationIdentifier as Optional<AnyObject>])
}
func issueRequestForVisitWithIdentifier(_ identifier: String) {
callJavaScriptFunction("webView.issueRequestForVisitWithIdentifier", withArguments: [identifier as Optional<AnyObject>])
}
func changeHistoryForVisitWithIdentifier(_ identifier: String) {
callJavaScriptFunction("webView.changeHistoryForVisitWithIdentifier", withArguments: [identifier as Optional<AnyObject>])
}
func loadCachedSnapshotForVisitWithIdentifier(_ identifier: String) {
callJavaScriptFunction("webView.loadCachedSnapshotForVisitWithIdentifier", withArguments: [identifier as Optional<AnyObject>])
}
func loadResponseForVisitWithIdentifier(_ identifier: String) {
callJavaScriptFunction("webView.loadResponseForVisitWithIdentifier", withArguments: [identifier as Optional<AnyObject>])
}
func cancelVisitWithIdentifier(_ identifier: String) {
callJavaScriptFunction("webView.cancelVisitWithIdentifier", withArguments: [identifier as Optional<AnyObject>])
}
// MARK: JavaScript Evaluation
private func callJavaScriptFunction(_ functionExpression: String, withArguments arguments: [AnyObject?] = [], completionHandler: ((AnyObject?) -> ())? = nil) {
guard let script = scriptForCallingJavaScriptFunction(functionExpression, withArguments: arguments) else {
NSLog("Error encoding arguments for JavaScript function `%@'", functionExpression)
return
}
evaluateJavaScript(script) { (result, error) in
if let result = result as? [String: AnyObject] {
if let error = result["error"] as? String, let stack = result["stack"] as? String {
NSLog("Error evaluating JavaScript function `%@': %@\n%@", functionExpression, error, stack)
} else {
completionHandler?(result["value"])
}
} else if let error = error {
self.delegate?.webView(self, didFailJavaScriptEvaluationWithError: error as NSError)
}
}
}
private func scriptForCallingJavaScriptFunction(_ functionExpression: String, withArguments arguments: [AnyObject?]) -> String? {
guard let encodedArguments = encodeJavaScriptArguments(arguments) else { return nil }
return
"(function(result) {\n" +
" try {\n" +
" result.value = " + functionExpression + "(" + encodedArguments + ")\n" +
" } catch (error) {\n" +
" result.error = error.toString()\n" +
" result.stack = error.stack\n" +
" }\n" +
" return result\n" +
"})({})"
}
private func encodeJavaScriptArguments(_ arguments: [AnyObject?]) -> String? {
let arguments = arguments.map { $0 == nil ? NSNull() : $0! }
if let data = try? JSONSerialization.data(withJSONObject: arguments, options: []),
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? {
let startIndex = string.index(after: string.startIndex)
let endIndex = string.index(before: string.endIndex)
return String(string[startIndex..<endIndex])
}
return nil
}
}
extension WebView: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let message = ScriptMessage.parse(message) else { return }
switch message.name {
case .PageLoaded:
pageLoadDelegate?.webView(self, didLoadPageWithRestorationIdentifier: message.restorationIdentifier!)
case .PageInvalidated:
delegate?.webViewDidInvalidatePage(self)
case .VisitProposed:
delegate?.webView(self, didProposeVisitToLocation: message.location!, withAction: message.action!)
case .VisitStarted:
visitDelegate?.webView(self, didStartVisitWithIdentifier: message.identifier!, hasCachedSnapshot: message.data["hasCachedSnapshot"] as! Bool)
case .VisitRequestStarted:
visitDelegate?.webView(self, didStartRequestForVisitWithIdentifier: message.identifier!)
case .VisitRequestCompleted:
visitDelegate?.webView(self, didCompleteRequestForVisitWithIdentifier: message.identifier!)
case .VisitRequestFailed:
visitDelegate?.webView(self, didFailRequestForVisitWithIdentifier: message.identifier!, statusCode: message.data["statusCode"] as! Int)
case .VisitRequestFinished:
visitDelegate?.webView(self, didFinishRequestForVisitWithIdentifier: message.identifier!)
case .VisitRendered:
visitDelegate?.webView(self, didRenderForVisitWithIdentifier: message.identifier!)
case .VisitCompleted:
visitDelegate?.webView(self, didCompleteVisitWithIdentifier: message.identifier!, restorationIdentifier: message.restorationIdentifier!)
case .ErrorRaised:
let error = message.data["error"] as? String
NSLog("JavaScript error: %@", error ?? "<unknown error>")
}
}
}
| mit | a777db73d5ac3b5ba133fb200353b57b | 50.026144 | 240 | 0.699885 | 5.271438 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/ios/NetworkRequest/CLDFetchImageRequestImpl.swift | 1 | 5535 | //
// CLDFetchImageRequestImpl.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
internal class CLDFetchImageRequestImpl: CLDFetchImageRequest {
fileprivate let url: String
fileprivate let downloadCoordinator: CLDDownloadCoordinator
fileprivate let closureQueue: OperationQueue
fileprivate var image: UIImage?
fileprivate var error: NSError?
// Requests
fileprivate var imageDownloadRequest: CLDNetworkDownloadRequest?
fileprivate var progress: ((Progress) -> Void)?
init(url: String, downloadCoordinator: CLDDownloadCoordinator) {
self.url = url
self.downloadCoordinator = downloadCoordinator
closureQueue = {
let operationQueue = OperationQueue()
operationQueue.name = "com.cloudinary.CLDFetchImageRequest"
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
return operationQueue
}()
}
// MARK: - Actions
func fetchImage() {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
if self.downloadCoordinator.imageCache.hasCachedImageForKey(self.url) {
self.downloadCoordinator.imageCache.getImageForKey(self.url, completion: { [weak self] (image) -> () in
if let fetchedImage = image {
self?.image = fetchedImage
self?.closureQueue.isSuspended = false
}
else {
self?.downloadImageAndCacheIt()
}
})
}
else {
self.downloadImageAndCacheIt()
}
}
}
// MARK: Private
fileprivate func downloadImageAndCacheIt() {
imageDownloadRequest = downloadCoordinator.download(url) as? CLDNetworkDownloadRequest
imageDownloadRequest?.progress(progress)
imageDownloadRequest?.responseData { [weak self] (responseData, responseError, httpCode) -> () in
if let data = responseData, !data.isEmpty {
if let
image = data.cldToUIImageThreadSafe(),
let url = self?.url {
self?.image = image
self?.downloadCoordinator.imageCache.cacheImage(image, data: data, key: url, completion: nil)
}
else {
let error = CLDError.error(code: .failedCreatingImageFromData, message: "Failed creating an image from the received data.", userInfo: ["statusCode": httpCode])
self?.error = error
}
}
else if let err = responseError {
self?.error = err
}
else {
let error = CLDError.error(code: .failedDownloadingImage, message: "Failed attempting to download image.", userInfo: ["statusCode": httpCode])
self?.error = error
}
self?.closureQueue.isSuspended = false
}
}
// MARK: - CLDFetchImageRequest
@discardableResult
@objc func responseImage(_ completionHandler: CLDCompletionHandler?) -> CLDFetchImageRequest {
closureQueue.addOperation {
if let image = self.image {
completionHandler?(image, nil)
}
else if let error = self.error {
completionHandler?(nil, error)
}
else {
completionHandler?(nil, CLDError.generalError())
}
}
return self
}
@discardableResult
@objc func progress(_ progress: ((Progress) -> Void)?) -> CLDNetworkDataRequest {
if let downloadRequest = self.imageDownloadRequest {
downloadRequest.progress(progress)
}
else {
self.progress = progress
}
return self
}
@objc func resume() {
imageDownloadRequest?.resume()
}
@objc func suspend() {
imageDownloadRequest?.suspend()
}
@objc func cancel() {
imageDownloadRequest?.cancel()
}
@objc func response(_ completionHandler: ((_ response: Any?, _ error: NSError?) -> ())?) -> CLDNetworkRequest {
responseImage(completionHandler)
return self
}
}
| mit | d4f0b86c4cbcdcacffea938ba8b5ab88 | 35.176471 | 179 | 0.605781 | 5.4 | false | false | false | false |
reproto/reproto | it/structures/swift/code-codable/Test.swift | 1 | 1984 | public struct Test_Entry: Codable {}
public struct Test_Type: Codable {}
public enum Test_Interface {
case SubType(Test_Interface_SubType)
enum CodingKeys: String, CodingKey {
case tag = "type"
}
}
extension Test_Interface: Decodable {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
switch try values.decode(String.self, forKey: .tag) {
case "SubType":
self = try .SubType(Test_Interface_SubType(from: decoder))
default:
let context = DecodingError.Context(codingPath: [], debugDescription: "type")
throw DecodingError.dataCorrupted(context)
}
}
}
extension Test_Interface: Encodable {
public func encode(to encoder: Encoder) throws {
var values = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .SubType(let d):
try values.encode("SubType", forKey: .tag)
try d.encode(to: encoder)
}
}
}
public struct Test_Interface_SubType: Codable {}
public enum Test_Enum {
case Variant
}
extension Test_Enum: Decodable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
switch try value.decode(String.self) {
case "Variant":
self = .Variant
default:
let context = DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "enum variant"
)
throw DecodingError.dataCorrupted(context)
}
}
}
extension Test_Enum: Encodable {
public func encode(to encoder: Encoder) throws {
var value = encoder.singleValueContainer()
switch self {
case .Variant:
try value.encode("Variant")
}
}
}
public struct Test_Tuple {}
extension Test_Tuple: Decodable {
public init(from decoder: Decoder) throws {
var values = try decoder.unkeyedContainer()
}
}
extension Test_Tuple: Encodable {
public func encode(to encoder: Encoder) throws {
var values = encoder.unkeyedContainer()
}
}
| apache-2.0 | 5bca432ddde64760236dafe63fa2bb88 | 22.069767 | 83 | 0.683468 | 4.10766 | false | true | false | false |
codefellows/sea-d34-iOS | Sample Code/Week 2/ImageFilters/ImageFilters/ParseService.swift | 1 | 688 | //
// ParseService.swift
// ImageFilters
//
// Created by Bradley Johnson on 4/7/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import Foundation
class ParseService {
class func uploadImage(originalImage : UIImage, size : CGSize, completionHandler : (String?) -> Void) {
let resizedImage = ImageResizer.resizeImage(originalImage, size: size)
let imageData = UIImageJPEGRepresentation(resizedImage, 1.0)
let imageFile = PFFile(name: "post.jpg", data: imageData)
let post = PFObject(className: "Post")
post["image"] = imageFile
post.saveInBackgroundWithBlock({ (finished, error) -> Void in
completionHandler(nil)
})
}
}
| mit | 0ff45a99a9d2c821612dbf1785c7ba0f | 25.461538 | 105 | 0.680233 | 4.195122 | false | false | false | false |
wangweicheng7/ClouldFisher | CloudFisher/AppDelegate.swift | 1 | 4590 | //
// AppDelegate.swift
// CloudFisher
//
// Created by weicheng wang on 2016/12/26.
// Copyright © 2016年 weicheng wang. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// registerNotificationCategory()
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (result, error) in
if result {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
})
} else {
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
UIApplication.shared.applicationIconBadgeNumber = 0
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if deviceToken.count == 0 {
return
}
print("\(deviceToken)")
let str = deviceToken.hexString
PWRequest.request(with: Api.device_token, parameter: ["device_token": str], to: "") { (result, success, code) in
if !success {
print("device_token 上传失败")
}
}
print(str)
}
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
print(notification.alertBody ?? "")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error)
}
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.
UIApplication.shared.applicationIconBadgeNumber = 0
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response)
completionHandler()
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
}
| mit | e62e5cda86a00c7ffa4c7ec33ae05ed3 | 40.252252 | 285 | 0.685739 | 5.916021 | false | false | false | false |
brentdax/swift | test/SILOptimizer/definite-init-convert-to-escape.swift | 1 | 3593 | // RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership -Xllvm -sil-disable-convert-escape-to-noescape-switch-peephole %s | %FileCheck %s --check-prefix=NOPEEPHOLE
// REQUIRES: objc_interop
import Foundation
// Make sure that we keep the escaping closures alive accross the ultimate call.
// CHECK-LABEL: sil @$s1A19bridgeNoescapeBlock5optFn0D3Fn2yySSSgcSg_AFtF
// CHECK: bb0
// CHECK: retain_value %0
// CHECK: retain_value %0
// CHECK: bb2
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb6
// CHECK: retain_value %1
// CHECK: retain_value %1
// CHECK: bb8
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb12
// CHECK: [[F:%.*]] = function_ref @noescapeBlock3
// CHECK: apply [[F]]
// CHECK: release_value {{.*}} : $Optional<NSString>
// CHECK: release_value %1 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) -> ()>
// CHECK: release_value %0 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>)
public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) {
noescapeBlock3(optFn, optFn2, "Foobar")
}
@_silgen_name("_returnOptionalEscape")
public func returnOptionalEscape() -> (() ->())?
// Make sure that we keep the escaping closure alive accross the ultimate call.
// CHECK-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[V0:%.*]] = function_ref @_returnOptionalEscape
// CHECK: [[V1:%.*]] = apply [[V0]]
// CHECK: retain_value [[V1]]
// CHECK: switch_enum {{.*}}bb2
// CHECK: bb2([[V2:%.*]]: $@callee_guaranteed () -> ()):
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release [[V2]]
// CHECK: bb6({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// CHECK: [[F:%.*]] = function_ref @noescapeBlock
// CHECK: apply [[F]]({{.*}})
// CHECK: release_value [[V1]] : $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// NOPEEPHOLE: bb0:
// NOPEEPHOLE: alloc_stack $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE: [[SLOT:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE: [[NONE:%.*]] = enum $Optional
// NOPEEPHOLE: store [[NONE]] to [[SLOT]]
// NOPEEPHOLE: [[V0:%.*]] = function_ref @_returnOptionalEscape
// NOPEEPHOLE: [[V1:%.*]] = apply [[V0]]
// NOPEEPHOLE: switch_enum {{.*}}bb2
// NOPEEPHOLE: bb2([[V2:%.*]]: $@callee_guaranteed () -> ()):
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: [[SOME:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[V2]]
// NOPEEPHOLE: store [[SOME]] to [[SLOT]]
// NOPEEPHOLE: convert_escape_to_noescape %
// NOPEEPHOLE-NOT: strong_release
// NOPEEPHOLE: br
// NOPEEPHOLE: bb6({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// NOPEEPHOLE: [[F:%.*]] = function_ref @noescapeBlock
// NOPEEPHOLE: apply [[F]]({{.*}})
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: dealloc_stack [[SLOT]]
public func bridgeNoescapeBlock() {
noescapeBlock(returnOptionalEscape())
}
| apache-2.0 | db2bd872b1a30379c1ad33e2ffee72f8 | 44.481013 | 279 | 0.650431 | 3.185284 | false | false | false | false |
mateuszmackowiak/MMLogger | MMLogger/Classes/Core/MMLogger.swift | 1 | 5354 | //
// Created by Mateusz Mackowiak on 21.03.2017.
// Copyright (c) 2016 Mateusz Mackowiak. All rights reserved.
//
import Foundation
//https://github.com/apple/swift/blob/master/stdlib/public/core/StaticString.swift#L254
public extension StaticString {
var stringValue: String {
return withUTF8Buffer {
(buffer) in
return String._fromWellFormedCodeUnitSequence(UTF8.self, input: buffer)
}
}
}
@objc public class MMLogger: NSObject {
@objc public var level: MMLogLevel = .verbose
@objc public static let `default` = MMLogger()
private struct LoggerWrapper {
let logger: MMLoggerProtocol
let levels: [MMLogLevel]
init(_ logger: MMLoggerProtocol, levels: [MMLogLevel]) {
self.logger = logger
self.levels = levels
}
}
private var loggers: [LoggerWrapper] = []
/**
Adds logger to system
When call to log statement is made, iterates over each logger, and depending on registered levels decides if it should forward the message struct to the logger.
- Parameters:
- logger:
- level: level from which logger will respond to message
*/
public func addLogger(_ logger: MMLoggerProtocol, from level: MMLogLevel) {
var levels = MMLogLevel.allLevels
let index = max(levels.index(where: {$0 == level})!, 0)
levels = Array(levels.suffix(from: index))
addLogger(logger, for: levels)
}
/**
Adds logger to system
When call to log statement is made, iterates over each logger, and depending on registered level decides if it should forward the message struct to the logger.
- Parameters:
- logger:
- level: levels for which logger will respond to message
*/
public func addLogger(_ logger: MMLoggerProtocol, for levels: [MMLogLevel]) {
loggers.append(LoggerWrapper(logger, levels: levels))
}
/**
Removes all added loggers
*/
public func removeAllLoggers() {
loggers.removeAll()
}
/// Verbose message logs.
///
/// - Parameters:
/// - message: The message
/// - file: The name of the file in which it appears.
/// - function: The name of the declaration in which it appears.
/// - line: The line number on which it appears.
public func verbose(_ message: @autoclosure () -> String, file: StaticString = #file, function: String = #function, line: UInt = #line) {
log(.verbose, message: message(), file: file.stringValue, function: function, line: line)
}
/// Debug logs
///
/// - Parameters:
/// - message: The message
/// - file: The name of the file in which it appears.
/// - function: The name of the declaration in which it appears.
/// - line: The line number on which it appears.
public func debug(_ message: @autoclosure () -> String, file: StaticString = #file, function: String = #function, line: UInt = #line) {
log(.debug, message: message(), file: file.stringValue, function: function, line: line)
}
/// info / notice logs
///
/// - Parameters:
/// - message: The message
/// - file: The name of the file in which it appears.
/// - function: The name of the declaration in which it appears.
/// - line: The line number on which it appears.
public func info(_ message: @autoclosure () -> String, file: StaticString = #file, function: String = #function, line: UInt = #line) {
log(.info, message: message(), file: file.stringValue, function: function, line: line)
}
/// Warning logs
///
/// - Parameters:
/// - message: The message
/// - file: The name of the file in which it appears.
/// - function: The name of the declaration in which it appears.
/// - line: The line number on which it appears.
public func warning(_ message: @autoclosure () -> String, file: StaticString = #file, function: String = #function, line: UInt = #line) {
log(.warning, message: message(), file: file.stringValue, function: function, line: line)
}
/// Error logs
///
/// - Parameters:
/// - message: The message
/// - file: The name of the file in which it appears.
/// - function: The name of the declaration in which it appears.
/// - line: The line number on which it appears.
public func error(_ message: @autoclosure () -> String, file: StaticString = #file, function: String = #function, line: UInt = #line) {
log(.error, message: message(), file: file.stringValue, function: function, line: line)
}
@objc func log(_ level: MMLogLevel, message: String, file: String, function: String, line: UInt) {
if self.level == .off {
return
}
let url = NSURL(string: String(describing:file))
let fileName = url?.deletingPathExtension?.lastPathComponent ?? ""
let message = MMLogMessage(message: message, date: Date(), file: file, fileName: fileName, function: function, line: line, level: level, threadName: Thread.current.name)
for loggerWrapper in loggers {
if level.rawValue > self.level.rawValue || !loggerWrapper.levels.contains(level) {
return
}
loggerWrapper.logger.log(message: message)
}
}
}
| mit | 05c865e59e68e0ede4f1c2534dfb5c33 | 37.797101 | 177 | 0.626821 | 4.269537 | false | false | false | false |
edx/edx-app-ios | Test/FirebaseConfigTests.swift | 1 | 10896 | //
// FirebaseConfigTests.swift
// edXTests
//
// Created by Saeed Bashir on 8/28/18.
// Copyright © 2018 edX. All rights reserved.
//
import Foundation
@testable import edX
let apiKey = "APebSdWSu456EDkUk0imSGqetnOznbZv22QRiq1"
let clientID = "302611111829-s11900000000tdhcbj9876548888qur3.apps.googleusercontent.com"
let googleAppID = "3:902600000000:ios:c00089xx00000266"
let gcmSenderID = "303600005829"
class FirebaseConfigTests: XCTestCase {
func testNoFirebaseConfig() {
let config = OEXConfig(dictionary:[:])
XCTAssertFalse(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceSegment)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertEqual(config.firebaseConfig.analyticsSource, AnalyticsSource.none)
}
func testEmptyFirebaseConfig() {
let config = OEXConfig(dictionary:["FIREBASE":[:]])
XCTAssertFalse(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceSegment)
XCTAssertEqual(config.firebaseConfig.analyticsSource, AnalyticsSource.none)
}
func testFirebaseConfig() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"ANALYTICS_ENABLED": true,
"ANALYTICS_SOURCE": "segment",
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertTrue(config.firebaseConfig.isAnalyticsSourceSegment)
}
func testFirebaseDisableConfig() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": false,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertFalse(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseDisableAnalytics() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseDisableCloudMessaging() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": false,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseAPIKey() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertEqual(config.firebaseConfig.apiKey, apiKey)
}
func testFirebaseClientID() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertEqual(config.firebaseConfig.cliendID, clientID)
}
func testFirebaseGoogleAppID() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertEqual(config.firebaseConfig.googleAppID, googleAppID)
}
func testFirebaseGCMSenderID() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
XCTAssertEqual(config.firebaseConfig.gcmSenderID, gcmSenderID)
}
func testFirebaseRequiredKeysAvailable() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.firebaseConfig.requiredKeysAvailable)
XCTAssertTrue(config.firebaseConfig.enabled)
XCTAssertTrue(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseRequiredKeysNotAvailable() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": false,
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.firebaseConfig.requiredKeysAvailable)
XCTAssertFalse(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseRequiredKeyMissing() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.firebaseConfig.requiredKeysAvailable)
XCTAssertFalse(config.firebaseConfig.enabled)
XCTAssertFalse(config.firebaseConfig.cloudMessagingEnabled)
}
func testFirebaseDisableIfSegmentEnable() {
let configDictionary = [
"FIREBASE" : [
"ENABLED": true,
"CLOUD_MESSAGING_ENABLED": true,
"API_KEY" : apiKey,
"CLIENT_ID" : clientID,
"GOOGLE_APP_ID" : googleAppID,
"GCM_SENDER_ID" : gcmSenderID
],
"SEGMENT_IO": [
"ENABLED": true,
"SEGMENT_IO_WRITE_KEY": "p910192UHD101010nY0000001Kb00GFcz'"
]
]
let config = OEXConfig(dictionary: configDictionary)
let firebaseEnable = config.firebaseConfig.enabled && !(config.segmentConfig?.isEnabled ?? false)
XCTAssertTrue(config.segmentConfig?.isEnabled ?? false)
XCTAssertFalse(firebaseEnable)
}
func testAnalyticsSourceNoneConfig() {
let configDictionary = [
"FIREBASE" : [
"ANALYTICS_SOURCE": "none",
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceSegment)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertEqual(config.firebaseConfig.analyticsSource, AnalyticsSource.none)
}
func testAnalyticsSourceSegmentConfig() {
let configDictionary = [
"FIREBASE" : [
"ANALYTICS_SOURCE": "segment",
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertTrue(config.firebaseConfig.isAnalyticsSourceSegment)
XCTAssertEqual(config.firebaseConfig.analyticsSource, AnalyticsSource.segment)
}
func testAnalyticsSourceFirebaseConfig() {
let configDictionary = [
"FIREBASE" : [
"ANALYTICS_SOURCE": "firebase",
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.firebaseConfig.isAnalyticsSourceSegment)
XCTAssertTrue(config.firebaseConfig.isAnalyticsSourceFirebase)
XCTAssertEqual(config.firebaseConfig.analyticsSource, AnalyticsSource.firebase)
}
}
| apache-2.0 | 503c721663a7e24ba8793da0f7d2d36c | 35.076159 | 105 | 0.607067 | 4.822931 | false | true | false | false |
josephkhawly/AKPickerView-Swift | AKPickerViewSample/ViewController.swift | 2 | 2467 | //
// ViewController.swift
// AKPickerViewSample
//
// Created by Akio Yasui on 2/10/15.
// Copyright (c) 2015 Akio Yasui. All rights reserved.
//
import UIKit
class ViewController: UIViewController, AKPickerViewDataSource, AKPickerViewDelegate {
@IBOutlet var pickerView: AKPickerView!
let titles = ["Tokyo", "Kanagawa", "Osaka", "Aichi", "Saitama", "Chiba", "Hyogo", "Hokkaido", "Fukuoka", "Shizuoka"]
override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.delegate = self
self.pickerView.dataSource = self
self.pickerView.font = UIFont(name: "HelveticaNeue-Light", size: 20)!
self.pickerView.highlightedFont = UIFont(name: "HelveticaNeue", size: 20)!
self.pickerView.pickerViewStyle = .Wheel
self.pickerView.maskDisabled = false
self.pickerView.reloadData()
}
// MARK: - AKPickerViewDataSource
func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int {
return self.titles.count
}
/*
Image Support
-------------
Please comment '-pickerView:titleForItem:' entirely and
uncomment '-pickerView:imageForItem:' to see how it works.
*/
func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String {
return self.titles[item]
}
func pickerView(pickerView: AKPickerView, imageForItem item: Int) -> UIImage {
return UIImage(named: self.titles[item])!
}
// MARK: - AKPickerViewDelegate
func pickerView(pickerView: AKPickerView, didSelectItem item: Int) {
println("Your favorite city is \(self.titles[item])")
}
/*
Label Customization
-------------------
You can customize labels by their any properties (except for fonts,)
and margin around text.
These methods are optional, and ignored when using images.
*/
/*
func pickerView(pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int) {
label.textColor = UIColor.lightGrayColor()
label.highlightedTextColor = UIColor.whiteColor()
label.backgroundColor = UIColor(
hue: CGFloat(item) / CGFloat(self.titles.count),
saturation: 1.0,
brightness: 0.5,
alpha: 1.0)
}
func pickerView(pickerView: AKPickerView, marginForItem item: Int) -> CGSize {
return CGSizeMake(40, 20)
}
*/
/*
UIScrollViewDelegate Support
----------------------------
AKPickerViewDelegate inherits UIScrollViewDelegate.
You can use UIScrollViewDelegate methods
by simply setting pickerView's delegate.
*/
func scrollViewDidScroll(scrollView: UIScrollView) {
// println("\(scrollView.contentOffset.x)")
}
}
| mit | 8e81541aee8f065986aacfcc014422b7 | 24.43299 | 117 | 0.719903 | 3.789555 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Models/AccessControlLevel.swift | 1 | 2498 | /// The accessibility of a Swift source declaration.
///
/// - SeeAlso: https://github.com/apple/swift/blob/main/docs/AccessControl.md
public enum AccessControlLevel: String, CustomStringConvertible {
/// Accessible by the declaration's immediate lexical scope.
case `private` = "source.lang.swift.accessibility.private"
/// Accessible by the declaration's same file.
case `fileprivate` = "source.lang.swift.accessibility.fileprivate"
/// Accessible by the declaration's same module, or modules importing it with the `@testable` attribute.
case `internal` = "source.lang.swift.accessibility.internal"
/// Accessible by the declaration's same program.
case `public` = "source.lang.swift.accessibility.public"
/// Accessible and customizable (via subclassing or overrides) by the declaration's same program.
case `open` = "source.lang.swift.accessibility.open"
/// Initializes an access control level by its Swift source keyword value.
///
/// - parameter value: The value used to describe this level in Swift source code.
internal init?(description value: String) {
switch value {
case "private": self = .private
case "fileprivate": self = .fileprivate
case "internal": self = .internal
case "public": self = .public
case "open": self = .open
default: return nil
}
}
/// Initializes an access control level by its SourceKit unique identifier.
///
/// - parameter value: The value used by SourceKit to refer to this access control level.
internal init?(identifier value: String) {
self.init(rawValue: value)
}
public var description: String {
switch self {
case .private: return "private"
case .fileprivate: return "fileprivate"
case .internal: return "internal"
case .public: return "public"
case .open: return "open"
}
}
/// Returns true if is `private` or `fileprivate`
var isPrivate: Bool {
return self == .private || self == .fileprivate
}
}
extension AccessControlLevel: Comparable {
private var priority: Int {
switch self {
case .private: return 1
case .fileprivate: return 2
case .internal: return 3
case .public: return 4
case .open: return 5
}
}
public static func < (lhs: AccessControlLevel, rhs: AccessControlLevel) -> Bool {
return lhs.priority < rhs.priority
}
}
| mit | 50031bcc3e5227046f9d3102845d27cc | 36.283582 | 108 | 0.654524 | 4.608856 | false | false | false | false |
DarrenKong/firefox-ios | XCUITests/ToolbarTest.swift | 1 | 3854 | /* 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 XCTest
let website1: [String: String] = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"]
let website2 = "example.com"
class ToolbarTests: BaseTestCase {
override func setUp() {
super.setUp()
XCUIDevice.shared().orientation = UIDeviceOrientation.landscapeLeft
}
override func tearDown() {
XCUIDevice.shared().orientation = UIDeviceOrientation.portrait
super.tearDown()
}
/**
* Tests landscape page navigation enablement with the URL bar with tab switching.
*/
func testLandscapeNavigationWithTabSwitch() {
let urlPlaceholder = "Search or enter address"
XCTAssert(app.textFields["url"].exists)
let defaultValuePlaceholder = app.textFields["url"].placeholderValue!
// Check the url placeholder text and that the back and forward buttons are disabled
XCTAssertTrue(urlPlaceholder == defaultValuePlaceholder, "The placeholder does not show the correct value")
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
XCTAssertFalse(app.buttons["Reload"].isEnabled)
// Navigate to two pages and press back once so that all buttons are enabled in landscape mode.
navigator.openURL(website1["url"]!)
waitForValueContains(app.textFields["url"], value: website1["value"]!)
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
XCTAssertTrue(app.buttons["Reload"].isEnabled)
navigator.openURL(website2)
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: website2)
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
app.buttons["URLBarView.backButton"].tap()
waitForValueContains(app.textFields["url"], value: website1["value"]!)
waitUntilPageLoad()
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertTrue(app.buttons["Forward"].isEnabled)
// Open new tab and then go back to previous tab to test navigation buttons.
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[website1["label"]!])
app.collectionViews.cells[website1["label"]!].tap()
waitForValueContains(app.textFields["url"], value: website1["value"]!)
// Test to see if all the buttons are enabled then close tab.
waitUntilPageLoad()
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertTrue(app.buttons["Forward"].isEnabled)
navigator.nowAt(BrowserTab)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[website1["label"]!])
app.collectionViews.cells[website1["label"]!].swipeRight()
// Go Back to other tab to see if all buttons are disabled.
navigator.nowAt(BrowserTab)
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
}
func testClearURLTextUsingBackspace() {
navigator.openURL(website1["url"]!)
waitForValueContains(app.textFields["url"], value: website1["value"]!)
// Simulate pressing on backspace key should remove the text
app.textFields["url"].tap()
app.textFields["address"].typeText("\u{8}")
let value = app.textFields["address"].value
XCTAssertEqual(value as? String, "", "The url has not been removed correctly")
}
}
| mpl-2.0 | a7b9c977f71e484f4234b4e9d991502d | 42.280899 | 137 | 0.686397 | 4.900763 | false | true | false | false |
danielallsopp/Charts | Source/Charts/Renderers/ChartXAxisRendererRadarChart.swift | 15 | 2981 | //
// ChartXAxisRendererRadarChart.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/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartXAxisRendererRadarChart: ChartXAxisRenderer
{
public weak var chart: RadarChartView?
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil)
self.chart = chart
}
public override func renderAxisLabels(context context: CGContext)
{
guard let
xAxis = xAxis,
chart = chart
else { return }
if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled)
{
return
}
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
let drawLabelAnchor = CGPoint(x: 0.5, y: 0.0)
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let modulus = xAxis.axisLabelModulus
for i in 0.stride(to: xAxis.values.count, by: modulus)
{
let label = xAxis.values[i]
if (label == nil)
{
continue
}
let angle = (sliceangle * CGFloat(i) + chart.rotationAngle) % 360.0
let p = ChartUtils.getPosition(center: center, dist: CGFloat(chart.yRange) * factor + xAxis.labelRotatedWidth / 2.0, angle: angle)
drawLabel(context: context, label: label!, xIndex: i, x: p.x, y: p.y - xAxis.labelRotatedHeight / 2.0, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: drawLabelAnchor, angleRadians: labelRotationAngleRadians)
}
}
public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat)
{
guard let xAxis = xAxis else { return }
let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label
ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians)
}
public override func renderLimitLines(context context: CGContext)
{
/// XAxis LimitLines on RadarChart not yet supported.
}
} | apache-2.0 | 1b7f62af9e95716873512b2289071dec | 33.275862 | 274 | 0.636699 | 4.968333 | false | false | false | false |
buscarini/JMSSwiftParse | Source/parse.swift | 1 | 49320 | //
// JMSSwiftParse.swift
// JMSSwiftParse
//
// Created by Jose Manuel Sánchez Peñarroja on 10/11/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
// MARK: Generic Parsers
/*
public func parse<T: Hashable,U: Hashable>(inout property: T, value: U,validate: (T)->Bool = { (val) in true }) -> Bool {
let converted : T? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable,U: Hashable>(inout property: T?, value: U,validate: (T)->Bool = { (val) in true }) -> Bool {
let converted : T? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable,U: Hashable>(inout property: T, value: U?,validate: (T)->Bool = { (val) in true }) -> Bool {
if let validValue : U = value {
return parse(&property, validValue, validate: validate)
}
return false
}
public func parse<T: Hashable,U: Hashable>(inout property: T?, value: U?,validate: (T)->Bool = { (val) in true }) -> Bool {
if let validValue : U = value {
return parse(&property, validValue, validate: validate)
}
return false
}
*/
/*
public func parse<T>(inout property: T, value: T,validate: (T)->Bool = { (val) in true }) -> Bool {
if validate(value) {
property = value
return true
}
return false
}
*/
// MARK: T <- NSNull
public func parse<T: Hashable>(inout property: T, value: NSNull) -> Bool {
return false
}
public func parse<T: Hashable>(inout property: T?, value: NSNull) -> Bool {
property = nil
return true
}
// MARK: T <-> T
public func parse<T: Hashable>(inout property: T, value: T?,validate: (T)->Bool) -> Bool {
if let valid = value {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable>(inout property: T?, value: T?,validate: (T)->Bool) -> Bool {
if let valid = value {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse<T: Hashable>(inout property: T, value: T?) -> Bool {
if let valid = value {
property = valid
return true
}
return false
}
public func parse<T: Hashable>(inout property: T?, value: T?) -> Bool {
if let valid = value {
property = valid
return true
}
return false
}
// MARK: Specific methods, required while they fix Swift bugs
// MARK: NSURL -> String
public func parse(inout property: String?, value: NSURL,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: NSURL) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: NSURL,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: NSURL) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: NSURL?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: NSURL?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: NSURL?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: NSURL?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String -> NSURL
public func parse(inout property: NSURL?, value: String,validate: (NSURL)->Bool) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL?, value: String) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL, value: String,validate: (NSURL)->Bool) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: String) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL?, value: String?,validate: (NSURL)->Bool) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL?, value: String?) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: String?,validate: (NSURL)->Bool) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL, value: String?) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSURL -> NSString
public func parse(inout property: NSString?, value: NSURL,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString?, value: NSURL) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString, value: NSURL,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: NSURL) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString?, value: NSURL?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString?, value: NSURL?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: NSURL?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString, value: NSURL?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSString -> NSURL
public func parse(inout property: NSURL?, value: NSString,validate: (NSURL)->Bool) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL?, value: NSString) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL, value: NSString,validate: (NSURL)->Bool) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: NSString) -> Bool {
let converted : NSURL? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSURL?, value: NSString?,validate: (NSURL)->Bool) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL?, value: NSString?) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSURL, value: NSString?,validate: (NSURL)->Bool) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSURL, value: NSString?) -> Bool {
if let validValue = value {
let converted : NSURL? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Bool -> NSNumber
public func parse(inout property: NSNumber?, value: Bool,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber?, value: Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber, value: Bool,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber?, value: Bool?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber?, value: Bool?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Bool?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber, value: Bool?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSNumber -> Bool
public func parse(inout property: Bool?, value: NSNumber,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool?, value: NSNumber) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool, value: NSNumber,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: NSNumber) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool?, value: NSNumber?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool?, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: NSNumber?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Bool -> String
public func parse(inout property: String?, value: Bool,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: Bool,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: Bool?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: Bool?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Bool?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: Bool?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String -> Bool
public func parse(inout property: Bool?, value: String,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool?, value: String) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool, value: String,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: String) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool?, value: String?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool?, value: String?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: String?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool, value: String?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Bool -> NSString
public func parse(inout property: NSString?, value: Bool,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString?, value: Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString, value: Bool,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString?, value: Bool?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString?, value: Bool?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Bool?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString, value: Bool?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSString -> Bool
public func parse(inout property: Bool?, value: NSString,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool?, value: NSString) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool, value: NSString,validate: (Bool)->Bool) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: NSString) -> Bool {
let converted : Bool? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Bool?, value: NSString?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool?, value: NSString?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Bool, value: NSString?,validate: (Bool)->Bool) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Bool, value: NSString?) -> Bool {
if let validValue = value {
let converted : Bool? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Int -> NSNumber
public func parse(inout property: NSNumber?, value: Int,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber?, value: Int) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber, value: Int,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Int) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber?, value: Int?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber?, value: Int?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Int?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber, value: Int?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSNumber -> Int
public func parse(inout property: Int?, value: NSNumber,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int?, value: NSNumber) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int, value: NSNumber,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: NSNumber) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int?, value: NSNumber?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int?, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: NSNumber?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Int -> String
public func parse(inout property: String?, value: Int,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: Int) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: Int,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Int) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: Int?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: Int?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Int?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: Int?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String -> Int
public func parse(inout property: Int?, value: String,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int?, value: String) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int, value: String,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: String) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int?, value: String?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int?, value: String?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: String?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int, value: String?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Int -> NSString
public func parse(inout property: NSString?, value: Int,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString?, value: Int) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString, value: Int,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Int) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString?, value: Int?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString?, value: Int?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Int?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString, value: Int?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSString -> Int
public func parse(inout property: Int?, value: NSString,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int?, value: NSString) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int, value: NSString,validate: (Int)->Bool) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: NSString) -> Bool {
let converted : Int? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Int?, value: NSString?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int?, value: NSString?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Int, value: NSString?,validate: (Int)->Bool) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Int, value: NSString?) -> Bool {
if let validValue = value {
let converted : Int? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Double -> NSNumber
public func parse(inout property: NSNumber?, value: Double,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber?, value: Double) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber, value: Double,validate: (NSNumber)->Bool) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Double) -> Bool {
let converted : NSNumber? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSNumber?, value: Double?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber?, value: Double?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSNumber, value: Double?,validate: (NSNumber)->Bool) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSNumber, value: Double?) -> Bool {
if let validValue = value {
let converted : NSNumber? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSNumber -> Double
public func parse(inout property: Double?, value: NSNumber,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double?, value: NSNumber) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double, value: NSNumber,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: NSNumber) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double?, value: NSNumber?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double?, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: NSNumber?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double, value: NSNumber?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Double -> String
public func parse(inout property: String?, value: Double,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: Double) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: Double,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Double) -> Bool {
let converted : String? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: Double?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: Double?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: Double?,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: Double?) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String -> Double
public func parse(inout property: Double?, value: String,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double?, value: String) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double, value: String,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: String) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double?, value: String?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double?, value: String?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: String?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double, value: String?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: Double -> NSString
public func parse(inout property: NSString?, value: Double,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString?, value: Double) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString, value: Double,validate: (NSString)->Bool) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Double) -> Bool {
let converted : NSString? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSString?, value: Double?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString?, value: Double?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSString, value: Double?,validate: (NSString)->Bool) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSString, value: Double?) -> Bool {
if let validValue = value {
let converted : NSString? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSString -> Double
public func parse(inout property: Double?, value: NSString,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double?, value: NSString) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double, value: NSString,validate: (Double)->Bool) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: NSString) -> Bool {
let converted : Double? = convert(value)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: Double?, value: NSString?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double?, value: NSString?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: Double, value: NSString?,validate: (Double)->Bool) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: Double, value: NSString?) -> Bool {
if let validValue = value {
let converted : Double? = convert(validValue)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: NSDate -> String
public func parse(inout property: String?, value: NSDate,format: String,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String?, value: NSDate,format: String) -> Bool {
let converted : String? = convert(value,format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String, value: NSDate,format: String,validate: (String)->Bool) -> Bool {
let converted : String? = convert(value,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: NSDate,format: String) -> Bool {
let converted : String? = convert(value,format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: String?, value: NSDate?,format: String,validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String?, value: NSDate?,format: String) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue,format)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: String, value: NSDate?,format: String, validate: (String)->Bool) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: String, value: NSDate?,format: String) -> Bool {
if let validValue = value {
let converted : String? = convert(validValue,format)
if let valid = converted {
property = valid
return true
}
}
return false
}
// MARK: String -> NSDate
public func parse(inout property: NSDate?, value: String,format: String,validate: (NSDate)->Bool) -> Bool {
let converted : NSDate? = convert(value,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate?, value: String,format: String) -> Bool {
let converted : NSDate? = convert(value,format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSDate, value: String,format: String,validate: (NSDate)->Bool) -> Bool {
let converted : NSDate? = convert(value,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate, value: String,format: String) -> Bool {
let converted : NSDate? = convert(value,format)
if let valid = converted {
property = valid
return true
}
return false
}
public func parse(inout property: NSDate?, value: String?,format: String,validate: (NSDate)->Bool) -> Bool {
if let validValue = value {
let converted : NSDate? = convert(validValue,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSDate?, value: String?,format: String) -> Bool {
if let validValue = value {
let converted : NSDate? = convert(validValue,format)
if let valid = converted {
property = valid
return true
}
}
return false
}
public func parse(inout property: NSDate, value: String?,format: String,validate: (NSDate)->Bool) -> Bool {
if let validValue = value {
let converted : NSDate? = convert(validValue,format)
if let valid = converted {
if validate(valid) {
property = valid
return true
}
}
}
return false
}
public func parse(inout property: NSDate, value: String?,format: String) -> Bool {
if let validValue = value {
let converted : NSDate? = convert(validValue,format)
if let valid = converted {
property = valid
return true
}
}
return false
}
| mit | 0f09c173559e8cbe22febab7a506fafb | 20.610868 | 123 | 0.670452 | 3.3562 | false | false | false | false |
slavapestov/swift | validation-test/stdlib/CoreMediaOverlay.swift | 2 | 3089 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
import CoreMedia
var CMTimeTests = TestSuite("CMTime")
let t1 = CMTimeMake(1, 10)
let t2 = CMTimeMake(2, 10)
CMTimeTests.test("isValid") {
expectFalse(kCMTimeInvalid.isValid)
expectTrue(t1.isValid)
}
CMTimeTests.test("isPositiveInfinity") {
expectTrue(kCMTimePositiveInfinity.isPositiveInfinity)
expectFalse(t1.isPositiveInfinity)
}
CMTimeTests.test("isNegativeInfinity") {
expectTrue(kCMTimeNegativeInfinity.isNegativeInfinity)
expectFalse(t1.isNegativeInfinity)
}
CMTimeTests.test("isIndefinite") {
expectTrue(kCMTimeIndefinite.isIndefinite)
expectFalse(t1.isIndefinite)
}
CMTimeTests.test("isNumeric") {
expectFalse(kCMTimeInvalid.isNumeric)
expectFalse(kCMTimePositiveInfinity.isNumeric)
expectFalse(kCMTimeNegativeInfinity.isNumeric)
expectFalse(kCMTimeIndefinite.isNumeric)
expectTrue(t1.isNumeric)
expectFalse(t1.hasBeenRounded)
expectEqual(0.1, t1.seconds)
t1.convertScale(100, method: CMTimeRoundingMethod.Default)
var t1a = t1.convertScale(11, method: CMTimeRoundingMethod.Default)
expectTrue(t1a.hasBeenRounded)
}
CMTimeTests.test("operators") {
expectEqual(CMTimeMake(3, 10), t1 + t2)
expectEqual(CMTimeMake(1, 10), t2 - t1)
expectFalse(t1 < kCMTimeZero)
expectFalse(t1 == kCMTimeZero)
expectTrue(t1 > kCMTimeZero)
expectFalse(t1 <= kCMTimeZero)
expectTrue(t1 >= kCMTimeZero)
expectTrue(t1 != kCMTimeZero)
}
let r1 = CMTimeRangeMake(kCMTimeZero, CMTimeMake(1, 1))
let r2 = CMTimeRangeMake(kCMTimeZero, kCMTimeZero)
let r3 = CMTimeRangeMake(CMTimeMake(1, 1), CMTimeMake(3, 2))
var CMTimeRangeTests = TestSuite("CMTimeRange")
CMTimeRangeTests.test("isValid") {
expectTrue(r1.isValid)
expectTrue(r2.isValid)
expectTrue(r3.isValid)
expectFalse(kCMTimeRangeInvalid.isValid)
}
CMTimeRangeTests.test("isIndefinite") {
expectFalse(r1.isIndefinite)
expectFalse(r2.isIndefinite)
expectFalse(r3.isIndefinite)
}
CMTimeRangeTests.test("isEmpty") {
expectFalse(r1.isEmpty)
expectTrue(r2.isEmpty)
expectFalse(r3.isEmpty)
}
CMTimeRangeTests.test("start/end") {
expectEqual(CMTimeMake(1, 1), r3.start)
expectEqual(CMTimeMake(5, 2), r3.end)
}
CMTimeRangeTests.test("union") {
expectEqual(r1, r1.union(r2))
expectEqual(r2, r2.union(r2))
expectNotEqual(r3, r2.union(r3))
}
CMTimeRangeTests.test("intersection") {
expectEqual(r2, r1.intersection(r2))
expectEqual(r2, r1.intersection(r3))
}
CMTimeRangeTests.test("contains") {
expectTrue(r1.containsTimeRange(r2))
expectFalse(r2.containsTimeRange(r2))
expectFalse(r2.containsTimeRange(r1))
expectFalse(r3.containsTime(kCMTimeZero))
}
CMTimeRangeTests.test("operators") {
expectFalse(r1 == r2)
expectTrue(r1 != r2)
}
runAllTests()
| apache-2.0 | 440e2e25d0a9fab836138681fb96abc1 | 23.322835 | 73 | 0.76562 | 3.478604 | false | true | false | false |
coderwhy/HYLabel | HYLabelDemoOC/HYLabelDemoOC/Source/HYLabel.swift | 2 | 10580 | //
// HYLabel.swift
// HYLabel
//
// Created by apple on 16/3/8.
// Copyright © 2016年 xiaomage. All rights reserved.
//
import UIKit
enum TapHandlerType : Int {
case noneHandle = 0
case userHandle = 1
case topicHandle = 2
case linkHandle = 3
}
public class HYLabel: UILabel {
// MARK:- 属性
// 重写系统的属性
override public var text : String? {
didSet {
prepareText()
}
}
override public var attributedText: NSAttributedString? {
didSet {
prepareText()
}
}
override public var font: UIFont! {
didSet {
prepareText()
}
}
override public var textColor: UIColor! {
didSet {
prepareText()
}
}
// 懒加载属性
private lazy var textStorage : NSTextStorage = NSTextStorage() // NSMutableAttributeString的子类
private lazy var layoutManager : NSLayoutManager = NSLayoutManager() // 布局管理者
private lazy var textContainer : NSTextContainer = NSTextContainer() // 容器,需要设置容器的大小
// 用于记录下标值
private lazy var linkRanges : [NSRange] = [NSRange]()
private lazy var userRanges : [NSRange] = [NSRange]()
private lazy var topicRanges : [NSRange] = [NSRange]()
// 用于记录用户选中的range
private var selectedRange : NSRange?
// 用户记录点击还是松开
private var isSelected : Bool = false
// 闭包属性,用于回调
private var tapHandlerType : TapHandlerType = TapHandlerType.noneHandle
public typealias HYTapHandler = (HYLabel, String, NSRange) -> Void
public var linkTapHandler : HYTapHandler?
public var topicTapHandler : HYTapHandler?
public var userTapHandler : HYTapHandler?
// MARK:- 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
prepareTextSystem()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareTextSystem()
}
// MARK:- 布局子控件
override public func layoutSubviews() {
super.layoutSubviews()
// 设置容器的大小为Label的尺寸
textContainer.size = frame.size
}
// MARK:- 重写drawTextInRect方法
override public func drawTextInRect(rect: CGRect) {
// 1.绘制背景
if selectedRange != nil {
// 2.0.确定颜色
let selectedColor = isSelected ? UIColor(white: 0.7, alpha: 0.2) : UIColor.clearColor()
// 2.1.设置颜色
textStorage.addAttribute(NSBackgroundColorAttributeName, value: selectedColor, range: selectedRange!)
// 2.2.绘制背景
layoutManager.drawBackgroundForGlyphRange(selectedRange!, atPoint: CGPoint(x: 0, y: 0))
}
// 2.绘制字形
// 需要绘制的范围
let range = NSRange(location: 0, length: textStorage.length)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero)
}
}
extension HYLabel {
/// 准备文本系统
private func prepareTextSystem() {
// 0.准备文本
prepareText()
// 1.将布局添加到storeage中
textStorage.addLayoutManager(layoutManager)
// 2.将容器添加到布局中
layoutManager.addTextContainer(textContainer)
// 3.让label可以和用户交互
userInteractionEnabled = true
// 4.设置间距为0
textContainer.lineFragmentPadding = 0
}
/// 准备文本
private func prepareText() {
// 1.准备字符串
var attrString : NSAttributedString?
if attributedText != nil {
attrString = attributedText
} else if text != nil {
attrString = NSAttributedString(string: text!)
} else {
attrString = NSAttributedString(string: "")
}
selectedRange = nil
// 2.设置换行模型
let attrStringM = addLineBreak(attrString!)
attrStringM.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: attrStringM.length))
// 3.设置textStorage的内容
textStorage.setAttributedString(attrStringM)
// 4.匹配URL
if let linkRanges = getLinkRanges() {
self.linkRanges = linkRanges
for range in linkRanges {
textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range)
}
}
// 5.匹配@用户
if let userRanges = getRanges("@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*") {
self.userRanges = userRanges
for range in userRanges {
textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range)
}
}
// 6.匹配话题##
if let topicRanges = getRanges("#.*?#") {
self.topicRanges = topicRanges
for range in topicRanges {
textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range)
}
}
setNeedsDisplay()
}
}
// MARK:- 字符串匹配封装
extension HYLabel {
private func getRanges(pattern : String) -> [NSRange]? {
// 创建正则表达式对象
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
return getRangesFromResult(regex)
}
private func getLinkRanges() -> [NSRange]? {
// 创建正则表达式
guard let detector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else {
return nil
}
return getRangesFromResult(detector)
}
private func getRangesFromResult(regex : NSRegularExpression) -> [NSRange] {
// 1.匹配结果
let results = regex.matchesInString(textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
// 2.遍历结果
var ranges = [NSRange]()
for res in results {
ranges.append(res.range)
}
return ranges
}
}
// MARK:- 点击交互的封装
extension HYLabel {
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 0.记录点击
isSelected = true
// 1.获取用户点击的点
let selectedPoint = touches.first!.locationInView(self)
// 2.获取该点所在的字符串的range
selectedRange = getSelectRange(selectedPoint)
// 3.是否处理了事件
if selectedRange == nil {
super.touchesBegan(touches, withEvent: event)
}
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if selectedRange == nil {
super.touchesBegan(touches, withEvent: event)
return
}
// 0.记录松开
isSelected = false
// 2.重新绘制
setNeedsDisplay()
// 3.取出内容
let contentText = (textStorage.string as NSString).substringWithRange(selectedRange!)
// 3.回调
switch tapHandlerType {
case .linkHandle:
if linkTapHandler != nil {
linkTapHandler!(self, contentText, selectedRange!)
}
case .topicHandle:
if topicTapHandler != nil {
topicTapHandler!(self, contentText, selectedRange!)
}
case .userHandle:
if userTapHandler != nil {
userTapHandler!(self, contentText, selectedRange!)
}
default:
break
}
}
private func getSelectRange(selectedPoint : CGPoint) -> NSRange? {
// 0.如果属性字符串为nil,则不需要判断
if textStorage.length == 0 {
return nil
}
// 1.获取选中点所在的下标值(index)
let index = layoutManager.glyphIndexForPoint(selectedPoint, inTextContainer: textContainer)
// 2.判断下标在什么内
// 2.1.判断是否是一个链接
for linkRange in linkRanges {
if index > linkRange.location && index < linkRange.location + linkRange.length {
setNeedsDisplay()
tapHandlerType = .linkHandle
return linkRange
}
}
// 2.2.判断是否是一个@用户
for userRange in userRanges {
if index > userRange.location && index < userRange.location + userRange.length {
setNeedsDisplay()
tapHandlerType = .userHandle
return userRange
}
}
// 2.3.判断是否是一个#话题#
for topicRange in topicRanges {
if index > topicRange.location && index < topicRange.location + topicRange.length {
setNeedsDisplay()
tapHandlerType = .topicHandle
return topicRange
}
}
return nil
}
}
// MARK:- 补充
extension HYLabel {
/// 如果用户没有设置lineBreak,则所有内容会绘制到同一行中,因此需要主动设置
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
let attrStringM = NSMutableAttributedString(attributedString: attrString)
if attrStringM.length == 0 {
return attrStringM
}
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range)
var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle
if paragraphStyle != nil {
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
} else {
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
attributes[NSParagraphStyleAttributeName] = paragraphStyle
attrStringM.setAttributes(attributes, range: range)
}
return attrStringM
}
}
| mit | 909fd9852b90b4c2b82f99f8914fcce4 | 28.249258 | 133 | 0.573197 | 5.070473 | false | false | false | false |
NougatFramework/Switchboard | Sources/Response.swift | 1 | 1713 | public protocol ResponseEncodable {
func asResponse() -> Response
}
public struct Response {
let statusCode: StatusCode
// TODO: This was [(String, String)], but it looks like built-in tuple comparison isn't in the snapshots yet.
// Change back to an array of tuples when the snapshots get tuple comparison.
var headers: [String: String]
// FIXME: Data instead?
let body: String
}
extension Response {
static func plainText(_ body: String, statusCode: StatusCode = .ok, headers: [String: String] = [:]) -> Response {
return make(body, contentType: "text/plain", statusCode: statusCode, headers: headers)
}
static func html(_ body: String, statusCode: StatusCode = .ok, headers: [String: String] = [:]) -> Response {
return make(body, contentType: "text/html", statusCode: statusCode, headers: headers)
}
fileprivate static func make(_ body: String, contentType: String, statusCode: StatusCode = .ok, headers: [String: String] = [:]) -> Response {
var responseHeaders = headers
responseHeaders["Content-Type"] = contentType
responseHeaders["Content-Length"] = "\(body.utf8.count)"
return self.init(statusCode: statusCode, headers: responseHeaders, body: body)
}
}
extension Response {
init(error: Error) {
self = type(of: self).plainText("\(error)", statusCode: .internalServerError)
}
}
extension Response: ResponseEncodable {
public func asResponse() -> Response {
return self
}
}
extension Response: Equatable {}
public func ==(lhs: Response, rhs: Response) -> Bool {
guard lhs.statusCode == rhs.statusCode else { return false }
guard lhs.headers == rhs.headers else { return false }
guard lhs.body == rhs.body else { return false }
return true
}
| mit | f81a3758468b73f6d7e28ed5fa3b3147 | 26.190476 | 143 | 0.706947 | 3.823661 | false | false | false | false |
summer-wu/WordPress-iOS | WordPress/Classes/Networking/PushAuthenticationServiceRemote.swift | 4 | 1738 | import Foundation
/**
* @class PushAuthenticationServiceRemote
* @brief The purpose of this class is to encapsulate all of the interaction with the REST endpoint,
* required to handle WordPress.com 2FA Code Veritication via Push Notifications
*/
@objc public class PushAuthenticationServiceRemote
{
/**
* @details Designated Initializer. Fails if the remoteApi is nil.
* @param remoteApi A Reference to the WordPressComApi that should be used to interact with WordPress.com
*/
public init?(remoteApi: WordPressComApi!) {
self.remoteApi = remoteApi
if remoteApi == nil {
return nil
}
}
/**
* @details Verifies a WordPress.com Login.
* @param token The token passed on by WordPress.com's 2FA Push Notification.
* @param success Closure to be executed on success. Can be nil.
* @param failure Closure to be executed on failure. Can be nil.
*/
public func authorizeLogin(token: String, success: (() -> ())?, failure: (() -> ())?) {
let path = "me/two-step/push-authentication"
let parameters = [
"action" : "authorize_login",
"push_token" : token
]
remoteApi.POST(path,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
success?()
},
failure:{ (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
failure?()
})
}
// MARK: - Private Internal Constants
private var remoteApi: WordPressComApi!
}
| gpl-2.0 | d17df257eee44943cc41c6c01df4aa2b | 33.76 | 115 | 0.581128 | 4.9375 | false | false | false | false |
WilliamDenniss/native-apps-ios-concept | SigninVC/AppDelegate.swift | 1 | 2925 | //
// AppDelegate.swift
// SigninVC
//
// Created by William Denniss on 6/26/15.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
}
func application(application: UIApplication,
continueUserActivity userActivity: NSUserActivity,
restorationHandler: ([AnyObject]?) -> Void) -> Bool
{
// checks for a Universal Link activity
if userActivity.activityType == NSUserActivityTypeBrowsingWeb
{
// gets URL the user loaded
let webURL = userActivity.webpageURL!
// sends to the root VC
let rootViewController = self.window!.rootViewController! as! MainViewController
rootViewController.universalLinkReceived(webURL)
}
return true;
}
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject) -> Bool
{
// sends to the root VC
let rootViewController = self.window!.rootViewController! as! MainViewController
rootViewController.customURIReceived(url)
return true
}
}
| apache-2.0 | ab9f2539d6f8fdb2369ca868fb0cb507 | 38.527027 | 281 | 0.754872 | 5.46729 | false | false | false | false |
stripe/stripe-ios | Tests/Tests/LinkLegalTermsViewSnapshotTests.swift | 1 | 2401 | //
// LinkLegalTermsViewSnapshotTests.swift
// StripeiOS Tests
//
// Created by Ramon Torres on 1/26/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
import iOSSnapshotTestCase
@testable@_spi(STP) import Stripe
@testable@_spi(STP) import StripeCore
@testable@_spi(STP) import StripePaymentSheet
@testable@_spi(STP) import StripePayments
@testable@_spi(STP) import StripePaymentsUI
@testable@_spi(STP) import StripeUICore
class LinkLegalTermsViewSnapshotTests: FBSnapshotTestCase {
override func setUp() {
super.setUp()
// recordMode = true
}
func testDefault() {
let sut = makeSUT()
verify(sut)
}
func testCentered() {
let sut = makeSUT(textAlignment: .center)
verify(sut)
}
func testColorCustomization() {
let sut = makeSUT()
sut.textColor = .orange
sut.tintColor = .purple
verify(sut)
}
func testLocalization() {
performLocalizedSnapshotTest(forLanguage: "de")
performLocalizedSnapshotTest(forLanguage: "es")
performLocalizedSnapshotTest(forLanguage: "el-GR")
performLocalizedSnapshotTest(forLanguage: "it")
performLocalizedSnapshotTest(forLanguage: "ja")
performLocalizedSnapshotTest(forLanguage: "ko")
performLocalizedSnapshotTest(forLanguage: "zh-Hans")
}
}
// MARK: - Helpers
extension LinkLegalTermsViewSnapshotTests {
func verify(
_ view: UIView,
identifier: String? = nil,
file: StaticString = #filePath,
line: UInt = #line
) {
view.autosizeHeight(width: 250)
STPSnapshotVerifyView(view, identifier: identifier, file: file, line: line)
}
func performLocalizedSnapshotTest(
forLanguage language: String,
file: StaticString = #filePath,
line: UInt = #line
) {
STPLocalizationUtils.overrideLanguage(to: language)
let sut = makeSUT()
STPLocalizationUtils.overrideLanguage(to: nil)
verify(sut, identifier: language, file: file, line: line)
}
}
// MARK: - Factory
extension LinkLegalTermsViewSnapshotTests {
func makeSUT() -> LinkLegalTermsView {
return LinkLegalTermsView()
}
func makeSUT(textAlignment: NSTextAlignment) -> LinkLegalTermsView {
return LinkLegalTermsView(textAlignment: textAlignment)
}
}
| mit | 3ad07639b9137c10b8879a6853222486 | 24.531915 | 83 | 0.664167 | 4.363636 | false | true | false | false |
dadederk/WeatherTV | Weather/Weather/Controllers/Weather/WorldWeather/WorldWeatherService.swift | 1 | 2082 | //
// WorldWeatherService.swift
// Weather
//
// Created by Daniel Devesa Derksen-Staats on 29/02/2016.
// Copyright © 2016 Desfici. All rights reserved.
//
import Foundation
struct WorldWeatherService : WeatherServiceProtocol {
private let baseUrl = "https://api.worldweatheronline.com/free/v2/weather.ashx"
private let apiKeyParameterName = "key"
private let cityNameParameterName = "q"
private let formatParameterName = "format"
enum Format: String {
case XML = "xml"
case JSON = "json"
}
func weatherForCititWithName(name: String,
country: String,
completionHandler: (weather: Weather?) -> ()) {
let apiKey = WeatherServiceConfiguration(serviceName: String(WorldWeatherService)).apiKey
let formattedName = name.stringByReplacingOccurrencesOfString(" ", withString: "+")
let formattedCountry = country.stringByReplacingOccurrencesOfString(" ", withString: "+")
let cityNameQueryItem = NSURLQueryItem(name: cityNameParameterName,
value: "\(formattedName),\(formattedCountry)")
let apiKeyQueryItem = NSURLQueryItem(name: apiKeyParameterName, value: apiKey)
let formatQueryItem = NSURLQueryItem(name: formatParameterName, value: Format.JSON.rawValue)
let queryItems = [cityNameQueryItem, apiKeyQueryItem, formatQueryItem]
let queryUrl = NSURLComponents(string: baseUrl)!
queryUrl.queryItems = queryItems
if let queryUrlString = queryUrl.URL?.absoluteString {
WeatherAPI.request(.GET, url:queryUrlString) { (result, error) in
if let json = result {
let weather = WorldWeatherParser.parseWeather(json)
completionHandler(weather: weather)
} else {
completionHandler(weather: nil)
}
}
} else {
completionHandler(weather: nil)
}
}
}
| apache-2.0 | 876ced1fa58dc30259c94be2b7ec9bf1 | 39.019231 | 100 | 0.61605 | 5.335897 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/Scenes/Login/JoinVC.swift | 1 | 3500 | //
// JoinVC.swift
// iOSStar
//
// Created by mu on 2017/6/22.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class JoinVC: UIViewController, UITextViewDelegate ,UIGestureRecognizerDelegate{
@IBOutlet weak var closeBtn: UIButton!
@IBOutlet weak var joinBtn: UIButton!
@IBOutlet weak var toalFieldText: UITextField!
@IBOutlet weak var middleFieldText: UITextField!
@IBOutlet weak var littleFieldText: UITextField!
@IBOutlet weak var joinScrollView: UIScrollView!
@IBOutlet weak var joinView: UIView!
@IBOutlet weak var joinBgView: UIView!
@IBOutlet weak var bgHeight: NSLayoutConstraint!
//定义block来判断选择哪个试图
var resultBlock: CompleteBlock?
override func viewDidLoad() {
super.viewDidLoad()
bgHeight.constant = 150 + UIScreen.main.bounds.size.height
}
@IBAction func joinXingXiang(_ sender: UIButton) {
if ShareDataModel.share().isweichaLogin == true && ShareDataModel.share().wechatUserInfo[SocketConst.Key.openid] != "" {
wxJoin()
}
else {
join()
}
}
//注册
func join() {
ShareDataModel.share().registerModel.memberId = toalFieldText.text!
ShareDataModel.share().registerModel.agentId = middleFieldText.text!
// ShareDataModel.share().registerModel.recommend = littleFieldText.text!
ShareDataModel.share().registerModel.sub_agentId = littleFieldText.text!
if checkTextFieldEmpty([toalFieldText,middleFieldText,littleFieldText]){
AppAPIHelper.login().regist(model: ShareDataModel.share().registerModel, complete: { [weak self](result) in
if let response = result {
if response["result"] as! Int == 1 {
SVProgressHUD.showSuccessMessage(SuccessMessage: "注册成功", ForDuration: 2.0, completion: {
self?.resultBlock!(doStateClick.doLogin as AnyObject)
})
}
}
}) { (error) in
SVProgressHUD.showErrorMessage(ErrorMessage: error.userInfo["NSLocalizedDescription"] as! String, ForDuration: 2.0, completion: nil)
}
}
}
//微信绑定
func wxJoin() {
ShareDataModel.share().wxregisterModel.memberId = toalFieldText.text!
ShareDataModel.share().wxregisterModel.agentId = middleFieldText.text!
// ShareDataModel.share().wxregisterModel.recommend = littleFieldText.text!
ShareDataModel.share().wxregisterModel.sub_agentId = toalFieldText.text!
AppAPIHelper.login().BindWeichat(model: ShareDataModel.share().wxregisterModel, complete: { (result) in
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.loginSuccessNotice), object: nil, userInfo: nil)
}) { (error ) in
SVProgressHUD.showErrorMessage(ErrorMessage: error.userInfo["NSLocalizedDescription"] as! String, ForDuration: 2.0, completion: nil)
}
}
//关闭
@IBAction func closeBtnTapped(_ sender: UIButton) {
let win : UIWindow = ((UIApplication.shared.delegate?.window)!)!
let tabar : BaseTabBarController = win.rootViewController as! BaseTabBarController
if tabar.selectedIndex == 1{
}else{
tabar.selectedIndex = 0
}
self.dismissController()
}
}
| gpl-3.0 | 91de9ec0abc48792143e277a237d3e64 | 38.215909 | 148 | 0.64619 | 4.695238 | false | false | false | false |
HotCocoaTouch/DeclarativeLayout | DeclarativeLayout/Classes/ViewLayoutComponent.swift | 1 | 14535 | import UIKit
enum LayoutComponentType {
case uiview(layout: UIViewLayoutComponentType)
case uistackview(layout: UIStackViewLayoutComponentType)
case layoutGuide(layout: LayoutGuideComponentType)
}
protocol ViewLayoutComponentType {
func allSubviews() -> [UIView]
func allArrangedSubviews() -> [UIView: UIStackViewLayoutComponentType]
func allConstraints() -> [LayoutConstraint]
func allLayoutGuides() -> [UILayoutGuide: UIView]
var subviews: [UIView] { get }
var sublayoutComponents: [LayoutComponentType] { get }
var layoutGuides: [UILayoutGuide] { get }
}
protocol LayoutGuideComponentType {
func allConstraints() -> [LayoutConstraint]
}
protocol UIViewLayoutComponentType: ViewLayoutComponentType {
var downcastedView: UIView { get }
}
protocol UIStackViewLayoutComponentType: ViewLayoutComponentType {
var downcastedView: UIStackView { get }
var arrangedSubviews: [UIView] { get }
var customSpacings: [(afterView: UIView, space: CGFloat)] { get }
}
public class ViewLayoutComponent<T: UIView>: ViewLayoutComponentType {
/**
The component's view.
*/
public final unowned let ownedView: T
let cachedLayoutObjectStore: CachedLayoutObjectStore
private(set) var subviews = [UIView]()
private(set) var sublayoutComponents = [LayoutComponentType]()
private(set) var layoutGuides = [UILayoutGuide]()
private var constraints = [LayoutConstraint]()
init(view: T, cachedLayoutObjectStore: CachedLayoutObjectStore) {
ownedView = view
self.cachedLayoutObjectStore = cachedLayoutObjectStore
}
/**
Add a subview to the component's view.
- parameters:
- identifier: An identifier to give for this view.
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
* This will just add a regular UIView (`UIView()`).
* Using an identifier will let you refer to the same
created instance of a `UIView` in subsequent layout updates.
*/
@discardableResult public func view(identifier: String,
layoutClosure: ((UIViewSubviewLayoutComponent<UIView, T>) -> Void)? = nil)
-> UIViewSubviewLayoutComponent<UIView, T> {
if let _view = cachedLayoutObjectStore.viewStorage[identifier] {
return view(_view, layoutClosure: layoutClosure)
} else {
let _view = UIView()
cachedLayoutObjectStore.viewStorage[identifier] = _view
return view(_view, layoutClosure: layoutClosure)
}
}
/**
Add a subview to the component's view.
- parameters:
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
* This will just add a regular UIView (`UIView()`).
* If you are calling `updateLayoutTo` more than once, you should not use this as it will cause
unnecessary layout recalculations to occur.
Consider using `view(identifier:layoutClosure:)` instead for that situation.
*/
@discardableResult public func view(layoutClosure: ((UIViewSubviewLayoutComponent<UIView, T>) -> Void)? = nil) -> UIViewSubviewLayoutComponent<UIView, T> {
return view(UIView(), layoutClosure: layoutClosure)
}
/**
Add a subview to the component's view.
- parameters:
- subview: The view you would like to add as a subview to the component's view.
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
*/
@discardableResult public func view<R>(_ subview: R,
layoutClosure: ((UIViewSubviewLayoutComponent<R, T>) -> Void)? = nil) -> UIViewSubviewLayoutComponent<R, T> {
subview.translatesAutoresizingMaskIntoConstraints = false
let subLayoutComponent = UIViewSubviewLayoutComponent(view: subview,
superview: ownedView,
cachedLayoutObjectStore: cachedLayoutObjectStore)
sublayoutComponents.append(.uiview(layout: subLayoutComponent))
subviews.append(subview)
layoutClosure?(subLayoutComponent)
return subLayoutComponent
}
/**
Add a subview, that is a stack view, to the component's view.
- parameters:
- identifier: An identifier to give for this view.
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
* This will just add a regular UIStackView (`UIStackView()`).
* Using an identifier will let you refer to the same created instance of a `UIStackView` in subsequent layout updates.
* This will allow you to, in the layout closure, add arranged views for the passed in stack view.
*/
@discardableResult public func stackView(identifier: String,
layoutClosure: ((UIStackViewSubviewLayoutComponent<UIStackView, T>)
-> Void)? = nil) -> UIStackViewSubviewLayoutComponent<UIStackView, T> {
if let view = cachedLayoutObjectStore.stackViewStorage[identifier] {
return stackView(view, layoutClosure: layoutClosure)
} else {
let view = UIStackView()
cachedLayoutObjectStore.stackViewStorage[identifier] = view
return stackView(view, layoutClosure: layoutClosure)
}
}
/**
Add a subview, that is a stack view, to the component's view.
- parameters:
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
* This will just add a regular UIStackView (`UIStackView()`).
* This will allow you to, in the layout closure, add arranged views for the passed in stack view.
* If you are calling `updateLayoutTo` more than once, you should not use this as it will cause
unnecessary layout recalculations to occur.
Consider using `addStackView(identifier:layoutClosure:)` instead for that situation.
*/
@discardableResult public func stackView(layoutClosure: ((UIStackViewSubviewLayoutComponent<UIStackView, T>) -> Void)? = nil) -> UIStackViewSubviewLayoutComponent<UIStackView, T> {
return stackView(UIStackView(), layoutClosure: layoutClosure)
}
/**
Add a subview, that is a stack view, to the component's view.
- parameters:
- subview: The view you would like to add as a subview to the component's view.
- layoutClosure: A closure that will define the layout component for the subview.
- returns: The layout component for the subview (the same one passed into the optional closure)
This will allow you to, in the layout closure, add arranged views for the passed in stack view.
*/
@discardableResult public func stackView<R>(_ subview: R,
layoutClosure: ((UIStackViewSubviewLayoutComponent<R, T>) -> Void)? = nil) -> UIStackViewSubviewLayoutComponent<R, T> {
subview.translatesAutoresizingMaskIntoConstraints = false
let subLayoutComponent = UIStackViewSubviewLayoutComponent(view: subview,
superview: ownedView,
cachedLayoutObjectStore: cachedLayoutObjectStore)
sublayoutComponents.append(.uistackview(layout: subLayoutComponent))
subviews.append(subview)
layoutClosure?(subLayoutComponent)
return subLayoutComponent
}
/**
Add a layout guide to the component's view.
- parameters:
- identifier: An identifier to give for this layout guide.
- layoutClosure: A closure that will define the layout component for the layout guide.
- returns: The layout component for the layout guide (the same one passed into the optional closure)
* This will just add a regular UILayoutGuide (`UILayoutGuide()`).
* Using an identifier will let you refer to the same created instance of a `UILayoutGuide`
in subsequent layout updates.
*/
@discardableResult public func layoutGuide(identifier: String,
layoutClosure: ((UILayoutGuideComponent<T>) -> Void)? = nil)
-> UILayoutGuideComponent<T> {
if let _layoutGuide = cachedLayoutObjectStore.layoutGuideStorage[identifier] {
return layoutGuide(_layoutGuide, layoutClosure: layoutClosure)
} else {
let _layoutGuide = UILayoutGuide()
cachedLayoutObjectStore.layoutGuideStorage[identifier] = _layoutGuide
return layoutGuide(_layoutGuide, layoutClosure: layoutClosure)
}
}
/**
Add a layout guide to the component's view.
- parameters:
- layoutClosure: A closure that will define the layout component for the layout guide.
- returns: The layout component for the layout guide (the same one passed into the optional closure)
* This will just add a regular UILayoutGuide (`UILayoutGuide()`).
* If you are calling `updateLayoutTo` more than once, you should not use this as it will cause
unnecessary layout recalculations to occur.
Consider using `addLayoutGuide(identifier:layoutClosure:)` instead for that situation.
*/
@discardableResult public func layoutGuide(layoutClosure: ((UILayoutGuideComponent<T>) -> Void)? = nil) -> UILayoutGuideComponent<T> {
return layoutGuide(UILayoutGuide(), layoutClosure: layoutClosure)
}
/**
Add a layout guide to the component's view.
- parameters:
- layoutGuide: The layout guide you would like ot add to the component's view.
- layoutClosure: A closure that will define the layout component for the layout guide.
- returns: The layout component for the layout guide (the same one passed into the optional closure)
*/
@discardableResult public func layoutGuide(_ layoutGuide: UILayoutGuide,
layoutClosure: ((UILayoutGuideComponent<T>) -> Void)? = nil) -> UILayoutGuideComponent<T> {
let subLayoutComponent = UILayoutGuideComponent(layoutGuide: layoutGuide,
owningView: ownedView)
sublayoutComponents.append(.layoutGuide(layout: subLayoutComponent))
layoutGuides.append(layoutGuide)
layoutClosure?(subLayoutComponent)
return subLayoutComponent
}
/**
Define constraints that should be activated
- parameters:
- constraints: Constraints to activate
- important: Do not activate these constraints yourself, the framework will do that for you.
If these constraints are activated at the wrong time it can cause your application to crash.
*/
public func constraints(_ _constraints: NSLayoutConstraint...) {
constraints(_constraints)
}
/**
Define constraints that should be activated
- parameters:
- constraints: Constraints to activate
- important: Do not activate these constraints yourself, the framework will do that for you.
If these constraints are activated at the wrong time it can cause your application to crash.
*/
public func constraints(_ _constraints: [NSLayoutConstraint]) {
constraints += _constraints.map(LayoutConstraint.init(wrappedConstraint:))
}
func allConstraints() -> [LayoutConstraint] {
return sublayoutComponents.reduce(constraints) { (combinedConstraints, layoutComponent) -> [LayoutConstraint] in
switch layoutComponent {
case .uistackview(let layoutComponent):
return combinedConstraints + layoutComponent.allConstraints()
case .uiview(let layoutComponent):
return combinedConstraints + layoutComponent.allConstraints()
case .layoutGuide(let layoutComponent):
return combinedConstraints + layoutComponent.allConstraints()
}
}
}
func allSubviews() -> [UIView] {
return sublayoutComponents.reduce(subviews) { (subviews, layoutComponent) -> [UIView] in
switch layoutComponent {
case .uistackview(let layoutComponent):
return subviews + layoutComponent.allSubviews()
case .uiview(let layoutComponent):
return subviews + layoutComponent.allSubviews()
case .layoutGuide:
return subviews
}
}
}
func allArrangedSubviews() -> [UIView: UIStackViewLayoutComponentType] {
return sublayoutComponents.reduce([:]) { (arrangedSubviews, layoutComponent) -> [UIView: UIStackViewLayoutComponentType] in
switch layoutComponent {
case .uistackview(let layoutComponent):
return arrangedSubviews.merging(layoutComponent.allArrangedSubviews()) { a, _ in a }
case .uiview(let layoutComponent):
return arrangedSubviews.merging(layoutComponent.allArrangedSubviews()) { a, _ in a }
case .layoutGuide:
return arrangedSubviews
}
}
}
func allLayoutGuides() -> [UILayoutGuide: UIView] {
let layoutGuideDict = layoutGuides.reduce([:]) { (dict, layoutGuide) -> [UILayoutGuide: UIView] in
var mutableDict = dict
mutableDict[layoutGuide] = ownedView
return mutableDict
}
return sublayoutComponents.reduce(layoutGuideDict) { (dict, layoutComponent) -> [UILayoutGuide: UIView] in
switch layoutComponent {
case .uistackview(let layoutComponent):
return dict.merging(layoutComponent.allLayoutGuides()) { a, _ in a }
case .uiview(let layoutComponent):
return dict.merging(layoutComponent.allLayoutGuides()) { a, _ in a }
case .layoutGuide:
return dict
}
}
}
}
| mit | 057684d23dfa292ba2ecbc4281c389cf | 44.707547 | 184 | 0.66075 | 5.306681 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILERemoteConnectionParameterRequestNegativeReply.swift | 1 | 3615 | //
// HCILERemoteConnectionParameterRequestNegativeReply.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Remote Connection Parameter Request Negative Reply Command
///
/// Both the master Host and the slave Host use this command to reply to the HCI
/// LE Remote Connection Parameter Request event. This indicates that the Host
/// has rejected the remote device’s request to change connection parameters.
/// The reason for the rejection is given in the Reason parameter.
func lowEnergyRemoteConnectionParameterRequestNegativeReply(connectionHandle: UInt16,
reason: UInt8,
timeout: HCICommandTimeout = .default) async throws -> UInt16 {
let parameters = HCILERemoteConnectionParameterRequestNegativeReply(connectionHandle: connectionHandle,
reason: reason)
let returnParameters = try await deviceRequest(parameters, HCILERemoteConnectionParameterRequestNegativeReplyReturn.self, timeout: timeout)
return returnParameters.connectionHandle
}
}
// MARK: - Command
/// LE Remote Connection Parameter Request Negative Reply Command
///
/// Both the master Host and the slave Host use this command to reply to the HCI
/// LE Remote Connection Parameter Request event. This indicates that the Host
/// has rejected the remote device’s request to change connection parameters.
/// The reason for the rejection is given in the Reason parameter.
@frozen
public struct HCILERemoteConnectionParameterRequestNegativeReply: HCICommandParameter {
public static let command = HCILowEnergyCommand.remoteConnectionParameterRequestNegativeReply //0x0021
public var connectionHandle: UInt16
public var reason: UInt8
public init(connectionHandle: UInt16,
reason: UInt8) {
self.connectionHandle = connectionHandle
self.reason = reason
}
public var data: Data {
let connectionHandleBytes = connectionHandle.littleEndian.bytes
return Data([
connectionHandleBytes.0,
connectionHandleBytes.1,
reason
])
}
}
// MARK: - Return parameter
/// LE Remote Connection Parameter Request Negative Reply Command
///
/// Both the master Host and the slave Host use this command to reply to the HCI
/// LE Remote Connection Parameter Request event. This indicates that the Host
/// has rejected the remote device’s request to change connection parameters.
/// The reason for the rejection is given in the Reason parameter.
@frozen
public struct HCILERemoteConnectionParameterRequestNegativeReplyReturn: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.remoteConnectionParameterRequestNegativeReply //0x0021
public static let length: Int = 2
/// Connection_Handle
/// Range 0x0000-0x0EFF (all other values reserved for future use)
public let connectionHandle: UInt16 // Connection_Handle
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
connectionHandle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))
}
}
| mit | 9d8e5ac8b194138061631a9eec06d4d6 | 36.583333 | 147 | 0.672395 | 5.25182 | false | false | false | false |
Suninus/iOS8-Sampler | iOS8Sampler/Samples/TouchRadiusViewController.swift | 8 | 2182 | //
// TouchRadiusViewController.swift
// iOS8Sampler
//
// Created by Shuichi Tsutsumi on 2015/02/18.
// Copyright (c) 2015年 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
class TouchRadiusViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: "TouchRadiusViewController", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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: Private
private func createHaloAt(location: CGPoint, withRadius radius: CGFloat) {
let halo = PulsingHaloLayer()
halo.repeatCount = 1
halo.position = location
halo.radius = radius * 2.0
halo.fromValueForRadius = 0.5
halo.keyTimeForHalfOpacity = 0.7
halo.animationDuration = 0.8
self.view.layer.addSublayer(halo)
}
// =========================================================================
// MARK: Touch Handlers
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for obj: AnyObject in touches {
let touch = obj as! UITouch
let location = touch.locationInView(self.view)
let radius = touch.majorRadius
self.createHaloAt(location, withRadius: radius)
}
}
}
| mit | 406ebaaff6be37e604695c309c3b9bd4 | 28.066667 | 106 | 0.589908 | 5.129412 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/PersistentUserData.swift | 1 | 4024 | //
// PersistentUserData.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program 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, version 3.
//
// 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 GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Sweeft
enum PersistendUserData: Codable {
enum State: Int, Codable {
case loggedIn
case awaitingConfirmation
}
enum CodingKeys: String, CodingKey {
case lrzID
case token
case state
}
case no
case requestingToken(lrzID: String)
case some(lrzID: String, token: String, state: State)
var user: User? {
guard case .some(let lrzID, let token, let state) = self else {
return nil
}
return state == .loggedIn ? User(lrzID: lrzID, token: token) : nil
}
init(from decoder: Decoder) throws {
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
let lrzID = try container.decode(String.self, forKey: .lrzID)
do {
let token = try container.decode(String.self, forKey: .token)
let state = try container.decode(State.self, forKey: .state)
self = .some(lrzID: lrzID, token: token, state: state)
} catch {
self = .requestingToken(lrzID: lrzID)
}
} catch {
self = .no
}
}
func encode(to encoder: Encoder) throws {
switch self {
case .no:
let dict = [String : String]()
var container = encoder.singleValueContainer()
try container.encode(dict)
case .requestingToken(let lrzID):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(lrzID, forKey: .lrzID)
case .some(let lrzID, let token, let state):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(lrzID, forKey: .lrzID)
try container.encode(token, forKey: .token)
try container.encode(state, forKey: .state)
}
}
}
private func fetchCredentialsFromDefaults() -> PersistendUserData? {
let defaults = UserDefaults.standard
guard let dictionary = defaults.dictionary(forKey: "AppDefaults.login") else {
return nil
}
guard let lrzID = dictionary["lrzID"] as? String, let token = dictionary["token"] as? String else {
return nil
}
return .some(lrzID: lrzID, token: token, state: .loggedIn)
}
struct PersistentUser: SingleStatus {
static let storage: Storage = .keychain
static let key: AppDefaults = .login
static var defaultValue: PersistendUserData {
guard let previousValue = fetchCredentialsFromDefaults() else {
return .no
}
UserDefaults.standard.removeObject(forKey: "AppDefaults.login")
UserDefaults.standard.synchronize()
PersistentUser.value = previousValue
return previousValue
}
}
extension PersistentUser {
static var isLoggedIn: Bool {
if case .some(_, _, .loggedIn) = value {
return true
}
return false
}
static var hasEnteredID: Bool {
if case .no = value {
return false
}
return true
}
static var hasRequestedToken: Bool {
if case .some = value {
return true
}
return false
}
}
| gpl-3.0 | d981248e1e15def9f171b7c69548b2a7 | 29.255639 | 103 | 0.608598 | 4.308351 | false | false | false | false |
Sweefties/SwiftyPageController | SwiftyPageController/Classes/SwiftyPageControllerAnimatorParallax.swift | 1 | 2842 | //
// PagesViewControllerAnimator.swift
// ContainerControllerTest
//
// Created by Alexander on 8/3/17.
// Copyright © 2017 CryptoTicker. All rights reserved.
//
import Foundation
import UIKit
open class SwiftyPageControllerAnimatorParallax: SwiftyPageControllerAnimatorProtocol {
fileprivate var _animationProgress: Float!
fileprivate var _animationSpeed: Float = 3.2
fileprivate var timer: Timer!
fileprivate var fromControllerAnimationIdentifier = "from.controller.animation.position.x"
fileprivate var toControllerAnimationIdentifier = "to.controller.animation.position.x"
public var animationProgress: Float {
get {
return _animationProgress
}
set {
_animationProgress = newValue
}
}
public var animationSpeed: Float {
get {
return _animationSpeed
}
set {
_animationSpeed = newValue
}
}
public var isEnabledOpacity = false
public func setupAnimation(fromController: UIViewController, toController: UIViewController, panGesture: UIPanGestureRecognizer, animationDirection: SwiftyPageController.AnimationDirection) {
let speed = panGesture.state != .changed ? animationSpeed : 0.0
// position animation
let animationPositionToController = CABasicAnimation(keyPath: "position.x")
animationPositionToController.duration = animationDuration
animationPositionToController.fromValue = animationDirection == .left ? (toController.view.frame.width * 1.5) : (-toController.view.frame.width / 2.0)
animationPositionToController.toValue = toController.view.frame.width / 2.0
animationPositionToController.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
toController.view.layer.add(animationPositionToController, forKey: toControllerAnimationIdentifier)
let animationPositionFromController = animationPositionToController
animationPositionFromController.fromValue = fromController.view.layer.position.x
animationPositionFromController.toValue = animationDirection == .left ? (0.0) : (toController.view.frame.width)
fromController.view.layer.add(animationPositionFromController, forKey: fromControllerAnimationIdentifier)
// set speed
toController.view.layer.speed = speed
fromController.view.layer.speed = speed
}
public func didFinishAnimation(fromController: UIViewController, toController: UIViewController) {
// remove animations
toController.view.layer.removeAnimation(forKey: toControllerAnimationIdentifier)
fromController.view.layer.removeAnimation(forKey: fromControllerAnimationIdentifier)
}
}
| mit | 5d1f08862819216f1709674f44dd0a24 | 39.014085 | 195 | 0.714537 | 5.37051 | false | false | false | false |
CoderFeiSu/FFCategoryHUD | FFCategoryHUD/FFSegmentBarStyle.swift | 1 | 1517 | //
// FFCategoryTitleStyle.swift
// FFCategoryHUDExample
//
// Created by Freedom on 2017/4/20.
// Copyright © 2017年 Freedom. All rights reserved.
//
import UIKit
public class FFSegmentBarStyle: NSObject {
/** 文字视图高度 */
public var height: CGFloat = 44
/** 普通文字颜色 */
public var normalColor: UIColor = .black
/** 选中文字颜色 */
public var selectColor: UIColor = .red
public var normalFont: UIFont = UIFont.systemFont(ofSize: 13.0)
/** 文字区背景颜色 */
public var barColor: UIColor = UIColor.lightGray
/** 内容背景颜色 */
public var contentColor: UIColor = UIColor.groupTableViewBackground
/** 默认文字之间的间距是10 */
public var margin: CGFloat = 10
/** 默认文字到屏幕左边的间距是5 */
public var leftMargin: CGFloat = 5
/** 默认文字到屏幕右边的间距是5 */
public var rightMargin: CGFloat = 5
/** 底部线条 */
public var bottomLine: FFSegmentBarBottomLine = FFSegmentBarBottomLine()
/** 是否可以缩放 */
public var isNeedScale: Bool = false
/** 放大到的比例 */
public var maxScale: CGFloat = 1.2
}
public class FFSegmentBarBottomLine: NSObject {
/** 是否显示底部指示条 */
public var isShow: Bool = false
public var height: CGFloat = 2.0
public var color: UIColor = UIColor.blue
/** 是否跟文字长度一样,默认占满整个文字视图 */
public var isFitTitle: Bool = false
}
| mit | 46541534b8c47d42c59fb09a3ca25478 | 25.916667 | 77 | 0.658669 | 3.788856 | false | false | false | false |
wess/reddift | reddift/Model/Paginator.swift | 1 | 1118 | //
// Paginator.swift
// reddift
//
// Created by sonson on 2015/04/14.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
/**
Paginator object for paiging listing object.
*/
public struct Paginator {
let after:String
let before:String
let modhash:String
public init() {
self.after = ""
self.before = ""
self.modhash = ""
}
public init(after:String, before:String, modhash:String) {
self.after = after
self.before = before
self.modhash = modhash
}
public var isVacant : Bool {
if (!after.isEmpty) || (!before.isEmpty) {
return false
}
return true
}
/**
Generate dictionary to add query parameters to URL.
If paginator is vacant, returns vacant dictionary as [String:String].
:returns: Dictionary object for paging.
*/
public func parameters() -> [String:String] {
var dict:[String:String] = [:]
if count(after) > 0 {
dict["after"] = after
}
if count(before) > 0 {
dict["before"] = before
}
return dict
}
}
| mit | 82c03ec096e4dd4e26ca4cc3bce14179 | 19.666667 | 70 | 0.587814 | 3.795918 | false | false | false | false |
ivlevAstef/DITranquillity | Samples/SampleChaos/SampleChaos/SampleClasses.swift | 1 | 4561 | //
// SampleClasses.swift
// SampleChaos
//
// Created by Alexander Ivlev on 14/06/16.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
import UIKit
import DITranquillity
protocol ServiceProtocol {
func foo()
}
class FooService: ServiceProtocol {
func foo() {
print("foo")
}
}
class BarService: ServiceProtocol {
func foo() {
print("bar")
}
}
protocol LoggerProtocol {
func log(_ msg: String)
}
class Logger: LoggerProtocol {
func log(_ msg: String) {
print("log: \(msg)")
}
}
class Logger2: LoggerProtocol {
func log(_ msg: String) {
print("log2: \(msg)")
}
}
class LoggerAll: LoggerProtocol {
let loggers: [LoggerProtocol]
var loggersFull: [LoggerProtocol]! {
didSet {
print(loggersFull)
}
}
init(loggers: [LoggerProtocol]) {
self.loggers = loggers
print(loggers)
}
func log(_ msg: String) {
for logger in loggers {
logger.log(msg)
}
}
}
class Inject {
private let service: ServiceProtocol
private let logger: LoggerProtocol
internal var logger2: LoggerProtocol? = nil
internal var service2: ServiceProtocol? = nil
init(service: ServiceProtocol, logger: LoggerProtocol, test: Int) {
self.service = service
self.logger = logger
}
var description: String {
return "<Inject: \(Unmanaged.passUnretained(self).toOpaque()) service:\(Unmanaged.passUnretained(service as AnyObject).toOpaque()) logger:\(Unmanaged.passUnretained(logger as AnyObject).toOpaque()) logger2:\(Unmanaged.passUnretained(logger2 as AnyObject).toOpaque()) service2:\(Unmanaged.passUnretained(service2 as AnyObject).toOpaque())>"
}
}
class InjectMany {
private let loggers: [LoggerProtocol]
init(loggers: [LoggerProtocol]) {
self.loggers = loggers
}
}
class Animal {
internal let name: String
init(name: String) {
self.name = name
}
}
class TestCat: Animal {
override init(name: String) {
super.init(name: name)
}
}
typealias CatTag = Animal
typealias DogTag = Animal
typealias BearTag = Animal
typealias TestCatTag = Animal
class Circular1 {
let ref: Circular2
init(ref: Circular2) {
self.ref = ref
}
var description: String {
return "<Circular1: \(Unmanaged.passUnretained(self).toOpaque()) Circular2:\(Unmanaged.passUnretained(ref).toOpaque())>"
}
}
class Circular2 {
var ref: Circular1!
var description: String {
return "<Circular2: \(Unmanaged.passUnretained(self).toOpaque()) Circular1:\(Unmanaged.passUnretained(ref).toOpaque())>"
}
}
class SamplePart: DIPart {
static func load(container: DIContainer) {
container.register{ 10 }.lifetime(.perRun(.strong))
container.register(BarService.init)
.as(ServiceProtocol.self)
.lifetime(.prototype)
container.register { LoggerAll(loggers: many($0)) }
.as(check: LoggerProtocol.self){$0}
.default()
.lifetime(.single)
.injection(cycle: true){ $0.loggersFull = many($1) }
container.register{ Logger() }
.as(check: LoggerProtocol.self){$0}
.lifetime(.single)
container.register{ Logger2() }
.as(check: LoggerProtocol.self){$0}
.lifetime(.perRun(.strong))
container.register(Inject.init)
.lifetime(.prototype)
.injection{ $0.service2 = $1 }
.injection{ $0.logger2 = $1 }
container.register { InjectMany(loggers: many($0)) }
.lifetime(.prototype)
//Animals
container.register{ Animal(name: "Cat") }
.as(Animal.self, tag: CatTag.self)
container.register{ Animal(name: "Dog") }
.as(Animal.self, tag: DogTag.self)
.default()
container.register{ Animal(name: "Bear") }
.as(Animal.self, tag: BearTag.self)
container.register{ TestCat(name: "Felix") }
.as(Animal.self, tag: TestCatTag.self)
//circular
container.register(Circular1.init)
.lifetime(.objectGraph)
container.register(Circular2.init)
.lifetime(.objectGraph)
.injection(cycle: true) { $0.ref = $1 }
}
}
class SampleStartupPart : DIPart {
static func load(container: DIContainer) {
container.append(part: SamplePart.self)
container.register(ViewController.self)
.injection { $0.injectGlobal = $1 }
.injection { $0.container = $1 }
container.register(ViewController2.self)
.injection { $0.inject = $1 }
.injection { $0.logger = $1 }
container.register { UIButton() }
.as(check: UIAppearance.self){$0}
.as(check: UIView.self){$0}
.lifetime(.prototype)
}
}
| mit | 8e2b9ab36ed7da2ddd86aa13060c71a2 | 21.352941 | 343 | 0.653509 | 3.768595 | false | false | false | false |
anto0522/AdMate | AdDataKit2/Public.swift | 1 | 11659 | //
// Public.swift
// AdMate
//
// Created by Antonin Linossier on 10/29/15.
// Copyright © 2015 Antonin Linossier. All rights reserved.
//
import Foundation
import SQLite
import Cocoa
import SwiftyJSON
import AdMateOAuth
//import p2_OAuth2
public enum RowSelected {
case Earnings
case PageViews
case Clicks
case PageRPM
case Coverage
case CTR
case CostPerClick
}
public struct AdData {
public var AdRequest = Int?()
public var AdRequestCoverage = Float?()
public var AdRequestCTR = Float?()
public var AdRequestRPM = Float?()
public var AdClicks = Int?()
public var AdCostPerClick = Float?()
public var Earnings = Float?()
public var PageViews = Int?()
public var PageViewRPM = Float?()
public var MatchedAdRequest = Int?()
public var Date = NSDate?()
public init(AdRequest: String, AdRequestCoverage: String, AdRequestCTR: String, AdRequestRPM: String, AdClicks: String, AdCostPerClick: String, Earnings: String, PageViews: String, PageViewRPM: String, MatchedAdRequest: String, Date: String)
{
self.AdRequest = ValidateDataFromDb(AdRequest, Type: "Int") as? Int
self.AdRequestCoverage = ValidateDataFromDb(AdRequestCoverage, Type: "Float") as? Float
self.AdRequestCTR = ValidateDataFromDb(AdRequestCTR, Type: "Float") as? Float
self.AdRequestRPM = ValidateDataFromDb(AdRequestRPM, Type: "Float") as? Float
self.AdClicks = ValidateDataFromDb(AdClicks, Type: "Int") as? Int
self.AdCostPerClick = ValidateDataFromDb(AdCostPerClick, Type: "Float") as? Float
self.Earnings = ValidateDataFromDb(Earnings, Type: "Float") as? Float
self.PageViews = ValidateDataFromDb(PageViews, Type: "Int") as? Int
self.PageViewRPM = ValidateDataFromDb(PageViewRPM, Type: "Float") as? Float
self.MatchedAdRequest = ValidateDataFromDb(MatchedAdRequest, Type: "Int") as? Int
self.Date = ValidateDataFromDb(Date, Type: "Date") as? NSDate
}
}
func ValidateDataFromDb(Data:String, Type: String) -> AnyObject{
switch Type
{
case "Date":
if Data != "<null>" && Data != "0"{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.dateFromString(Data)
return date!
} else {
return NSDate()
}
case "Float":
if Data != "<null>" && Data != "0"{
return Data.floatValue
} else {
return Float(0)
}
case "Int":
if Data != "<null>" && Data != "0"{
return Int(Data)!
} else {
return Int(0)
}
default:
return 0
}
}
public extension String {
var floatValue: Float {
return (self as NSString).floatValue
}
}
public extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
///
/// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Return precent escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}
}
public let UserIDDefault = String("UD77")
//public var documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
public var documentsFolder = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("4K3EUCP99P.AdMate")
public let defaults: NSUserDefaults = NSUserDefaults(suiteName: "4K3EUCP99P.AdMate")!
public var dbpath = (documentsFolder)?.URLByAppendingPathComponent("AdMate.db")
public func copyFile(fileName: NSString) {
let dbPath = getPath(fileName as String)
print("copyFile fileName=\(fileName) to path=\(dbPath)")
let fileManager = NSFileManager.defaultManager()
let fromPath = (NSBundle.mainBundle().resourceURL)!.URLByAppendingPathComponent(fileName as String)
if !fileManager.fileExistsAtPath(dbPath.path!) {
print("dB not found in document directory filemanager will copy this file from this path=\(fromPath.path) :::TO::: path=\(dbPath.path)")
defaults.setObject(dbPath.path, forKey: "DBPath")
defaults.synchronize()
do {
try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath.path!)
} catch _ {
}
} else {
print("DID-NOT copy dB file, file allready exists at path:\(dbPath)")
}
}
public func getPath(fileName: String) -> NSURL {
let documentsFolder = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("4K3EUCP99P.AdMate")
return documentsFolder!.URLByAppendingPathComponent(fileName)
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
//extension NSDate: Comparable { }
public let AdDataTable = Table("AdData")
public let AdRequestData = Expression<String>("AD_REQUESTS")
public let AdRequestCoverageData = Expression<String>("AD_REQUESTS_COVERAGE")
public let AdRequestCTRData = Expression<String>("AD_REQUESTS_CTR")
public let AdRequestRPMData = Expression<String>("AD_REQUESTS_RPM")
public let ClicksData = Expression<String>("CLICKS")
public let CostPerClickData = Expression<String>("COST_PER_CLICK")
public let EarningsData = Expression<String>("EARNINGS")
public let PageViewRPMData = Expression<String>("PAGE_VIEWS_RPM")
public let PageViewsData = Expression<String>("PAGE_VIEWS")
public let MatchedAdREquestData = Expression<String>("MATCHED_AD_REQUESTS")
public let DateData = Expression<String>("DATE")
public extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joinWithSeparator("&")
}
}
public extension NSDate
{
func isGreaterThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
{
isGreater = true
}
//Return Result
return isGreater
}
func isLessThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isLess = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending
{
isLess = true
}
//Return Result
return isLess
}
// func isEqualToDate(dateToCompare : NSDate) -> Bool
// {
// //Declare Variables
// var isEqualTo = false
//
// //Compare Values
// if self.compare(dateToCompare) == NSComparisonResult.OrderedSame
// {
// isEqualTo = true
// }
//
// //Return Result
// return isEqualTo
// }
public func rounder (numbertoround: Float) -> NSString {
let rounded: NSString
if (numbertoround > 10){
rounded = NSString(format: "%.02f", numbertoround)
} else if (numbertoround < 1){
rounded = NSString(format: "%.02f", numbertoround)
} else {
rounded = NSString(format: "%.02f", numbertoround)
}
return rounded
}
func addDays(daysToAdd : Int) -> NSDate
{
let secondsInDays : NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded : NSDate = self.dateByAddingTimeInterval(secondsInDays)
//Return Result
return dateWithDaysAdded
}
func addHours(hoursToAdd : Int) -> NSDate
{
let secondsInHours : NSTimeInterval = Double(hoursToAdd) * 60 * 60
let dateWithHoursAdded : NSDate = self.dateByAddingTimeInterval(secondsInHours)
//Return Result
return dateWithHoursAdded
}
}
public func GetCurrencySymbol(Code: String)-> String{
if let path = NSBundle.mainBundle().pathForResource("Common-Currency", ofType: "json") {
do {
let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
if let currencycode = jsonObj[Code]["symbol"].string{
return currencycode
} else {
return "$"
}
} else {
print("could not get json from file, make sure that file contains valid json.")
return "$"
}
} catch let error as NSError {
print(error.localizedDescription)
return "$"
}
} else {
print("Invalid filename/path.")
return "$"
}
}
public func ConvertPercentage(Percentage: Float)-> String{
let Compromised = Percentage * 100
return rounder(Float(Compromised))
}
public func colorWithHexString (hex:String) -> NSColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return NSColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return NSColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
| mit | 86a28965db86cbb5822215853c21ad68 | 27.296117 | 248 | 0.608681 | 4.973549 | false | false | false | false |
gaelfoppolo/handicarparking | HandiParking/HandiParking/Source/DTIActivityIndicatorView.swift | 1 | 4529 | //
// DTIActivityIndicatorView.swift
//
// Created by dtissera on 12/08/2014.
// Copyright (c) 2014 o--O--o. All rights reserved.
//
import UIKit
import QuartzCore
import Foundation
//@IBDesignable
@objc
public class DTIActivityIndicatorView: UIView {
// warning unlike objc, we dont have TARGET_INTERFACE_BUILDER macro in swift !
// this variable as the right value only after prepareForInterfaceBuilder()
// is called
// https://developer.apple.com/library/prerelease/ios/recipes/xcode_help-IB_objects_media/CreatingaLiveViewofaCustomObject.html
// http://justabeech.com/2014/08/03/prepareforinterfacebuilder-and-property-observers/
private var runningWithinInterfaceBuilder: Bool = false
/** private properties */
private var activityStarted: Bool = false
private var currentAnimation: DTIAnimProtocol? = nil
/** @IBInspectable properties */
@IBInspectable public var indicatorColor: UIColor = UIColor.whiteColor() {
didSet {
if (self.currentAnimation != nil) {
self.currentAnimation!.needUpdateColor()
}
}
}
@IBInspectable public var indicatorStyle: String = DTIIndicatorStyle.convInv(.defaultValue)
/** ctor && ~ctor */
override public init(frame: CGRect) {
super.init(frame: frame);
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
if (self.activityStarted) {
self.stopActivity(false)
}
}
/** private members */
private func setUpAnimation() {
let style = DTIIndicatorStyle.conv(self.indicatorStyle)
switch style {
case .rotatingPane:self.currentAnimation = DTIAnimRotatingPlane(indicatorView: self)
case .doubleBounce:self.currentAnimation = DTIAnimDoubleBounce(indicatorView: self)
case .wave:self.currentAnimation = DTIAnimWave(indicatorView: self)
case .wanderingCubes:self.currentAnimation = DTIAnimWanderingCubes(indicatorView: self)
case .chasingDots:self.currentAnimation = DTIAnimChasingDots(indicatorView: self)
case .pulse:self.currentAnimation = DTIAnimPulse(indicatorView: self)
case .spotify:self.currentAnimation = DTIAnimSpotify(indicatorView: self)
case .wp8:self.currentAnimation = DTIAnimWp8(indicatorView: self)
}
self.setUpColors()
}
private func setUpColors() {
self.backgroundColor = UIColor.clearColor()
if (self.currentAnimation != nil) {
self.currentAnimation!.needUpdateColor()
}
}
/** overrides */
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.runningWithinInterfaceBuilder = true
setUpColors();
}
override public func layoutSubviews() {
if (self.currentAnimation != nil) {
currentAnimation!.needLayoutSubviews()
}
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
if (self.runningWithinInterfaceBuilder) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, self.indicatorColor.CGColor)
let dashLengths:[CGFloat] = [2.0, 2.0]
CGContextSetLineDash(context, 0.0, dashLengths, dashLengths.count)
CGContextStrokeRect(context, self.bounds)
CGContextRestoreGState(context)
}
}
override public func sizeThatFits(size: CGSize) -> CGSize {
if (size.width < 20.0) {
return CGSize(width: 20.0, height: 20.0)
}
// force width = height
return CGSize(width: size.width, height: size.width)
}
/** public members */
public func startActivity() {
if (self.activityStarted) {
return
}
self.activityStarted = true
self.setUpAnimation()
currentAnimation!.needLayoutSubviews()
currentAnimation!.setUp()
currentAnimation!.startActivity()
}
public func stopActivity(animated: Bool) {
if (!self.activityStarted) {
return
}
self.activityStarted = false;
currentAnimation!.stopActivity(animated)
}
public func stopActivity() {
self.stopActivity(true)
}
}
| gpl-3.0 | ba4a75bbaa08cff7bdf66e69049e31ae | 30.234483 | 131 | 0.632811 | 4.955142 | false | false | false | false |
wookay/Look | Look/lib/Look.swift | 1 | 891 | //
// Look.swift
// Look
//
// Created by wookyoung on 11/26/15.
// Copyright © 2015 factorcat. All rights reserved.
//
import UIKit
public class Look : CustomDebugStringConvertible, CustomPlaygroundQuickLookable {
public var canvas: UIView? = nil
var object: AnyObject? = nil
var preview: PlaygroundQuickLook = .Text("nil")
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return self.preview
}
public var debugDescription: String {
if let obj = self.object {
var targetStream = String()
dump(obj, &targetStream)
return targetStream
} else {
return "nil"
}
}
var def = LookDefault()
struct LookDefault {
var frame = CGRectMake(0, 0, 200, 100)
var fontName = "Helvetica"
var fontSize: CGFloat = 15
}
}
| mit | a0d43d8010c971ecac028c3f85123ef5 | 22.421053 | 81 | 0.598876 | 4.564103 | false | false | false | false |
leotumwattana/WWC-Animations | WWC-Animations/ShakyCircle.swift | 1 | 1783 | //
// ShakyCircle.swift
// WWC-Animations
//
// Created by Leo Tumwattana on 27/5/15.
// Copyright (c) 2015 Innovoso Ltd. All rights reserved.
//
import UIKit
import pop
class ShakyCircle: Circle {
override func tapped(tap: UITapGestureRecognizer) {
if let anim = layer.pop_animationForKey("shake") as? POPAnimation {
reset()
} else {
shake()
}
}
private func shake() {
let shake = POPBasicAnimation(propertyNamed: kPOPLayerTranslationX)
shake.fromValue = -5
shake.toValue = 5
shake.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
shake.duration = 0.05
shake.autoreverses = true
shake.repeatForever = true
layer.pop_removeAnimationForKey("reset")
layer.pop_addAnimation(shake, forKey: "shake")
}
private func reset() {
let reset = POPSpringAnimation(propertyNamed: kPOPLayerTranslationX)
reset.toValue = 0
reset.velocity = 2000
reset.springBounciness = 20
reset.dynamicsFriction = 10
reset.dynamicsTension = 1000
layer.pop_removeAnimationForKey("shake")
layer.pop_addAnimation(reset, forKey: "reset")
let scream = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
scream.toValue = NSValue(CGSize: CGSizeMake(1.5, 1.5))
scream.springSpeed = 20
scream.completionBlock = { [unowned self] (anim, finished) in
let settle = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
settle.toValue = NSValue(CGSize: CGSizeMake(1, 1))
self.layer.pop_addAnimation(settle, forKey: "scale")
}
layer.pop_addAnimation(scream, forKey: "scale")
}
}
| bsd-3-clause | 8f2ef6ce0d6c14ea87aef5d2ffdfa3bd | 31.418182 | 95 | 0.639372 | 4.583548 | false | false | false | false |
jingtaozf/radare2-bindings | r2pipe/swift/r2pipeNative.swift | 2 | 4678 | #if HAVE_SPAWN
import Foundation
private struct Stack<T> {
var items = [T]()
mutating func push(item:T) {
items.append (item);
}
mutating func pop() -> T? {
if items.count > 0 {
return items.removeLast()
}
return nil;
}
}
typealias Closure = (String?)->Void
class R2PipeNative {
var taskNotLaunched = true;
var initState = true;
private var stack = Stack<Closure>();
private let pipe = NSPipe()
private let pipeIn = NSPipe()
private let task = NSTask()
private var bufferedString = "";
private var inHandle:NSFileHandle? = nil;
init?(file:String?) {
let outHandle:NSFileHandle;
if file == nil {
#if USE_ENV_PIPE
let dict = NSProcessInfo.processInfo().environment
let env_IN = dict["R2PIPE_IN"] as String?
let env_OUT = dict["R2PIPE_OUT"] as String?
// print ("PIPES \(env_IN) \(env_OUT)");
if env_IN == nil || env_OUT == nil {
return nil;
}
let fd_IN = Int32(env_IN!);
let fd_OUT = Int32(env_OUT!);
if fd_IN == nil || fd_OUT == nil {
return nil;
}
if fd_IN < 0 || fd_OUT < 0 {
return nil;
}
initState = false;
taskNotLaunched = false;
outHandle = NSFileHandle(fileDescriptor:fd_IN!)
inHandle = NSFileHandle(fileDescriptor:fd_OUT!)
#else
return nil;
#endif
} else {
task.launchPath = "/usr/bin/radare2";
task.arguments = ["-q0", file!]
task.standardOutput = pipe
task.standardInput = pipeIn
outHandle = pipe.fileHandleForReading
inHandle = pipeIn.fileHandleForWriting
}
outHandle.waitForDataInBackgroundAndNotify()
NSNotificationCenter.defaultCenter()
.addObserverForName(NSFileHandleDataAvailableNotification,
object: outHandle, queue: nil) {
notification -> Void in
var data = outHandle.availableData
if data.length > 0 {
var count = data.length
var pointer = UnsafePointer<UInt8>(data.bytes)
var buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
var foundTerminator = false;
var foundTerminatorAt = -1;
for (var i = 0; i<count; i++) {
if (buffer[i] == 0) {
foundTerminator = true;
foundTerminatorAt = i;
break;
}
}
if (foundTerminator) {
for (;;) {
if (self.initState) {
// skip
self.initState = false;
} else {
let newData = NSData(bytes:data.bytes, length:foundTerminatorAt);
if let str = NSString(data:newData, encoding: NSUTF8StringEncoding) {
self.bufferedString += str as String;
self.runCallback (self.bufferedString);
self.bufferedString = "";
} else {
print ("ERROR")
}
}
let newBytes = UnsafePointer<UInt8>(data.bytes) + foundTerminatorAt + 1;
count = count - foundTerminatorAt - 1;
data = NSData(bytes:newBytes, length:count);
pointer = UnsafePointer<UInt8>(newBytes)
buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
if count < 1 {
break;
}
foundTerminator = false;
foundTerminatorAt = -1;
for (var i = 0; i<count; i++) {
if (buffer[i] == 0) {
foundTerminator = true;
foundTerminatorAt = i;
break;
}
}
if (!foundTerminator) {
if let d = NSString(data:data, encoding: NSUTF8StringEncoding) {
self.bufferedString = d as String
}
break;
}
}
} else {
if let str = NSString(data:data, encoding: NSUTF8StringEncoding) {
self.bufferedString += str as String;
}
}
outHandle.waitForDataInBackgroundAndNotify ();
} else {
// EOF happened
}
}
NSNotificationCenter.defaultCenter()
.addObserverForName(NSTaskDidTerminateNotification,
object: outHandle, queue: nil) {
notification -> Void in
print ("Terminated")
/* TODO: Terminate properly */
self.taskNotLaunched = true;
}
}
private func runCallback(str:String) {
if let closure = stack.pop() {
closure(str);
}
}
func sendCommand(str:String, closure:Closure) -> Bool{
let cmd = str + "\n";
if let data = cmd.dataUsingEncoding(NSUTF8StringEncoding) {
inHandle!.writeData (data)
stack.push (closure);
}
if (self.taskNotLaunched) {
task.launch()
self.taskNotLaunched = false;
self.initState = true;
}
return true;
}
func sendCommandSync(str:String) -> String? {
let timeout = 10000000;
var result:String? = nil;
self.sendCommand (str, closure:{
(str:String?) in
result = str
})
for (var i = 0; i<timeout; i++) {
// wait for reply in a loop
if let r = result {
return r;
}
let next = NSDate(timeIntervalSinceNow:0.1)
NSRunLoop.currentRunLoop().runUntilDate(next);
}
return nil;
}
}
#endif
| gpl-3.0 | 4a3ad4b61017e827db26f5af34c8f5a7 | 24.150538 | 78 | 0.628046 | 3.315379 | false | false | false | false |
nathawes/swift | stdlib/public/Darwin/XCTest/XCTest.swift | 9 | 30673 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
// The actual XCTest overlay is not maintained in this repository -- it is
// distributed in Xcode (libXCTestSwiftSupport.dylib), along with
// XCTest.framework itself.
//
// The codebase here builds the obsolete /usr/lib/swift/libswiftXCTest.dylib
// that currently ships in the OS. There is no expectation that that library is
// usable for anything; it only exists to maintain a superficial level of binary
// compatibility with existing apps that happen to link to it by mistake.
//
// rdar://problem/55270944
@_exported import XCTest // Clang module
import CoreGraphics
@_implementationOnly import _SwiftXCTestOverlayShims
// --- XCTest API Swiftification ---
extension XCTContext {
/// Create and run a new activity with provided name and block.
public class func runActivity<Result>(named name: String, block: (XCTActivity) throws -> Result) rethrows -> Result {
let context = _XCTContextCurrent()
if _XCTContextShouldStartActivity(context, XCTActivityTypeUserCreated) {
return try autoreleasepool {
let activity = _XCTContextWillStartActivity(context, name, XCTActivityTypeUserCreated)
defer {
_XCTContextDidFinishActivity(context, activity)
}
return try block(activity)
}
} else {
fatalError("XCTContext.runActivity(named:block:) failed because activities are disallowed in the current configuration.")
}
}
}
#if os(macOS)
@available(swift 4.0)
@available(macOS 10.11, *)
extension XCUIElement {
/// Types a single key from the XCUIKeyboardKey enumeration with the specified modifier flags.
@nonobjc public func typeKey(_ key: XCUIKeyboardKey, modifierFlags: XCUIElement.KeyModifierFlags) {
// Call the version of the method defined in XCTest.framework.
typeKey(key.rawValue, modifierFlags: modifierFlags)
}
}
#endif
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(_ expected: Bool, _ condition: String, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCase()
_XCTPreformattedFailureHandler(test, expected, file.description, Int(line), condition, message())
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(_ assertionType: _XCTAssertionType, _ formatIndex: Int, _ expressionStrings: CVarArg...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case success
case failedWithError(error: Error)
case failedWithException(className: String, name: String, reason: String)
case failedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception or error,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(_ block: () throws -> Void) -> _XCTThrowableBlockResult {
var blockErrorOptional: Error?
let exceptionResult = _XCTRunThrowableBlockBridge({
do {
try block()
} catch {
blockErrorOptional = error
}
})
if let blockError = blockErrorOptional {
return .failedWithError(error: blockError)
} else if let exceptionResult = exceptionResult {
if exceptionResult["type"] == "objc" {
return .failedWithException(
className: exceptionResult["className"]!,
name: exceptionResult["name"]!,
reason: exceptionResult["reason"]!)
} else {
return .failedWithUnknownException
}
} else {
return .success
}
}
// --- Supported Assertions ---
public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`nil`
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssert(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(try expression(), message(), file: file, line: line)
}
public func XCTAssertTrue(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`true`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertFalse(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`false`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equalWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
preconditionFailure("Unsupported floating-point type passed to XCTAssertEqual")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertEqual(_:_:accuracy:file:line:)")
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line)
}
func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
preconditionFailure("Unsupported floating-point type passed to XCTAssertNotEqual")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertNotEqual(_:_:accuracy:file:line:)")
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertNotEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line)
}
public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.greaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.greaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.lessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.lessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Error) -> Void = { _ in }) {
// evaluate expression exactly once
var caughtErrorOptional: Error?
let result = _XCTRunThrowableBlock {
do {
_ = try expression()
} catch {
caughtErrorOptional = error
}
}
switch result {
case .success:
if let caughtError = caughtErrorOptional {
errorHandler(caughtError)
} else {
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message(), file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertThrowsError failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message(), file, line)
}
}
public func XCTAssertNoThrow<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.noThrow
let result = _XCTRunThrowableBlock { _ = try expression() }
switch result {
case .success:
return
case .failedWithError(let error):
_XCTRegisterFailure(true, "XCTAssertNoThrow failed: threw error \"\(error)\"", message(), file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message(), file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message(), file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
| apache-2.0 | c0f88f95bf7977ec510547c0e30702cf | 40.171812 | 256 | 0.708506 | 4.388754 | false | false | false | false |
marcelmueller/MyWeight | MyWeight/Screens/List/ListView.swift | 1 | 4947 | //
// ListView.swift
// MyWeight
//
// Created by Diogo on 09/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
public class ListView: UIView {
typealias Cell = TableViewCell<MassView, MassViewModel>
let tableView: UITableView
let addButton: TintButton = TintButton()
let buttonTopShadow = GradientView()
let style: StyleProvider = Style()
public var viewModel: ListViewModelProtocol = ListViewModel() {
didSet {
update()
}
}
override public init(frame: CGRect)
{
tableView = UITableView(frame: frame, style: .grouped)
super.init(frame: frame)
setUp()
update()
}
public var topOffset: CGFloat {
set(topOffset) {
topConstraint?.constant = topOffset
}
get {
return topConstraint?.constant ?? 0
}
}
var topConstraint: NSLayoutConstraint?
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUp()
{
let contentView = self
contentView.backgroundColor = style.backgroundColor
contentView.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = tableView.topAnchor.constraint(equalTo: contentView.topAnchor)
topConstraint?.isActive = true
tableView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
tableView.allowsSelection = false
tableView.registerCellClass(Cell.self)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 85
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = style.backgroundColor
tableView.separatorStyle = .none
contentView.addSubview(addButton)
addButton.translatesAutoresizingMaskIntoConstraints = false
let padding: CGFloat = style.grid * 2
addButton.topAnchor.constraint(equalTo: tableView.bottomAnchor).isActive = true
addButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding) .isActive = true
addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
addButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
addButton.addTarget(self,
action: #selector(ListView.buttonTap),
for: .touchUpInside)
contentView.addSubview(buttonTopShadow)
buttonTopShadow.translatesAutoresizingMaskIntoConstraints = false
buttonTopShadow.heightAnchor.constraint(equalToConstant: style.grid * 4).isActive = true
buttonTopShadow.leadingAnchor.constraint(equalTo: contentView.leadingAnchor) .isActive = true
buttonTopShadow.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
buttonTopShadow.bottomAnchor.constraint(equalTo: addButton.topAnchor).isActive = true
buttonTopShadow.colors = [style.backgroundColor, style.backgroundColor.withAlphaComponent(0)]
buttonTopShadow.locations = [0, 1]
buttonTopShadow.startPoint = CGPoint(x: 0.5, y: 1)
buttonTopShadow.endPoint = CGPoint(x: 0.5, y: 0)
}
func update()
{
addButton.title = viewModel.buttonTitle
tableView.reloadData()
if let emptyListViewModel = viewModel.emptyListViewModel {
let backgroundView = TitleDescriptionView()
backgroundView.viewModel = emptyListViewModel
tableView.backgroundView = backgroundView
} else {
tableView.backgroundView = nil
}
}
func buttonTap()
{
viewModel.didTapAction()
}
}
extension ListView: UITableViewDelegate, UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
public func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
{
return Int(viewModel.items)
}
public func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: Cell.defaultReuseIdentifier,
for: indexPath) as! Cell
cell.viewModel = viewModel.data(UInt(indexPath.row))
return cell
}
public func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat
{
return CGFloat.leastNormalMagnitude
}
}
| mit | d199b6e92b9dbc4ea39fda8f7de32841 | 30.909677 | 116 | 0.661747 | 5.532438 | false | false | false | false |
hxx0215/VPNOn | VPNOn/LTVPNDomainsViewController.swift | 1 | 1503 | //
// LTVPNDomainsViewController.swift
// VPNOn
//
// Created by Lex Tang on 1/28/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import VPNOnKit
@objc protocol LTVPNDomainsViewControllerDelegate {
optional func didTapSaveDomainsWithText(text: String)
}
class LTVPNDomainsViewController: UITableViewController
{
weak var delegate: LTVPNDomainsViewControllerDelegate?
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var textView: UITextView!
@IBAction func save(sender: AnyObject?) {
VPNManager.sharedManager.onDemandDomains = textView.text
if let d = delegate {
d.didTapSaveDomainsWithText?(textView.text)
}
popDetailViewController()
}
override func loadView() {
super.loadView()
let backgroundView = LTViewControllerBackground()
tableView.backgroundView = backgroundView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.text = VPNManager.sharedManager.onDemandDomains
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
delegate = nil
}
// MARK: - Navigation
func popDetailViewController() {
let topNavigationController = splitViewController!.viewControllers.last! as! UINavigationController
topNavigationController.popViewControllerAnimated(true)
}
}
| mit | 3d806b6310bc22d46c54c50bd069e42f | 25.839286 | 107 | 0.691284 | 5.273684 | false | false | false | false |
colemancda/NetworkObjectsUI | NetworkObjectsUI/NetworkObjectsUI/NetworkActivityIndicatorManager.swift | 2 | 3638 | //
// NetworkActivityIndicatorManager.swift
// NetworkObjectsUI
//
// Created by Alsey Coleman Miller on 1/30/15.
// Copyright (c) 2015 ColemanCDA. All rights reserved.
//
import Foundation
import UIKit
final public class NetworkActivityIndicatorManager {
// MARK: - Singleton
public static let sharedManager = NetworkActivityIndicatorManager()
// MARK: - Properties
public let URLSession: NSURLSession
public var managingNetworkActivityIndicator: Bool = false {
didSet {
if managingNetworkActivityIndicator == true {
if self.timer == nil {
self.timer = NSTimer(timeInterval: self.updateInterval, target: self, selector: "updateNetworkActivityIndicator", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
}
self.timer!.fire()
}
else {
self.timer?.invalidate()
self.timer = nil
}
}
}
public let updateInterval: NSTimeInterval
/** The minimum amount of time the activity indicator must be visible. Prevents blinks. */
public var minimumNetworkActivityIndicatorVisiblityInterval: NSTimeInterval
// MARK: - Private Properties
private var timer: NSTimer?
private var lastNetworkActivityIndicatorVisibleState: Bool = false
private var lastNetworkActivityIndicatorVisibleStateTransitionToTrue: NSDate?
// MARK: - Initialization
public init(URLSession: NSURLSession = NSURLSession.sharedSession(), updateInterval: NSTimeInterval = 0.001, minimumNetworkActivityIndicatorVisiblityInterval: NSTimeInterval = 1) {
self.URLSession = URLSession
self.updateInterval = updateInterval
self.minimumNetworkActivityIndicatorVisiblityInterval = minimumNetworkActivityIndicatorVisiblityInterval
}
// MARK: - Private Methods
@objc private func updateNetworkActivityIndicator() {
if self.lastNetworkActivityIndicatorVisibleStateTransitionToTrue != nil {
let timeInterval = NSDate().timeIntervalSinceDate(lastNetworkActivityIndicatorVisibleStateTransitionToTrue!)
if timeInterval < minimumNetworkActivityIndicatorVisiblityInterval {
return
}
else {
lastNetworkActivityIndicatorVisibleStateTransitionToTrue = nil
}
}
self.URLSession.getTasksWithCompletionHandler { (dataTasks: [NSURLSessionDataTask], uploadTasks: [NSURLSessionUploadTask], downloadTasks: [NSURLSessionDownloadTask]) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
let networkActivityIndicatorVisible = Bool(dataTasks.count)
if self.lastNetworkActivityIndicatorVisibleState == false && networkActivityIndicatorVisible == true {
self.lastNetworkActivityIndicatorVisibleStateTransitionToTrue = NSDate()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = networkActivityIndicatorVisible
self.lastNetworkActivityIndicatorVisibleState = networkActivityIndicatorVisible
})
}
}
} | mit | 95309e2b1de10e00e0e00954f184a372 | 34.676471 | 184 | 0.62177 | 6.996154 | false | false | false | false |
Harry-L/5-3-1 | ios-charts-master/Charts/Classes/Components/ChartYAxis.swift | 4 | 7575 | //
// ChartYAxis.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/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 UIKit
/// Class representing the y-axis labels settings and its entries.
/// Be aware that not all features the YLabels class provides are suitable for the RadarChart.
/// Customizations that affect the value range of the axis need to be applied before setting data for the chart.
public class ChartYAxis: ChartAxisBase
{
@objc
public enum YAxisLabelPosition: Int
{
case OutsideChart
case InsideChart
}
/// Enum that specifies the axis a DataSet should be plotted against, either Left or Right.
@objc
public enum AxisDependency: Int
{
case Left
case Right
}
public var entries = [Double]()
public var entryCount: Int { return entries.count; }
/// the number of y-label entries the y-labels should have, default 6
private var _labelCount = Int(6)
/// indicates if the top y-label entry is drawn or not
public var drawTopYLabelEntryEnabled = true
/// if true, the y-labels show only the minimum and maximum value
public var showOnlyMinMaxEnabled = false
/// flag that indicates if the axis is inverted or not
public var inverted = false
/// if true, the y-label entries will always start at zero
public var startAtZeroEnabled = true
/// if true, the set number of y-labels will be forced
public var forceLabelsEnabled = false
/// the formatter used to customly format the y-labels
public var valueFormatter: NSNumberFormatter?
/// the formatter used to customly format the y-labels
internal var _defaultValueFormatter = NSNumberFormatter()
/// A custom minimum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMin()` to undo this.
/// Do not forget to set startAtZeroEnabled = false if you use this method.
/// Otherwise, the axis-minimum value will still be forced to 0.
public var customAxisMin = Double.NaN
/// Set a custom maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMax()` to undo this.
public var customAxisMax = Double.NaN
/// axis space from the largest value to the top in percent of the total axis range
public var spaceTop = CGFloat(0.1)
/// axis space from the smallest value to the bottom in percent of the total axis range
public var spaceBottom = CGFloat(0.1)
public var axisMaximum = Double(0)
public var axisMinimum = Double(0)
/// the total range of values this axis covers
public var axisRange = Double(0)
/// the position of the y-labels relative to the chart
public var labelPosition = YAxisLabelPosition.OutsideChart
/// the side this axis object represents
private var _axisDependency = AxisDependency.Left
/// the minimum width that the axis should take
///
/// **default**: 0.0
public var minWidth = CGFloat(0)
/// the maximum width that the axis can take.
/// use zero for disabling the maximum
///
/// **default**: 0.0 (no maximum specified)
public var maxWidth = CGFloat(0)
public override init()
{
super.init()
_defaultValueFormatter.minimumIntegerDigits = 1
_defaultValueFormatter.maximumFractionDigits = 1
_defaultValueFormatter.minimumFractionDigits = 1
_defaultValueFormatter.usesGroupingSeparator = true
self.yOffset = 0.0
}
public init(position: AxisDependency)
{
super.init()
_axisDependency = position
_defaultValueFormatter.minimumIntegerDigits = 1
_defaultValueFormatter.maximumFractionDigits = 1
_defaultValueFormatter.minimumFractionDigits = 1
_defaultValueFormatter.usesGroupingSeparator = true
self.yOffset = 0.0
}
public var axisDependency: AxisDependency
{
return _axisDependency
}
public func setLabelCount(count: Int, force: Bool)
{
_labelCount = count
if (_labelCount > 25)
{
_labelCount = 25
}
if (_labelCount < 2)
{
_labelCount = 2
}
forceLabelsEnabled = force
}
/// the number of label entries the y-axis should have
/// max = 25,
/// min = 2,
/// default = 6,
/// be aware that this number is not fixed and can only be approximated
public var labelCount: Int
{
get
{
return _labelCount
}
set
{
setLabelCount(newValue, force: false);
}
}
/// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically.
public func resetCustomAxisMin()
{
customAxisMin = Double.NaN
}
/// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically.
public func resetCustomAxisMax()
{
customAxisMax = Double.NaN
}
public func requiredSize() -> CGSize
{
let label = getLongestLabel() as NSString
var size = label.sizeWithAttributes([NSFontAttributeName: labelFont])
size.width += xOffset * 2.0
size.height += yOffset * 2.0
size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width))
return size
}
public func getRequiredHeightSpace() -> CGFloat
{
return requiredSize().height + yOffset
}
public override func getLongestLabel() -> String
{
var longest = ""
for (var i = 0; i < entries.count; i++)
{
let text = getFormattedLabel(i)
if (longest.characters.count < text.characters.count)
{
longest = text
}
}
return longest
}
/// - returns: the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set).
public func getFormattedLabel(index: Int) -> String
{
if (index < 0 || index >= entries.count)
{
return ""
}
return (valueFormatter ?? _defaultValueFormatter).stringFromNumber(entries[index])!
}
/// - returns: true if this axis needs horizontal offset, false if no offset is needed.
public var needsOffset: Bool
{
if (isEnabled && isDrawLabelsEnabled && labelPosition == .OutsideChart)
{
return true
}
else
{
return false
}
}
public var isInverted: Bool { return inverted; }
public var isStartAtZeroEnabled: Bool { return startAtZeroEnabled; }
/// - returns: true if focing the y-label count is enabled. Default: false
public var isForceLabelsEnabled: Bool { return forceLabelsEnabled }
public var isShowOnlyMinMaxEnabled: Bool { return showOnlyMinMaxEnabled; }
public var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled; }
} | mit | 5dde46a8b0b1af82a65a79cba1e8a7b5 | 29.796748 | 145 | 0.631419 | 5.019881 | false | false | false | false |
wuzhenli/MyDailyTestDemo | swiftTest/_0304_Class_Struct.playground/Contents.swift | 1 | 16000 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print(str)
class Person {
var age: Int = 12
var name: String?
var weight: Float?
}
/* 类型的 类型:值 / 引用类型
结构体和枚举是值类型
值类型被赋予给一个变量、常量或者被传递给一个函数的时候,其值会被拷贝。
类是引用类型
与值类型不同,引用类型在被赋予到一个变量、常量或者被传递到一个函数时,其值不会被拷贝。因此,引用的是已存在的实例本身而不是其拷贝。
*/
/*
恒等运算符
因为类是引用类型,有可能有多个常量和变量在幕后同时引用同一个类实例。(对于结构体和枚举来说,这并不成立。因为它们作为值类型,在被赋予到常量、变量或者传递到函数时,其值总是会被拷贝。)
如果能够判定两个常量或者变量是否引用同一个类实例将会很有帮助。为了达到这个目的,Swift 内建了两个恒等运算符:
等价于(===)
不等价于(!==)
运用这两个运算符检测两个常量或者变量是否引用同一个实例
*/
let p1 = Person()
let p2 = p1
//if p1 === p2 {
// print("p1 p2是同一个实例")
//} else {
// print("p1 p2不是 同一个实例")
//}
/* copy
字符串、数组、和字典类型的赋值与复制行为
Swift 中,许多基本类型,诸如String,Array和Dictionary类型均以结构体的形式实现。这意味着被赋值给新的常量或变量,或者被传入函数或方法中时,它们的值会被拷贝。
Objective-C 中NSString,NSArray和NSDictionary类型均以类的形式实现,而并非结构体。它们在被赋值或者被传入函数或方法时,不会发生值拷贝,而是传递现有实例的引用。
*/
/* lazy
如果一个被标记为 lazy 的属性在没有初始化时就同时被多个线程访问,则无法保证该属性只会被初始化一次。
*/
/* property
Swift 中的属性没有对应的实例变量,属性的后端存储也无法直接访问。这就避免了不同场景下访问方式的困扰,同时也将属性的定义简化成一个语句。属性的全部信息——包括命名、类型和内存管理特征——都在唯一一个地方(类型定义中)定义。
*/
struct Cube {
var width : Float
var height: Float
var length = 0.0
var colume : Float {
get {
return width * height * Float(length)
}
}
}
var c = Cube(width: 3, height: 2, length: 2)
//print("\(c.colume)")
/* 属性观察器
注意
父类的属性在子类的构造器中被赋值时,它在父类中的 willSet 和 didSet 观察器会被调用,随后才会调用子类的观察器。
在父类初始化方法调用之前,子类给属性赋值时,观察器不会被调用。 有关构造器代理的更多信息,请参考值类型的构造器代理和类的构造器代理规则。
*/
class StepCount {
var count: Int = 0 {
willSet {
print("newValue:\(newValue)")
}
didSet {
print("oldValue:\(oldValue)")
}
}
}
var sCount = StepCount()
//sCount.count = 1
/* 类型属性
必须给存储型类型属性指定默认值,因为类型本身没有构造器,
存储型类型属性是延迟初始化的,它们只有在第一次被访问的时候才会被初始化。即使它们被多个线程同时访问,系统也保证只会对其进行一次初始化,并且不需要对其使用 lazy 修饰符。
*/
class Room {
static var personNum: Int = 0;
}
// MARK http://wiki.jikexueyuan.com/project/swift/chapter2/11_Methods.html
/**
* 结构体、枚举 类型的方法内部不能修改 成员变量的值,如果想修改成员的值,请加 mutating 关键字
* 变量可以钓鱼mutating方法,常量不可以
*/
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
func addX() -> Void { // 结构体、枚举 类型的方法内部不能修改 成员变量的值,如果想修改成员的值,请加 mutating 关键字
print(x)
}
}
var p = Point(x: 12.0, y: 12.0)
p.moveByX(deltaX: 1.2, y: 1.2)
/**
* 类方法
* static关键字定义,子类不能重写父类方法
* class关键字定义类方法,子类可以重写父类方法
*/
class SomeClass {
static var count: Int = 100
static func classTypeMehtod() {
print("classType Method ----类方法")
}
class func someTypeMethod() {
// 在这里实现类型方法
print("someTypeMethod : 父类")
}
}
class SomeSunClass : SomeClass {
override static func someTypeMethod() {
print("someTypeMethod : 子类")
classTypeMehtod() // 类方法中直接钓用类方法、类成员
print("count:\(count)")
}
}
//let someClass_1 = SomeSunClass()
//SomeSunClass.classTypeMehtod()
//SomeSunClass.someTypeMethod()
//
//var dicTest = ["a":1, "b":2, "c":3]
//print(dicTest["aa"] ?? "none")
//print(dicTest["bb"] ?? "no bb")
//MARK 构造器
/* 构造器
注意
当你为存储型属性设置默认值或者在构造器中为其赋值时,它们的值是被直接设置的,不会触发任何属性观察者。
*/
struct InitStruct {
var count: Int
init(outCount inCount:Int) {
self.count = inCount
}
// init( count:Int) {
// self.count = count
// }
init(_ count:Int) {
self.count = count
}
}
//var initS_1 = InitStruct(count: 1)
class InitClass {
let text: String
init(t: String) {
self.text = t
}
}
// 学习点 http://wiki.jikexueyuan.com/project/swift/chapter2/14_Initialization.html
// MARK: 指定构造器和便利构造器
/*
* 指定构造器
init(parameters) {
statements
}
* 便利构造器
convenience init(parameters) {
statements
}
* 类的构造器代理规则
为了简化指定构造器和便利构造器之间的调用关系,Swift 采用以下三条规则来限制构造器之间的代理调用:
规则 1:指定构造器必须调用其直接父类的的指定构造器。
规则 2:便利构造器必须调用同类中定义的其它构造器。
规则 3:便利构造器必须最终导致一个指定构造器被调用。
一个更方便记忆的方法是:
指定构造器必须总是向上代理
便利构造器必须总是横向代理
*** 子类中“重写”一个父类便利构造器时,不需要加override前缀 ***
* 两段式构造过程
Swift 中类的构造过程包含两个阶段。第一个阶段,每个存储型属性被引入它们的类指定一个初始值。当每个存储型属性的初始值被确定后,第二阶段开始,它给每个类一次机会,在新实例准备使用之前进一步定制它们的存储型属性。
* 你可以用非可失败构造器重写可失败构造器,但反过来却不行。
*/
/* 闭包初始化属性
* 闭包执行时,实例的其它部分都还没有初始化。这意味着你不能在闭包里访问其它属性,即使这些属性有默认值。
* 同样,你也不能使用隐式的self属性,或者调用任何实例方法。
*/
class ClassBiBao {
var name: String = {
return "闭包初始化"
}() // () : 代表立即执行闭包
}
// MARK : 析构过程
// MARK : http://wiki.jikexueyuan.com/project/swift/chapter2/15_Deinitialization.html
/*
每个类最多只能有一个析构器,而且析构器不带任何参数
deinit {
// 执行析构过程
}
子类继承了父类的析构器,并且在子类析构器实现的最后,父类的析构器会被自动调用。
即使子类没有提供自己的析构器,父类的析构器也同样会被调用。
*/
// MARK : ARC
// MARK : http://wiki.jikexueyuan.com/project/swift/chapter2/16_Automatic_Reference_Counting.html
/*
* 当 ARC 设置弱引用为nil时,属性观察不会被触发。
* 无主引用通常都被期望拥有值。不过 ARC 无法在实例被销毁后将无主引用设为nil,因为非可选类型的变量不允许被赋值为nil。
* 注意
Swift 有如下要求:只要在闭包内使用self的成员,就要用self.someProperty或者self.someMethod()(而不只是someProperty或someMethod())。这提醒你可能会一不小心就捕获了self。
*/
// MARK : 错误处理
/*
* Swift 中的错误处理并不涉及解除调用栈,这是一个计算代价高昂的过程。就此而言,throw语句的性能特性是可以和return语句相媲美的。
*/
func canThrowErrors() throws -> String {
return "error";
}
func cannotThrowErrors() -> String {
return "error";
}
enum ErrorDef : Error {
case ErrorOne
case ErrorTwo
case ErrorThree
}
func testThrows() throws -> String {
throw ErrorDef.ErrorOne
// return "string ---"
}
//let x = try? testThrows()
//print(x ?? "error---")
let y: String?
do {
y = try testThrows()
print("none error")
} catch {
// print("throw error")
}
/*
* try!来禁用错误传递
有时你知道某个throwing函数实际上在运行时是不会抛出错误的,在这种情况下,你可以在表达式前面写try!来禁用错误传递
// defer
print("----- defer -----")
func deferTest() {
print("begin defer")
defer {
print("this is defer 1")
}
print("center defer")
defer {
print("this is defer 2")
}
print("END defer")
}
deferTest()
*/
// MARK : 类型转换
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
var movieCount: Int = 0
var songCount: Int = 0
var mediaCount = 0
for item in library {
if item is MediaItem {
mediaCount += 1
}
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
//print("mediaCount:\(mediaCount)") // is : 判断是否某各类,或其父类
//print("song:\(songCount) moveCount:\(movieCount)")
//for item in library {
// if let song = item as? Song {
// print("SONG \(song.artist) \(song.name)")
// } else if let movie = item as? Movie {
// print(movie.director)
// }
//}
/*
Swift 为不确定类型提供了两种特殊的类型别名:
Any 可以表示任何类型,包括函数类型。
AnyObject 可以表示任何类类型的实例。
*/
var things = [Any]()
things.append(0)
things.append(0.00)
things.append(12.32)
things.append("things")
//print(things)
//for thing in things {
// switch thing {
// case 0 as Int:
// print("zero as an Int")
// case 0 as Double:
// print("zero as a Double")
// case let someInt as Int:
// print("an integer value of \(someInt)")
// case let someDouble as Double where someDouble > 0:
// print("a positive double value of \(someDouble)")
// case is Double:
// print("some other double value that I don't want to print")
// case let someString as String:
// print("a string value of \"\(someString)\"")
// case let (x, y) as (Double, Double):
// print("an (x, y) point at \(x), \(y)")
// case let movie as Movie:
// print("a movie called '\(movie.name)', dir. \(movie.director)")
// default:
// print("something else")
// }
//}
let typeAny: Int? = 22
things.append(typeAny) // 警告 ⚠️
things.append(typeAny as Any)
/* 嵌套类型
*
*/
struct BlackjackCard {
// 嵌套的 Suit 枚举
enum Suit: Character {
case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
}
// 嵌套的 Rank 枚举
enum Rank: Int {
case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King, Ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .Ace:
return Values(first: 1, second: 11)
case .Jack, .Queen, .King:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}
// BlackjackCard 的属性和方法
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
/* 扩展和 Objective-C 中的分类类似。(与 Objective-C 不同的是,Swift 的扩展没有名字。)
Swift 中的扩展可以:
添加计算型属性和计算型类型属性
* 扩展可以添加新的计算型属性,但是不可以添加存储型属性,也不可以为已有属性添加属性观察器。
定义实例方法和类型方法
提供新的构造器
定义下标
定义和使用新的嵌套类型
使一个已有类型符合某个协议
在 Swift 中,你甚至可以对协议进行扩展,提供协议要求的实现,或者添加额外的功能,从而可以让符合协议的类型拥有这些功能。你可以从协议扩展获取更多的细节。
------------------------
* 扩展可以为一个类型添加新的功能,但是不能重写已有的功能。
* 扩展能为类添加新的便利构造器,但是它们不能为类添加新的指定构造器或析构器。
*/
struct Size {
var width = 0.0, height = 0.0
}
struct Point_1 {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point_1()
var size = Size()
}
extension Rect {
init(center: Point_1, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point_1(x: originX, y: originY), size: size)
}
}
//嵌套类型
//扩展可以为已有的类、结构体和枚举添加新的嵌套类型:
extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind: Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
default:
return .Negative
}
}
}
// MARK : 高级运算符
/*
按位取反运算符
按位取反运算符(~)可以对一个数值的全部比特位进行取反:
*/
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // 等于 0b11110000
/*
按位与运算符
按位与运算符(&): 只有当两个数的对应位都为 1 的时候,新数的对应位才为 1:
*/
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
/*
按位异或运算符
按位异或运算符(^): 当两个数的对应位不相同时,新数的对应位就为 1:
*/
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // 等于 00010001
/*
将一个整数左移一位,等价于将这个数乘以 2,同样地,将一个整数右移一位,等价于将这个数除以 2。
*/
| apache-2.0 | 1f1f7f76da4a69a97f7d1467ea8d42d5 | 19.213382 | 124 | 0.622294 | 2.751169 | false | false | false | false |
Hyfenglin/bluehouseapp | iOS/post/post/Comment.swift | 1 | 559 | //
// Comment.swift
// post
//
// Created by Derek Li on 14-10-8.
// Copyright (c) 2014年 Derek Li. All rights reserved.
//
import Foundation
class Comment{
var id:Int = 0
var modified:String?
var created:String?
var content:String?
init(){
}
init(dic:NSDictionary){
self.id = dic.objectForKey("id") as Int
self.modified = dic.objectForKey("modified") as? String
self.content = dic.objectForKey("content") as? String
self.created = dic.objectForKey("created") as? String
}
} | mit | f257929e027eca48a29b01173fa1f1b7 | 20.461538 | 63 | 0.610413 | 3.688742 | false | false | false | false |
MrZoidberg/metapp | metapp/Pods/RxDataSources/Sources/DataSources+Rx/RxCollectionViewSectionedAnimatedDataSource.swift | 13 | 3590 | //
// RxCollectionViewSectionedAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
/*
This is commented becuse collection view has bugs when doing animated updates.
Take a look at randomized sections.
*/
open class RxCollectionViewSectionedAnimatedDataSource<S: AnimatableSectionModelType>
: CollectionViewSectionedDataSource<S>
, RxCollectionViewDataSourceType {
public typealias Element = [S]
public var animationConfiguration = AnimationConfiguration()
// For some inexplicable reason, when doing animated updates first time
// it crashes. Still need to figure out that one.
var dataSet = false
private let disposeBag = DisposeBag()
// This subject and throttle are here
// because collection view has problems processing animated updates fast.
// This should somewhat help to alleviate the problem.
private let partialUpdateEvent = PublishSubject<(UICollectionView, Event<Element>)>()
public override init() {
super.init()
self.partialUpdateEvent
// so in case it does produce a crash, it will be after the data has changed
.observeOn(MainScheduler.asyncInstance)
// Collection view has issues digesting fast updates, this should
// help to alleviate the issues with them.
.throttle(0.5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] event in
self?.collectionView(event.0, throttledObservedEvent: event.1)
})
.addDisposableTo(disposeBag)
}
/**
This method exists because collection view updates are throttled because of internal collection view bugs.
Collection view behaves poorly during fast updates, so this should remedy those issues.
*/
open func collectionView(_ collectionView: UICollectionView, throttledObservedEvent event: Event<Element>) {
UIBindingObserver(UIElement: self) { dataSource, newSections in
let oldSections = dataSource.sectionModels
do {
let differences = try differencesForSectionedView(oldSections, finalSections: newSections)
for difference in differences {
dataSource.setSections(difference.finalSections)
collectionView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration)
}
}
catch let e {
#if DEBUG
print("Error while binding data animated: \(e)\nFallback to normal `reloadData` behavior.")
rxDebugFatalError(e)
#endif
self.setSections(newSections)
collectionView.reloadData()
}
}.on(event)
}
open func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Element>) {
UIBindingObserver(UIElement: self) { dataSource, newSections in
#if DEBUG
self._dataSourceBound = true
#endif
if !self.dataSet {
self.dataSet = true
dataSource.setSections(newSections)
collectionView.reloadData()
}
else {
let element = (collectionView, observedEvent)
dataSource.partialUpdateEvent.on(.next(element))
}
}.on(observedEvent)
}
}
| mpl-2.0 | 406f0c73ca6f9604e1b1cf056dde6c19 | 36.778947 | 119 | 0.648649 | 5.581649 | false | false | false | false |
wikimedia/wikipedia-ios | Widgets/Widgets/FeaturedArticleWidget.swift | 1 | 8115 | import SwiftUI
import WidgetKit
import WMF
import UIKit
// MARK: - Widget
struct FeaturedArticleWidget: Widget {
private let kind: String = WidgetController.SupportedWidget.featuredArticle.identifier
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: FeaturedArticleProvider(), content: { entry in
FeaturedArticleView(entry: entry)
})
.configurationDisplayName(FeaturedArticleWidget.LocalizedStrings.widgetTitle)
.description(FeaturedArticleWidget.LocalizedStrings.widgetDescription)
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
// MARK: - Timeline Entry
struct FeaturedArticleEntry: TimelineEntry {
// MARK: - Properties
var date: Date
var content: WidgetFeaturedContent?
var fetchError: WidgetContentFetcher.FetcherError?
// MARK: - Computed Properties
var hasDisplayableContent: Bool {
return fetchError == nil && content?.featuredArticle != nil
}
var fetchedLanguageCode: String? {
return content?.featuredArticle?.languageCode
}
var title: String {
return (content?.featuredArticle?.displayTitle as NSString?)?.wmf_stringByRemovingHTML() ?? ""
}
var description: String {
return content?.featuredArticle?.description ?? ""
}
var extract: String {
return content?.featuredArticle?.extract ?? ""
}
var layoutDirection: LayoutDirection {
if let direction = content?.featuredArticle?.languageDirection {
return direction == "rtl" ? .rightToLeft : .leftToRight
}
return .leftToRight
}
var contentURL: URL? {
guard let page = content?.featuredArticle?.contentURL.desktop.page else {
return nil
}
return URL(string: page)
}
var imageData: Data? {
return content?.featuredArticle?.thumbnailImageSource?.data
}
}
// MARK: - Timeline Provider
struct FeaturedArticleProvider: TimelineProvider {
typealias Entry = FeaturedArticleEntry
func placeholder(in context: Context) -> FeaturedArticleEntry {
return FeaturedArticleEntry(date: Date(), content: nil)
}
func getSnapshot(in context: Context, completion: @escaping (FeaturedArticleEntry) -> Void) {
WidgetController.shared.fetchFeaturedContent(isSnapshot: context.isPreview) { result in
let currentDate = Date()
switch result {
case .success(let featuredContent):
completion(FeaturedArticleEntry(date: currentDate, content: featuredContent))
case .failure(let fetchError):
completion(FeaturedArticleEntry(date: currentDate, content: nil, fetchError: fetchError))
}
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<FeaturedArticleEntry>) -> Void) {
WidgetController.shared.fetchFeaturedContent { result in
let currentDate = Date()
switch result {
case .success(let featuredContent):
completion(Timeline(entries: [FeaturedArticleEntry(date: currentDate, content: featuredContent)], policy: .after(currentDate.randomDateShortlyAfterMidnight() ?? currentDate)))
case .failure(let fetchError):
completion(Timeline(entries: [FeaturedArticleEntry(date: currentDate, content: nil, fetchError: fetchError)], policy: .atEnd))
}
}
}
}
// MARK: - View
struct FeaturedArticleView: View {
@Environment(\.widgetFamily) private var widgetFamily
@Environment(\.colorScheme) private var colorScheme
var entry: FeaturedArticleEntry
var headerCaptionText: String {
switch widgetFamily {
case .systemLarge:
return FeaturedArticleWidget.LocalizedStrings.fromLanguageWikipediaTextFor(languageCode: entry.fetchedLanguageCode)
default:
return FeaturedArticleWidget.LocalizedStrings.widgetTitle
}
}
var headerTitleText: String {
switch widgetFamily {
case .systemLarge:
return FeaturedArticleWidget.LocalizedStrings.widgetTitle
default:
return entry.title
}
}
var backgroundImage: UIImage? {
guard let imageData = entry.imageData else {
return nil
}
return UIImage(data: imageData)
}
// MARK: - Nested Views
@ViewBuilder
var content: some View {
switch widgetFamily {
case .systemLarge:
largeWidgetContent
default:
smallWidgetContent
}
}
var smallWidgetContent: some View {
headerData
.background(Color(colorScheme == .light ? Theme.light.colors.paperBackground : Theme.dark.colors.paperBackground))
}
var largeWidgetContent: some View {
GeometryReader { proxy in
VStack(spacing: 0) {
headerData
.frame(height: proxy.size.height / 2.25)
.clipped()
bodyData
}
}
.background(Color(colorScheme == .light ? Theme.light.colors.paperBackground : Theme.dark.colors.paperBackground))
}
var headerData: some View {
ZStack {
headerBackground
VStack(alignment: .leading, spacing: 4) {
Spacer()
HStack {
Text(headerCaptionText)
.font(.caption2)
.fontWeight(.bold)
.foregroundColor(.white)
.readableShadow(intensity: 0.8)
Spacer()
}
HStack {
Text(headerTitleText)
.font(.headline)
.foregroundColor(.white)
.readableShadow(intensity: 0.8)
Spacer()
}
}
.padding()
.background(
Rectangle()
.foregroundColor(.black)
.mask(LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .center, endPoint: .bottom))
.opacity(0.35)
)
}
}
var bodyData: some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(entry.title)
.foregroundColor(Color(colorScheme == .light ? Theme.light.colors.primaryText : Theme.dark.colors.primaryText))
.font(.custom("Georgia", size: 21, relativeTo: .title))
Spacer()
}
HStack {
Text(entry.description)
.foregroundColor(Color(colorScheme == .light ? Theme.light.colors.secondaryText : Theme.dark.colors.secondaryText))
.font(.caption)
Spacer()
}
Spacer()
.frame(height: 8)
HStack {
Text(entry.extract)
.foregroundColor(Color(colorScheme == .light ? Theme.light.colors.primaryText : Theme.dark.colors.primaryText))
.font(.caption)
.lineLimit(5)
.lineSpacing(4)
.truncationMode(.tail)
}
}
.padding()
}
@ViewBuilder
var headerBackground: some View {
GeometryReader { proxy in
if let backgroundImage = backgroundImage {
Image(uiImage: backgroundImage)
.resizable()
.aspectRatio(contentMode: .fill)
} else {
ZStack {
Rectangle()
.foregroundColor(Color(UIColor("318CDB")))
Text(entry.extract)
.font(.headline)
.fontWeight(.semibold)
.lineSpacing(6)
.foregroundColor(Color.black.opacity(0.15))
.frame(width: proxy.size.width * 1.25, height: proxy.size.height * 2, alignment: .topLeading)
.padding(EdgeInsets(top: 16, leading: 10, bottom: 0, trailing: 0))
}
}
}
}
func noContent(message: String) -> some View {
Rectangle()
.foregroundColor(Color(UIColor.base30))
.overlay(
Text(message)
.font(.caption)
.bold()
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
.foregroundColor(.white)
.padding()
)
}
@ViewBuilder
var widgetBody: some View {
if entry.hasDisplayableContent {
content
.overlay(FeaturedArticleOverlayView())
} else if entry.fetchError == .unsupportedLanguage {
noContent(message: FeaturedArticleWidget.LocalizedStrings.widgetLanguageFailure)
} else {
noContent(message: FeaturedArticleWidget.LocalizedStrings.widgetContentFailure)
}
}
// MARK: - Body
var body: some View {
widgetBody
.widgetURL(entry.contentURL)
.environment(\.layoutDirection, entry.layoutDirection)
.flipsForRightToLeftLayoutDirection(true)
}
}
struct FeaturedArticleOverlayView: View {
var body: some View {
VStack(alignment: .trailing) {
HStack(alignment: .top) {
Spacer()
Image("W")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 16, alignment: .trailing)
.foregroundColor(.white)
.padding(EdgeInsets(top: 16, leading: 0, bottom: 0, trailing: 16))
.readableShadow()
}
Spacer()
.readableShadow()
.padding(EdgeInsets(top: 0, leading: 16, bottom: 16, trailing: 45))
}
.foregroundColor(.white)
}
}
| mit | 2d96c1ec691a2746ee545655cc94d32d | 25.262136 | 179 | 0.710043 | 3.715659 | false | false | false | false |
PGSSoft/AutoMate | AutoMateTests/TestLauncherTests.swift | 1 | 2818 | //
// TestLauncherTests.swift
// AutoMate
//
// Created by Joanna Bednarz on 03/06/16.
// Copyright © 2016 PGS Software. All rights reserved.
//
import XCTest
@testable import AutoMate
class TestLauncherTests: XCTestCase {
// MARK: Properties
let argument = LaunchOptionsFactory.multiLanguageLaunchArgument
let environment = LaunchOptionsFactory.futureEventsLaunchEnvironment
// MARK: Tests
func testConfigureCleanApplicationWithLaunchOptions() {
let application = ApplicationsFactory.cleanApplication
let launcher = TestLauncher(options: [argument, environment])
let configApplication = launcher.configure(application)
XCTAssertEqual(configApplication.launchArguments, argument.launchArguments!)
XCTAssertEqual(configApplication.launchEnvironment, environment.launchEnvironments!)
}
func testConfigureCleanApplicationWithDoubledLaunchOptions() {
let application = ApplicationsFactory.cleanApplication
let launcher = TestLauncher(options: [argument, argument, environment, environment])
let configApplication = launcher.configure(application)
XCTAssertEqual(configApplication.launchArguments, argument.launchArguments!)
XCTAssertEqual(configApplication.launchEnvironment, environment.launchEnvironments!)
}
func testConfigureSetUpApplicationWithoutLaunchOptions() {
let application = ApplicationsFactory.configuredApplication
let launcher = TestLauncher()
let configApplication = launcher.configure(application)
XCTAssertEqual(configApplication.launchArguments, application.launchArguments)
XCTAssertEqual(configApplication.launchEnvironment, application.launchEnvironment)
}
func testConfigureSetUpApplicationWithLaunchOptions() {
let application = ApplicationsFactory.configuredApplication
let launcher = TestLauncher(options: [argument, environment])
let configApplication = launcher.configure(application)
var argumentsSetUp = application.launchArguments
argumentsSetUp += argument.launchArguments!
var environmentSetUp = application.launchEnvironment
environmentSetUp.unionInPlace(environment.launchEnvironments!)
XCTAssertEqual(configApplication.launchArguments, argumentsSetUp)
XCTAssertEqual(configApplication.launchEnvironment, environmentSetUp)
}
func testConfigureLauncherHelperMethod() {
let application = ApplicationsFactory.cleanApplication
let configApplication = TestLauncher.configure(application, withOptions: [argument, environment])
XCTAssertEqual(configApplication.launchArguments, argument.launchArguments!)
XCTAssertEqual(configApplication.launchEnvironment, environment.launchEnvironments!)
}
}
| mit | 4490833e2223b85db5f859f270ead894 | 41.044776 | 105 | 0.770323 | 5.772541 | false | true | false | false |
CPC-Coder/CPCBannerView | Example/CPCBannerView/CPCBannerView/Custom/CPCBannerViewCustom.swift | 2 | 1916 | //
// CPCBannerViewDefault.swift
// bannerView
//
// Created by 鹏程 on 17/7/5.
// Copyright © 2017年 pengcheng. All rights reserved.
//
/*-------- 温馨提示 --------*/
/*
CPCBannerViewDefault --> collectionView上有lab (所有cell共享控件)
CPCBannerViewCustom --> 每个cell上都有lab(cell都有独有控件)
CPCBannerViewTextOnly --> 只有文字
*/
/*-------- 温馨提示 --------*/
import UIKit
enum CPCBannerViewCustomType{
case img,text,imgAndText
}
class CPCBannerViewCustom: CPCBaseBannerView {
var type : CPCBannerViewCustomType = .img{
didSet{
if type == .text {
scrollDirection = .vertical
pageControl.isHidden = true
} else {
scrollDirection = .horizontal
pageControl.isHidden = false
}
}
}
let cellID = "CPCBannerViewDefaultCellID"
override init(delegate: CPCBannerViewDelegate) {
super.init(delegate: delegate)
backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 重写父类方法
override func registerCell(collectionView: UICollectionView) {
collectionView.register(CPCBannerViewCustomCell.self, forCellWithReuseIdentifier: cellID)
}
override func dequeueReusableCell(collectionView: UICollectionView, indexPath: IndexPath) -> (UICollectionViewCell) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CPCBannerViewCustomCell
cell.type = type
return cell
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| mit | b96a99074e4552d07b48753d5fa95c85 | 21.378049 | 126 | 0.584196 | 5.013661 | false | false | false | false |
Eonil/EditorLegacy | Modules/Editor/Sources/ProtoUIComponents/LayoutConstraint.swift | 1 | 3767 | //
// LayoutConstraint.swift
// RustCodeEditor
//
// Created by Hoon H. on 11/10/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Foundation
import AppKit
struct LayoutConstraint {
// struct Expression {
// let multiplier:CGFloat
// let constant:CGFloat
// }
//
// static func setWidthOfView(view: NSView, equalsToValue: CGFloat) -> NSLayoutConstraint {
// return NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: CGFloat, constant: CGFloat)
// }
}
struct LayoutExpression {
let argument:LayoutArgument
let multiplier:CGFloat
let constant:CGFloat
}
typealias LayoutArgument = (view: NSView, attribute:NSLayoutAttribute)
let width = NSLayoutAttribute.Width
let height = NSLayoutAttribute.Height
let centerX = NSLayoutAttribute.CenterX
let centerY = NSLayoutAttribute.CenterY
let left = NSLayoutAttribute.Left
let right = NSLayoutAttribute.Right
let top = NSLayoutAttribute.Top
let bottom = NSLayoutAttribute.Bottom
infix operator .. {
precedence 255
}
infix operator ~~ {
precedence 1
}
func .. (left:NSView, right:NSLayoutAttribute) -> LayoutArgument {
return (left,right)
}
func .. (left:NSViewController, right:NSLayoutAttribute) -> LayoutArgument {
return (left.view,right)
}
func ~~ (left:NSLayoutConstraint, right:NSLayoutPriority) -> NSLayoutConstraint {
let c1 = NSLayoutConstraint(item: left.firstItem, attribute: left.firstAttribute, relatedBy: left.relation, toItem: left.secondItem, attribute: left.secondAttribute, multiplier: left.multiplier, constant: left.constant)
c1.priority = right
return c1
}
func * (left:LayoutArgument, right:CGFloat) -> LayoutExpression {
return LayoutExpression(argument: left, multiplier: right, constant: 0)
}
func + (left:LayoutExpression, right:CGFloat) -> LayoutExpression {
return LayoutExpression(argument: left.argument, multiplier: left.multiplier, constant: right)
}
func == (left:LayoutArgument, right:LayoutExpression) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.Equal, toItem: right.argument.view, attribute: right.argument.attribute, multiplier: right.multiplier, constant: right.constant)
}
func >= (left:LayoutArgument, right:LayoutExpression) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: right.argument.view, attribute: right.argument.attribute, multiplier: right.multiplier, constant: right.constant)
}
func <= (left:LayoutArgument, right:LayoutExpression) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: right.argument.view, attribute: right.argument.attribute, multiplier: right.multiplier, constant: right.constant)
}
func == (left:LayoutArgument, right:CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: right)
}
func >= (left:LayoutArgument, right:CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: right)
}
func <= (left:LayoutArgument, right:CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(item: left.view, attribute: left.attribute, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: right)
}
| mit | 01d17612ca795c38a43e70475becf622 | 38.652632 | 240 | 0.787364 | 4.037513 | false | false | false | false |
square/wire | wire-library/wire-runtime-swift/src/test/swift/JSONStringTests.swift | 1 | 1999 | /*
* Copyright 2020 Square Inc.
*
* 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 XCTest
@testable import Wire
final class JsonStringTests: XCTestCase {
struct SupportedTypes : Codable, Equatable {
@JSONString
var a: Int64
@JSONString
var b: UInt64
@JSONString
var c: [Int64]
@JSONString
var d: [UInt64]
@JSONString
var e: Int64?
@JSONString
var f: Int64?
@JSONString
var g: UInt64?
@JSONString
var h: UInt64?
}
func testSupportedTypes() throws {
let expectedStruct = SupportedTypes(
a: -12,
b: 13,
c: [-14],
d: [15],
e: -16,
f: nil,
g: 17,
h: nil
)
let expectedJson = """
{\
"a":"-12",\
"b":"13",\
"c":["-14"],\
"d":["15"],\
"e":"-16",\
"f":null,\
"g":"17",\
"h":null\
}
"""
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // For deterministic output.
let jsonData = try encoder.encode(expectedStruct)
let actualJson = String(data: jsonData, encoding: .utf8)!
XCTAssertEqual(expectedJson, actualJson)
let actualStruct = try JSONDecoder().decode(SupportedTypes.self, from: jsonData)
XCTAssertEqual(expectedStruct, actualStruct)
}
}
| apache-2.0 | 73a78d2d9d519395619e8c53ef8b70f6 | 25.653333 | 88 | 0.570285 | 4.271368 | false | true | false | false |
mobgeek/swift | Swift em 4 Semanas/Playgrounds/Semana 2/4-Coleções.playground/Contents.swift | 2 | 1291 | // Playground - noun: a place where people can play
import UIKit
// Arrays
var listaCompras: [String] = ["Laranja", "Maça", "Limão"]
var novaListaCompras = ["Laranja", "Tomate", "Alface"]
// Propriedades
listaCompras.count
novaListaCompras.isEmpty
// Métodos
listaCompras.append("Picanha")
listaCompras.removeAtIndex(2)
listaCompras
listaCompras += ["Abacaxi", "Cafe"]
// Subscript
listaCompras[0] = "Cerveja"
listaCompras[2...4] = ["Leite", "Sal"]
listaCompras
for item in listaCompras {
println(item)
}
// Array vazia
var algunsInteiros = [Int] ()
algunsInteiros.append(6)
algunsInteiros.append(9)
algunsInteiros = []
// Dicionários
var dicionarioNumeros = [1: "Um", 2:"Dois"] // [Int: String]
dicionarioNumeros[3]
if let numero = dicionarioNumeros[3] {
println("O valor correspondente a essa chave existe e é \(numero)")
}
dicionarioNumeros.count
dicionarioNumeros[3] = "Tres"
dicionarioNumeros[3] = "Três"
dicionarioNumeros[3] = nil
dicionarioNumeros
for (numero, descrição) in dicionarioNumeros {
println("\(numero): \(descrição)")
}
for numero in dicionarioNumeros.keys {
println("Número: \(numero)")
}
var numeroEmPolones = [Int:String]()
numeroEmPolones[13] = "trzynascie"
numeroEmPolones = [:]
| mit | b1a3367f3bf59639c89ffe912891d4dd | 11.54902 | 71 | 0.691406 | 2.700422 | false | false | false | false |
CoderLiLe/Swift | for/main.swift | 1 | 2207 | //
// main.swift
// for
//
// Created by LiLe on 15/3/17.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
for循环
格式: for (初始化表达式;循环保持条件;循环后表达式) {需要执行的语句}
OC:
int sum = 0;
for (int i = 0; i <= 10; i++) {
sum = i++;
}
NSLog(@"%d", sum);
int sum = 0;
int i = 0;
for (; i <= 10; i++) {
sum = i++;
}
NSLog(@"%d", sum);
int sum = 0;
int i = 0;
for (; i <= 10; ) {
sum = i++;
i++;
}
NSLog(@"%d", sum);
int sum = 0;
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
if (i > 10) {
break;
}
}
NSLog(@"%d", sum);
int sum = 0;
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
NSLog(@"%d", sum);
}
如果只有一条指令for后面的大括号可以省略
for后面的三个参数都可以省略, 如果省略循环保持语句, 那么默认为真
Swift:
0.for后的圆括号可以省略
1.只能以bool作为条件语句
2.如果只有条指令for后面的大括号不可以省略
3.for后面的三个参数都可以省略, 如果省略循环保持语句, 那么默认为真
*/
var sum:Int = 0
for var i = 0 ; i <= 10 ; i++
{
sum = i++
}
print(sum)
var sum1:Int = 0
var i1 = 0
for ; i1 <= 10 ; i1++
{
sum1 = i1++
}
print(sum1)
var sum2:Int = 0
var i2 = 0
for ; i2 <= 10;
{
sum2 = i2++
i2++
}
print(sum2)
var sum3:Int = 0
var i3 = 0
for ; ;
{
sum3 = i3++
i3++
if i3 > 10
{
break
}
}
print(sum3)
/*
for in循环
格式: for (接收参数 in 取出的参数) {需要执行的语句}
for in含义: 从(in)取出什么给什么, 直到取完为止
OC:
for (NSNumber *i in @[@1, @2, @3, @4, @5]) {
NSLog(@"%@", i);
}
NSDictionary *dict = @{@"name":@"lnj", @"age":@30};
for (NSArray *keys in dict.allKeys) {
NSLog(@"%@", keys);
}
NSDictionary *dict = @{@"name":@"lnj", @"age":@30};
for (NSArray *keys in dict.allValues) {
NSLog(@"%@", keys);
}
Swift:
for in 一般用于遍历区间或者集合
*/
var sum4:Int = 0
for i4 in 1...10 // 会将区间的值依次赋值给i
{
sum4 += i4;
}
print(sum4)
for dict in ["name":"lnj", "age":30]
{
print(dict);
}
for (key, value) in ["name":"lnj", "age":30]
{
print("\(key) = \(value)")
}
| mit | 19a86fd4b04dbdf9193da573e6b31312 | 11.65035 | 51 | 0.51686 | 2.222359 | false | false | false | false |
takeo-asai/math-puzzle | problems/40.swift | 1 | 3854 | // cards.count must be >= 1
struct Cards: Hashable {
var cards: [Int]
init(_ cs: [Int]) {
cards = cs
}
mutating func reverse() -> [Int] {
let n = cards.first!
cards = cards[0..<n].reverse() + cards[n..<cards.count]
return cards
}
// 戻す. 1枚目がnだとreverse()するとn-1番目にnが来る
func reReverse() -> [[Int]] {
var re: [[Int]] = []
for n in 2 ... cards.count {
if n == cards[n-1] {
re += [cards[0..<n].reverse() + cards[n..<cards.count]]
}
}
return re
}
private func isNotGoal() -> Bool {
return cards.first! != 1
}
mutating func count() -> Int {
var count = 0
while isNotGoal() {
reverse()
count = count + 1
}
return count
}
var hashValue: Int {
get {
return cards.description.hashValue
}
}
}
func == (lhs: Cards, rhs: Cards) -> Bool {
return lhs.hashValue == rhs.hashValue
}
extension Array {
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
// https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift
// https://github.com/pNre/ExSwift/blob/master/LICENSE
/**
- parameter length: The length of each permutation
- returns: All permutations of a given length within an array
*/
func permutation (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
} else if length == 0 {
return [[]]
} else {
var permutations: [[Element]] = []
let combinations = combination(length)
for combination in combinations {
var endArray: [[Element]] = []
var mutableCombination = combination
permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray)
}
return permutations
}
}
private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] {
if n == 1 {
endArray += [array]
}
for var i = 0; i < n; i++ {
permutationHelper(n - 1, array: &array, endArray: &endArray)
let j = n % 2 == 0 ? i : 0
let temp: Element = array[j]
array[j] = array[n - 1]
array[n - 1] = temp
}
return endArray
}
func combination (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
}
var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]}
var combinations: [[Element]] = []
let offset = self.count - indexes.count
while true {
var combination: [Element] = []
for index in indexes {
combination.append(self[index])
}
combinations.append(combination)
var i = indexes.count - 1
while i >= 0 && indexes[i] == i + offset {
i--
}
if i < 0 {
break
}
i++
let start = indexes[i-1] + 1
for j in (i-1)..<indexes.count {
indexes[j] = start + j - i + 1
}
}
return combinations
}
}
var cache: [Cards: Int] = [: ]
func searchAndCheck(presents: [[Int]], depth: Int) -> [[Int]] {
var nexts: [[Int]] = []
for p in presents {
for re in Cards(p).reReverse() {
let c = Cards(re)
if let _ = cache[c] {
} else {
cache[c] = depth
nexts += [re]
}
}
}
return nexts
}
let n = 9
var maxI: [Int] = []
var maxC = Cards([])
var max = 0
for p in Array((1 ... n)).permutation(n) {
var c = Cards(p)
var v = c.count()
if max < v {
max = v
maxC = c
maxI = p
}
}
print(max)
print(maxC)
print(maxI)
| mit | 36e6b596fdbf83ea5105f7b9e797dd87 | 25.727273 | 112 | 0.50157 | 3.675 | false | false | false | false |
brokenseal/iOS-exercises | Team Treehouse/RestaurantFinder/RestaurantFinder/AppDelegate.swift | 1 | 3331 | //
// AppDelegate.swift
// RestaurantFinder
//
// Created by Pasan Premaratne on 5/4/16.
// Copyright © 2017 Davide Callegar. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.venue == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | c3b3c9d99dbda996dc93b1b2c187ebf3 | 54.5 | 285 | 0.761562 | 6.155268 | false | false | false | false |
joseph-zhong/CommuterBuddy-iOS | SwiftSideMenu/ViewController.swift | 1 | 10612 | //
// ViewController.swift
// SwiftSideMenu
//
// Created by Evgeny on 03.08.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import UserNotifications
//import XCGLogger
class ViewController: UIViewController, ENSideMenuDelegate, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var destinationTextField: UITextField!
@IBOutlet weak var searchBarButtonItem: UIBarButtonItem!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var alarmSwitch: UISwitch!
@IBOutlet weak var unitLabel: UILabel!
lazy var locationManager: CLLocationManager! = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
return manager
}()
var geocoder: CLGeocoder!
override func viewDidLoad() {
super.viewDidLoad()
// ENSideMenu Delegate
self.sideMenuController()?.sideMenu?.delegate = self
// searchBarButton gestures
self.searchBarButtonItem.action = #selector(self.toggleDestinationTextField)
self.searchBarButtonItem.target = self
// distanceSlider gestures
// self.distanceSlider.addTarget(self, action: #selector(self.changeLabelValue), for: UIControlEvents.valueChanged)
// alarmSwitch gesture
self.alarmSwitch.addTarget(self, action: #selector(self.toggleAlarm), for: UIControlEvents.valueChanged)
// hide keyboard
self.hideKeyboardWhenTappedAround()
// locationManager
if (CLLocationManager.locationServicesEnabled()) {
self.locationManager.startUpdatingLocation()
self.locationManager.startUpdatingHeading()
}
else {
// TODO: do something here
}
// geocoder
self.geocoder = CLGeocoder()
// map
self.mapView.delegate = self
self.mapView.showsUserLocation = true
self.mapView.showsPointsOfInterest = true
self.mapView.mapType = MKMapType.standard
self.mapView.userTrackingMode = MKUserTrackingMode.followWithHeading
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func toggleSideMenu(_ sender: AnyObject) {
self.toggleSideMenuView()
}
// MARK: - ENSideMenu Delegate
func sideMenuWillOpen() {
print("ViewController: sideMenuWillOpen")
}
func sideMenuWillClose() {
print("ViewController: sideMenuWillClose")
}
func sideMenuShouldOpenSideMenu() -> Bool {
print("ViewController: sideMenuShouldOpenSideMenu")
return true
}
func sideMenuDidClose() {
print("ViewController: sideMenuDidClose")
}
func sideMenuDidOpen() {
print("ViewController: sideMenuDidOpen")
}
// MARK: - CLLocationManager Delegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last!
// first time retrieving location
if userLocation.coordinate.latitude == 47.606200001
&& userLocation.coordinate.longitude == 122.332100001 {
self.setMapRegion(location: location)
}
userLocation = location
print("locationManager: didUpdateLocations \(locations)")
if destination != nil {
distanceFromDest = Float(userLocation.distance(from: destination!))
self.changeLabelValue(distance: metersToMiles(meters: distanceFromDest!))
}
if UIApplication.shared.applicationState == .background {
print("locationManager: didUpdateLocations background userLocation \(userLocation)")
// check distance and region entering
// draw overlay
// end loop sound alarm
if self.alarmSwitch.isOn && distanceFromDest! <= thresholdDist! {
// check distance and region entering
}
}
else if UIApplication.shared.applicationState == .active {
print("locationManager: didUpdateLocations active userLocation \(userLocation)")
}
}
func fireNotification() -> Void {
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Destination Reached!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "", arguments: nil)
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request)
//
//
// let notificationContent = UNNotificationContent()
//// notificationContent.title = "Destination Reached"
//// notificationContent.sound =
// let notificationRequest = UNNotificationRequest(identifier: "Notification",
// content: notificationContent,
// trigger: UNNotificationTrigger?)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationManager.stopUpdatingLocation()
print("locationManager: didFailWithError \(error)")
}
func locationManager(_ manager: CLLocationManager,
didUpdateHeading newHeading: CLHeading) {
print("locationManager: didUpdateHeading \(newHeading)")
}
func locationManager(_ manager: CLLocationManager,
didStartMonitoringFor region: CLRegion) {
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("locationManager: didEnterRegion \(region)")
}
func locationManager(_ manager: CLLocationManager,
monitoringDidFailFor region: CLRegion?,
withError error: Error){
}
func locationManager(_ manager: CLLocationManager,
didDetermineState state: CLRegionState,
for region: CLRegion) {
}
func locationManager(_ manager: CLLocationManager,
didExitRegion region: CLRegion) {
}
// MARK: - MKMap Delegate
func mapView(_ mapView: MKMapView,
regionWillChangeAnimated animated: Bool) {
print("mapView: regionWillChangeAnimated \(animated)")
}
func mapView(_ mapView: MKMapView,
regionDidChangeAnimated animated: Bool) {
print("mapView: regionDidChangeAnimated \(animated)")
// update destination
destination = CLLocation(latitude: self.mapView.centerCoordinate.latitude,
longitude: self.mapView.centerCoordinate.longitude)
distanceFromDest = Float(userLocation.distance(from: destination!))
print("mapView: destination \(destination)")
self.setDestinationTextField(location: destination!)
self.changeLabelValue(distance: metersToMiles(meters: distanceFromDest!))
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if (overlay is MKPolyline) {
let pr = MKPolylineRenderer(overlay: overlay)
pr.strokeColor = UIColor.blue
pr.lineWidth = 3
return pr
}
return MKOverlayRenderer()
}
func mapView(_ mapView: MKMapView, didAdd renderers: [MKOverlayRenderer]) {
}
// MARK: - Map Functionality
func setMapRegion(location: CLLocation) {
// set region
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
// MARK: - Geocoding functionality
func setDestinationTextField(location: CLLocation) {
self.geocoder.reverseGeocodeLocation(location) { (placemarks: [CLPlacemark]?, error: Error?) in
if error == nil && placemarks != nil && (placemarks?.count)! > 0 {
print("setDestinationTextField placemarks: \(placemarks)")
let placemark = placemarks![0]
if placemark.thoroughfare != nil {
self.destinationTextField.text = placemark.thoroughfare!
}
else if placemark.subThoroughfare != nil {
self.destinationTextField.text = placemark.subThoroughfare!
}
else {
self.destinationTextField.text = ""
}
print("destinationTextField text: \(self.destinationTextField.text)")
self.changeLabelValue(distance: metersToMiles(meters: Float(userLocation.distance(from: location))))
}
else {
print("setDestinationTextField error: \(error)")
}
}
}
// MARK: - Gesture Targets
func toggleDestinationTextField(){
self.destinationTextField.becomeFirstResponder()
print("toggleDestinationTextField: focus \(self.destinationTextField.isFocused)")
}
func toggleAlarm() {
print("toggleAlarm: isOn \(self.alarmSwitch.isOn)")
if self.alarmSwitch.isOn {
self.distanceLabel.textColor = UIColor.blue
}
else {
self.distanceLabel.textColor = UIColor.black
}
}
func changeLabelValue(distance: Float) {
// update value
self.distanceLabel.text = String(format: "%.2f", distance)
print("changeLabelValue: text \(self.distanceLabel.text)")
}
}
| mit | b18f0dd574febffd6e19f4463f8e8be0 | 35.593103 | 133 | 0.619016 | 5.955107 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.