repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lizhuoli1126/e-lexer | other/e-lexer-swift/e-lexer/ll.swift | 1 | 1908 | //
// ll.swift
// e-lexer
//
// Created by lizhuoli on 15/12/5.
// Copyright © 2015年 lizhuoli. All rights reserved.
//
import Foundation
struct Stack<Element> {
var items = [Element]()
mutating func push(item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
func empty() -> Bool {
return items.isEmpty
}
func top() -> Element? {
return items.last
}
}
class LLParse {
var stack = Stack<Symbol>()
let grammar:[Symbol: [Production]]
var currentChoice = 0
init(grammar:[Symbol: [Production]) {
self.grammar = grammar
}
deinit{}
func ll(currentToken:Character) {
if (grammar.isEmpty) {
return
}
var temp:Symbol?
var tempNum:Int = 0
let start = grammar["S"]
stack.push((start?.left)!)
while(!stack.empty()) {
guard let top = stack.top() else {return}
if (top.type == .Terminal) {
if (top.value == currentToken) {
stack.pop()
// getNextToken()
} else {
for _ in 0...tempNum {
stack.pop()
}
stack.push(temp!)
}
} else if (top.type == .NonTerminal) {
temp = stack.pop()
tempNum++
let rule = nextRule(top)
if rule.count != 0 {
for r in rule {
stack.push(r)
tempNum++
}
} else {
Error.parseError()
}
}
}
}
func nextRule(p :Symbol) -> [Symbol] {
grammar[p]
}
}
class LRParse {
} | mit | 3381c81b07c58b7e39fb94847856214f | 20.908046 | 53 | 0.425197 | 4.440559 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/LaunchLoading/LaunchLoadingView.swift | 2 | 1667 | /*
Copyright 2020 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import Reusable
@objcMembers
final class LaunchLoadingView: UIView, NibLoadable, Themable {
// MARK: - Constants
private enum LaunchAnimation {
static let duration: TimeInterval = 3.0
static let repeatCount = Float.greatestFiniteMagnitude
}
// MARK: - Properties
@IBOutlet private weak var animationView: ElementView!
private var animationTimeline: Timeline_1!
// MARK: - Setup
static func instantiate() -> LaunchLoadingView {
let view = LaunchLoadingView.loadFromNib()
return view
}
override func awakeFromNib() {
super.awakeFromNib()
let animationTimeline = Timeline_1(view: self.animationView, duration: LaunchAnimation.duration, repeatCount: LaunchAnimation.repeatCount)
animationTimeline.play()
self.animationTimeline = animationTimeline
}
// MARK: - Public
func update(theme: Theme) {
self.backgroundColor = theme.backgroundColor
self.animationView.backgroundColor = theme.backgroundColor
}
}
| apache-2.0 | d6416f9d6355edc272ca3384d8244315 | 28.767857 | 146 | 0.707858 | 5.006006 | false | false | false | false |
tjw/swift | test/expr/primary/literal/collection_upcast_opt.swift | 1 | 1223 | // RUN: %target-typecheck-verify-swift -dump-ast 2> %t.ast
// RUN: %FileCheck %s < %t.ast
// Verify that upcasts of array literals upcast the individual elements in place
// rather than introducing a collection_upcast_expr.
protocol P { }
struct X : P { }
struct TakesArray<T> {
init(_: [(T) -> Void]) { }
}
// CHECK-LABEL: func_decl "arrayUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: array_expr type='[(X) -> Void]'
// CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x1}}
// CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x2}}
func arrayUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesArray<X>([x1, x2])
}
struct TakesDictionary<T> {
init(_: [Int : (T) -> Void]) { }
}
// CHECK-LABEL: func_decl "dictionaryUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: paren_expr type='([Int : (X) -> Void])'
// CHECK-NOT: collection_upcast_expr
// CHECK: (dictionary_expr type='[Int : (X) -> Void]'
func dictionaryUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesDictionary<X>(([1: x1, 2: x2]))
}
| apache-2.0 | 50b6d600ae26595dda799ea833c9a442 | 31.184211 | 81 | 0.631235 | 2.968447 | false | false | false | false |
codecombat/codecombat-ios | CodeCombat/ArgumentStringPickerPopoverViewController.swift | 2 | 2157 | //
// ArgumentStringPickerPopoverView.swift
// CodeCombat
//
// Created by Michael Schmatz on 10/28/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import Foundation
protocol StringPickerPopoverDelegate {
func stringWasSelectedByStringPickerPopover(selected:String,characterRange:NSRange)
}
class ArgumentStringPickerPopoverViewController: UITableViewController {
var strings:[String] = []
var pickerDelegate:StringPickerPopoverDelegate! = nil
var selectedString:String = ""
var characterRange:NSRange!
let rowHeight = 30
init(stringChoices:[String], characterRange:NSRange) {
super.init(style: UITableViewStyle.Plain)
strings = stringChoices
self.characterRange = characterRange
clearsSelectionOnViewWillAppear = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return strings.count
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGFloat(rowHeight)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.text = strings[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selected = strings[indexPath.row]
if pickerDelegate != nil {
pickerDelegate.stringWasSelectedByStringPickerPopover(selected, characterRange:characterRange)
dismissViewControllerAnimated(true, completion: nil)
}
}
}
| mit | 83613c204d47b175fad9c06511cfe64e | 31.19403 | 116 | 0.753825 | 5.075294 | false | false | false | false |
farzadshbfn/POP | Sources/UICollectionViewExtension.swift | 1 | 2176 | //
// UICollectionViewExtension.swift
// POP
//
// Created by Farzad Sharbafian on 12/16/16.
// Copyright © 2016 FarzadShbfn. All rights reserved.
//
import Foundation
import UIKit
extension UICollectionView {
// MARK:- Registeration
// MARK: Cell
/// Registering a cell which is `ReusableView` and also `NibLoadableView`
public func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let nib = UINib(nibName: T.nibName, bundle: nil)
register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
}
/// Registering a cell which is `ReusableView`
public func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView {
register(T.self, forCellWithReuseIdentifier: T.reuseIdentifier)
}
// MARK: UICollectionSupplementaryView
public struct SupplementaryViewKind : OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let header = SupplementaryViewKind(rawValue: 1 << 0)
public static let footer = SupplementaryViewKind(rawValue: 1 << 1)
}
/// Registering a view which is `ReusableView` and also `NibLoadableView`
public func register<T: UIView>(_: T.Type, forKind kind: SupplementaryViewKind) where T: ReusableView, T: NibLoadableView {
let nib = UINib(nibName: T.nibName, bundle: nil)
if kind.contains(.header) {
register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: T.reuseIdentifier)
}
if kind.contains(.footer) {
register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: T.reuseIdentifier)
}
}
/// Registering a view which is `ReusableView`
public func register<T: UIView>(_: T.Type, forKind kind: SupplementaryViewKind) where T: ReusableView {
if kind.contains(.header) {
register(T.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: T.reuseIdentifier)
}
if kind.contains(.footer) {
register(T.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: T.reuseIdentifier)
}
}
// MARK:- Dequeution
}
| mit | 52e94040a2562835831655300fcbabe4 | 31.462687 | 125 | 0.750345 | 4.306931 | false | false | false | false |
leeaken/LTMap | LTMap/LTLocationMap/LocationPick/Common/LTLocationCommon.swift | 1 | 881 | //
// LTLocationCommon.swift
// LTMap
//
// Created by aken on 2017/6/16.
// Copyright © 2017年 LTMap. All rights reserved.
//
import Foundation
let cellIdentifier = "cellIdentifier"
struct LTLocationCommon {
static let MapDefaultWidth = UIScreen.main.bounds.size.width
static let MapDefaultHeight = (UIScreen.main.bounds.size.height - 64)/2 - 44
static let MapAfterAnimationsDefaultHeight = (UIScreen.main.bounds.size.height - 64)/2 - 132 - 44
static let TableViewDefaultHeight = (UIScreen.main.bounds.size.height - 64)/2
static let TableViewAfterAnimationsDefaultHeight = (UIScreen.main.bounds.size.height - 64)/2 + 132
static let POISearchPageSize = 20
static let POISearchRadius = 1000
}
enum MXPickLocationType: String {
case LTPickMix // 地图和列表混合
case LTPickMap // 地图
case LTPickList // 列表
}
| mit | 2c59bbeb7daca732112c234294b5e66f | 28.517241 | 102 | 0.718458 | 3.754386 | false | false | false | false |
D-Pointer/imperium-server | swift/Sources/imperium-server/Mutex.swift | 1 | 2064 |
import Foundation
public class Mutex {
private var mutex: pthread_mutex_t = pthread_mutex_t()
public init() {
var attr: pthread_mutexattr_t = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
pthread_mutexattr_settype(&attr, Int32(PTHREAD_MUTEX_RECURSIVE))
let err = pthread_mutex_init(&self.mutex, &attr)
pthread_mutexattr_destroy(&attr)
switch err {
case 0:
// Success
break
case EAGAIN:
fatalError("Could not create mutex: EAGAIN (The system temporarily lacks the resources to create another mutex.)")
case EINVAL:
fatalError("Could not create mutex: invalid attributes")
case ENOMEM:
fatalError("Could not create mutex: no memory")
default:
fatalError("Could not create mutex, unspecified error \(err)")
}
}
public final func lock() {
let ret = pthread_mutex_lock(&self.mutex)
switch ret {
case 0:
// Success
break
case EDEADLK:
fatalError("Could not lock mutex: a deadlock would have occurred")
case EINVAL:
fatalError("Could not lock mutex: the mutex is invalid")
default:
fatalError("Could not lock mutex: unspecified error \(ret)")
}
}
public final func unlock() {
let ret = pthread_mutex_unlock(&self.mutex)
switch ret {
case 0:
// Success
break
case EPERM:
fatalError("Could not unlock mutex: thread does not hold this mutex")
case EINVAL:
fatalError("Could not unlock mutex: the mutex is invalid")
default:
fatalError("Could not unlock mutex: unspecified error \(ret)")
}
}
deinit {
assert(pthread_mutex_trylock(&self.mutex) == 0 && pthread_mutex_unlock(&self.mutex) == 0, "deinitialization of a locked mutex results in undefined behavior!")
pthread_mutex_destroy(&self.mutex)
}
}
| gpl-2.0 | 874d9c8e7cade3c4dde8159f56f83a59 | 26.891892 | 166 | 0.583333 | 4.777778 | false | false | false | false |
JohnnyH1012/CustomCollectionViewLayout-master | CustomCollectionLayout/CustomCollectionViewLayout.swift | 1 | 6232 | //
// CustomCollectionViewLayout.swift
// CustomCollectionLayout
//
// Created by JOSE MARTINEZ on 15/12/2014.
// Copyright (c) 2014 brightec. All rights reserved.
//
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
let numberOfColumns = 8
var itemAttributes : NSMutableArray!
var itemsSize : NSMutableArray!
var contentSize : CGSize!
override func prepareLayout() {
if self.collectionView?.numberOfSections() == 0 {
return
}
if (self.itemAttributes != nil && self.itemAttributes.count > 0) {
for section in 0..<self.collectionView!.numberOfSections() {
var numberOfItems : Int = self.collectionView!.numberOfItemsInSection(section)
for index in 0..<numberOfItems {
if section != 0 && index != 0 {
continue
}
var attributes : UICollectionViewLayoutAttributes = self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: section))
if section == 0 {
var frame = attributes.frame
frame.origin.y = self.collectionView!.contentOffset.y
attributes.frame = frame
}
if index == 0 {
var frame = attributes.frame
frame.origin.x = self.collectionView!.contentOffset.x
attributes.frame = frame
}
}
}
return
}
if (self.itemsSize == nil || self.itemsSize.count != numberOfColumns) {
self.calculateItemsSize()
}
var column = 0
var xOffset : CGFloat = 0
var yOffset : CGFloat = 0
var contentWidth : CGFloat = 0
var contentHeight : CGFloat = 0
for section in 0..<self.collectionView!.numberOfSections() {
var sectionAttributes = NSMutableArray()
for index in 0..<numberOfColumns {
var itemSize = self.itemsSize[index].CGSizeValue()
var indexPath = NSIndexPath(forItem: index, inSection: section)
var attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = CGRectIntegral(CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height))
if section == 0 && index == 0 {
attributes.zIndex = 1024;
} else if section == 0 || index == 0 {
attributes.zIndex = 1023
}
if section == 0 {
var frame = attributes.frame
frame.origin.y = self.collectionView!.contentOffset.y
attributes.frame = frame
}
if index == 0 {
var frame = attributes.frame
frame.origin.x = self.collectionView!.contentOffset.x
attributes.frame = frame
}
sectionAttributes.addObject(attributes)
xOffset += itemSize.width
column++
if column == numberOfColumns {
if xOffset > contentWidth {
contentWidth = xOffset
}
column = 0
xOffset = 0
yOffset += itemSize.height
}
}
if (self.itemAttributes == nil) {
self.itemAttributes = NSMutableArray(capacity: self.collectionView!.numberOfSections())
}
self.itemAttributes .addObject(sectionAttributes)
}
var attributes : UICollectionViewLayoutAttributes = self.itemAttributes.lastObject?.lastObject as! UICollectionViewLayoutAttributes
contentHeight = attributes.frame.origin.y + attributes.frame.size.height
self.contentSize = CGSizeMake(contentWidth, contentHeight)
}
override func collectionViewContentSize() -> CGSize {
return self.contentSize
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return self.itemAttributes[indexPath.section][indexPath.row] as! UICollectionViewLayoutAttributes
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var attributes : NSMutableArray = NSMutableArray()
for section in self.itemAttributes {
attributes.addObjectsFromArray(
section.filteredArrayUsingPredicate(
NSPredicate(block: { (evaluatedObject, bindings) -> Bool in
return CGRectIntersectsRect(rect, evaluatedObject.frame)
})
)
)
}
return attributes as [AnyObject]
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
func sizeForItemWithColumnIndex(columnIndex: Int) -> CGSize {
var text : String = ""
switch (columnIndex) {
case 0:
text = "Col 0"
case 1:
text = "Col 1"
case 2:
text = "Col 2"
case 3:
text = "Col 3"
case 4:
text = "Col 4"
case 5:
text = "Col 5"
case 6:
text = "Col 6"
default:
text = "Col 7"
}
var size : CGSize = (text as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(17.0)])
let width : CGFloat = size.width + 25
return CGSizeMake(width + 20, 30)
}
func calculateItemsSize() {
self.itemsSize = NSMutableArray(capacity: numberOfColumns)
for index in 0..<numberOfColumns {
self.itemsSize.addObject(NSValue(CGSize: self.sizeForItemWithColumnIndex(index)))
}
}
} | mit | aba0a78d14f8c3b6ce643a4a2e686140 | 36.10119 | 160 | 0.534981 | 5.998075 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Controller/Views/LocationCell.swift | 1 | 7302 | //
// LocationCell.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 18/11/16.
// Copyright © 2016 Mihai Cristescu. All rights reserved.
//
import UIKit
final class LocationCell: UITableViewCell {
// MARK: - Properties
var mount: Mount! {
didSet {
if let mount = mount {
locationNameLabel.text = mount.name
ownerNameLabel.text = "\(mount.owner.firstName) \(mount.owner.lastName)"
if mount.online {
statusLabel.textColor = UIColor(red: 0.0, green: 0.8, blue: 0.0, alpha: 1.0)
} else {
statusLabel.textColor = UIColor.gray
}
if var spaceUsed = mount.spaceUsed, var spaceTotal = mount.spaceTotal {
spaceUsed /= 1024
spaceTotal /= 1024
spaceUsedValueLabel.text = "\(spaceUsed) / \(spaceTotal) GB"
}
setupViews()
}
}
}
let leftView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let locationNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeue(size: 24)
return label
}()
let ownerLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = NSLocalizedString("Owner", comment: "")
label.font = UIFont.fontHelveticaNeue(size: 14)
return label
}()
let ownerNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeue(size: 14)
label.textColor = UIColor.defaultColor
return label
}()
let spaceUsedLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = NSLocalizedString("Usage", comment: "")
label.font = UIFont.fontHelveticaNeue(size: 14)
return label
}()
let spaceUsedValueLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeue(size: 14)
label.textColor = UIColor.defaultColor
return label
}()
let statusLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "●"
label.font = UIFont.fontHelveticaNeue(size: 20)
label.textColor = UIColor.white
return label
}()
let desktopLabel: UILabelWithPadding = {
let label = UILabelWithPadding(paddingTop: 4, paddingLeft: 5, paddingBottom: 4, paddingRight: 5)
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeueMedium(size: 12)
label.text = "DESKTOP"
label.layer.borderWidth = 0.6
label.layer.borderColor = UIColor.black.cgColor
label.layer.cornerRadius = 5
return label
}()
// MARK: - Initializers and Deinitializers
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden Methods and Properties
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .blue
accessoryType = .disclosureIndicator
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
setLeftViewBackgroundColor()
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
setLeftViewBackgroundColor()
}
// MARK: - Helper Functions
private func setupViews() {
contentView.addSubview(locationNameLabel)
contentView.addSubview(statusLabel)
contentView.addSubview(leftView)
setLeftViewBackgroundColor()
NSLayoutConstraint.activate([
locationNameLabel.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor),
locationNameLabel.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor),
statusLabel.bottomAnchor.constraint(equalTo: locationNameLabel.bottomAnchor),
statusLabel.leftAnchor.constraint(equalTo: locationNameLabel.rightAnchor, constant: 10),
leftView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
leftView.topAnchor.constraint(equalTo: contentView.topAnchor),
leftView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
leftView.widthAnchor.constraint(equalToConstant: 5)
])
if mount.type == "device" {
contentView.addSubview(spaceUsedLabel)
contentView.addSubview(spaceUsedValueLabel)
NSLayoutConstraint.activate([
spaceUsedLabel.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor),
spaceUsedLabel.bottomAnchor.constraint(equalTo: locationNameLabel.bottomAnchor, constant: 30),
spaceUsedValueLabel.firstBaselineAnchor.constraint(equalTo: spaceUsedLabel.firstBaselineAnchor),
spaceUsedValueLabel.leftAnchor.constraint(equalTo: spaceUsedLabel.rightAnchor, constant: 10)
])
if mount.type == "device" && mount.origin == "desktop" {
contentView.addSubview(desktopLabel)
NSLayoutConstraint.activate([
desktopLabel.leftAnchor.constraint(equalTo: statusLabel.rightAnchor, constant: 10),
desktopLabel.centerYAnchor.constraint(equalTo: statusLabel.centerYAnchor)
])
}
}
if mount.type == "import" || mount.type == "export" {
contentView.addSubview(ownerLabel)
contentView.addSubview(ownerNameLabel)
NSLayoutConstraint.activate([
ownerLabel.leftAnchor.constraint(equalTo: locationNameLabel.leftAnchor),
ownerLabel.bottomAnchor.constraint(equalTo: locationNameLabel.bottomAnchor, constant: 30),
ownerNameLabel.leftAnchor.constraint(equalTo: ownerLabel.rightAnchor, constant: 8),
ownerNameLabel.centerYAnchor.constraint(equalTo: ownerLabel.centerYAnchor)
])
}
}
private func setLeftViewBackgroundColor() {
if mount.type == "device" {
if mount.isPrimary {
leftView.backgroundColor = UIColor(red: 0.8, green: 0.3, blue: 0.3, alpha: 1.0)
} else {
leftView.backgroundColor = UIColor(red: 0.7, green: 0.5, blue: 0.1, alpha: 1.0)
}
}
if mount.type == "import" {
leftView.backgroundColor = UIColor(red: 0.0, green: 0.6, blue: 0.0, alpha: 1.0)
}
if mount.type == "export" {
leftView.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 1.0, alpha: 1.0)
}
}
}
| mit | 1dc5146cc16cfc472f247883013364af | 33.592417 | 112 | 0.630086 | 5.20985 | false | false | false | false |
arn00s/cariocamenu | Sources/CariocaIndicatorView.swift | 1 | 15104 | //
// CariocaMenuIndicatorView.swift
// CariocaMenu
//
// Created by Arnaud Schloune on 01/12/2017.
// Copyright © 2017 CariocaMenu. All rights reserved.
//
import Foundation
import UIKit
///Defines bouncing values for animation from/to
public typealias BouncingValues = (from: CGFloat, to: CGFloat)
///The constants that will be used to animate the indicator
struct IndicatorPositionConstants {
///Starting position constant (indicator on hold)
let start: CGFloat
///Starting position bouncing values
let startBounce: BouncingValues
///Ending position bouncing values
let end: BouncingValues
///The value to hide the menu, when restoring the boomerang.
let hidingConstant: CGFloat
}
///The menu's indicator
public class CariocaIndicatorView: UIView {
///The edge of the indicator.
var edge: UIRectEdge
///The original edge. Used when boomerang is not .none
private let originalEdge: UIRectEdge
///The indicator's top constraint
var topConstraint = NSLayoutConstraint()
///The indicator's horizontal constraint.
private var horizontalConstraint = NSLayoutConstraint()
///The icon's view
var iconView: CariocaIconView
///The custom indicator configuration
private let config: CariocaIndicator
///The constraints applied to the iconview. Can be updated later with custom configuration
private var iconConstraints: [NSLayoutConstraint] = []
///The indicator's possible animation states
private enum AnimationState {
///The indicator is on hold, the menu is closed
case onHold
///The indicator is performing showing animation
case showing
///The indicator is performing restoration animation
case restoring
}
///Status of the indicator animations. Avoid double animations issues
private var state: AnimationState = .onHold
///Initialise an IndicatorView
///- Parameter edge: The inital edge. Will be updated every time the user changes of edge.
///- Parameter indicator: The indicator custom configuration
init(edge: UIRectEdge, indicator: CariocaIndicator) {
self.edge = edge
self.originalEdge = edge
self.config = indicator
self.iconView = CariocaIconView()
self.iconView.translatesAutoresizingMaskIntoConstraints = false
let frame = CGRect(x: 0, y: 0, width: indicator.size.width, height: indicator.size.height)
super.init(frame: frame)
self.backgroundColor = .clear
self.addSubview(iconView)
iconConstraints = iconView.makeAnchorConstraints(to: self)
self.addConstraints(iconConstraints)
iconView.font = config.font
}
//swiftlint:disable function_parameter_count
///Calculates the indicator's position for animation
///- Parameter hostWidth: The hostView's width
///- Parameter indicatorWidth: The indicator's size
///- Parameter edge: The original edge
///- Parameter borderMargin: The border magins
///- Parameter bouncingValues: The values to make the bouncing effect in animations
///- Parameter startInset: The view's starting inset, if applies (iPhone X safe area)
///- Parameter endInset: The view's starting inset, if applies (iPhone X safe area)
///- Returns: IndicatorPositionConstants All the possible calculated positions
class func positionConstants(hostWidth: CGFloat,
indicatorWidth: CGFloat,
edge: UIRectEdge,
borderMargin: CGFloat,
bouncingValues: BouncingValues,
startInset: CGFloat,
endInset: CGFloat) -> IndicatorPositionConstants {
let multiplier: CGFloat = edge == .left ? -1.0 : 1.0
let hostMidWidth = hostWidth / 2.0
let indicWidth = indicatorWidth / 2.0
let inverseMultiplier: CGFloat = multiplier * -1.0
//Start positions
let start = hostMidWidth - indicWidth + borderMargin - startInset
let startBounceFrom = start + bouncingValues.from + startInset
let startBounceTo = start - bouncingValues.to
let startBounce: BouncingValues = (from: (startBounceFrom * multiplier), to: (startBounceTo * multiplier))
//End positions
let endBounceFrom: CGFloat = (hostMidWidth - indicWidth + bouncingValues.from + endInset) * inverseMultiplier
let endBounceTo: CGFloat = (hostMidWidth - indicWidth - borderMargin - endInset) * inverseMultiplier
let endBounce: BouncingValues = (from: endBounceFrom, to: endBounceTo)
///Hiding constant
let hidingConstant = (hostMidWidth + indicatorWidth) * inverseMultiplier
return IndicatorPositionConstants(start: start * multiplier,
startBounce: startBounce,
end: endBounce,
hidingConstant: hidingConstant)
}
//swiftlint:enable function_parameter_count
///Adds the indicator in the hostView
///- Parameter hostView: the menu's hostView
///- Parameter tableView: the menu's tableView
///- Parameter position: the indicator initial position in %
func addIn(_ hostView: UIView,
tableView: UITableView,
position: CGFloat) {
self.translatesAutoresizingMaskIntoConstraints = false
hostView.addSubview(self)
topConstraint = CariocaMenu.equalConstraint(self, toItem: tableView, attribute: .top)
horizontalConstraint = makeHorizontalConstraint(hostView, NSLayoutAttribute.centerX)
hostView.addConstraints([
NSLayoutConstraint(item: self,
attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute,
multiplier: 1, constant: frame.size.width),
NSLayoutConstraint(item: self,
attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute,
multiplier: 1, constant: frame.size.height),
topConstraint,
horizontalConstraint
])
topConstraint.constant = verticalConstant(for: position,
hostHeight: hostView.frame.height,
height: frame.height)
}
///Calculates the Y constraint based on percentage.
///A margin of 50% of the indicator view is applied for security.
///- Parameter percentage: The desired position percentage
///- Parameter hostHeight: The host's height
///- Parameter height: The indicator's height
///- Returns: CGFloat: The constant calculated Y value
private func verticalConstant(for percentage: CGFloat,
hostHeight: CGFloat,
height: CGFloat) -> CGFloat {
let demiHeight = height / 2.0
let min = demiHeight
let max = hostHeight - (height + demiHeight)
let desiredPosition = ((hostHeight / 100.0) * percentage) - demiHeight
//Check the minimum/maximum
return desiredPosition < min ? min : desiredPosition > max ? max : desiredPosition
}
///Create the horizontal constraint
///- Parameter hostView: The menu's hostView
///- Parameter attribute: The layoutAttribute for the constraint
///- Parameter priority: The constraint's priority
///- Returns: NSLayoutConstraint the horizontal constraint
private func makeHorizontalConstraint(_ hostView: UIView,
_ attribute: NSLayoutAttribute) -> NSLayoutConstraint {
return NSLayoutConstraint(item: self,
attribute: attribute, relatedBy: .equal,
toItem: hostView, attribute: attribute,
multiplier: 1, constant: 0.0)
}
///Draws the shape, depending on the edge.
///- Parameter frame: The IndicatorView's frame
override public func draw(_ frame: CGRect) {
applyMarginConstraints(margins: config.iconMargins(for: edge))
let ovalPath = config.shape(for: edge, frame: frame)
config.color.setFill()
ovalPath.fill()
}
///Applies the margins to the iconView
///- Parameter margins: Tuple of margins in CSS Style (Top, Right, Bottom, left)
private func applyMarginConstraints(margins: (top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat)) {
iconConstraints[0].constant = margins.top
iconConstraints[1].constant = margins.right
iconConstraints[2].constant = margins.bottom
iconConstraints[3].constant = margins.left
setNeedsLayout()
}
///Calls the positionConstants() with all internal parameters
///- Returns: IndicatorPositionConstants All the possible calculated positions
private func positionValues(_ hostView: UIView) -> IndicatorPositionConstants {
let insets = insetsValues(hostView.insets(),
orientation: UIDevice.current.orientation,
edge: edge)
return CariocaIndicatorView.positionConstants(hostWidth: hostView.frame.width,
indicatorWidth: frame.width,
edge: edge,
borderMargin: config.borderMargin,
bouncingValues: config.bouncingValues,
startInset: insets.start,
endInset: insets.end)
}
///When the hostView has rotated, re-apply the constraints.
///This should have an effect only on iPhone X, because of the view edges.
///- Parameter hostView: The menu's hostView
func repositionXAfterRotation(_ hostView: UIView) {
let positions = positionValues(hostView)
horizontalConstraint.constant = positions.start
}
///Calculates inset values, depending on orientation.
///The goal is to only have the inset on the indicator when the edge of the indicator is on the side of the notch.
///- Parameter insets: The original insets
///- Parameter orientation: The screen orientation
///- Parameter edge: The screen edge
///- Returns: Start end End insets for the indicator.
func insetsValues(_ insets: UIEdgeInsets,
orientation: UIDeviceOrientation,
edge: UIRectEdge) -> (start: CGFloat, end: CGFloat) {
var startInset = edge == .left ? insets.left : insets.right
let endInset = edge == .left ? insets.right : insets.left
if (orientation == .landscapeLeft && edge == .right) || //The notch is on the left side
(orientation == .landscapeRight && edge == .left) { //The notch is on the right side
startInset = 0.0
}
//Special case to not put the at the notch level
//35.0 is the limit of the notch.
startInset = startInset == 44.0 ? (35.0 - config.borderMargin) : startInset
return (start: startInset, end: endInset)
}
///Show the indicator on a specific edge, by animating the horizontal position
///- Parameter edge: The screen edge
///- Parameter hostView: The menu's hostView, to calculate the positions
///- Parameter isTraversingView: Should the indicator traverse the hostView, and stick to the opposite edge ?
func show(edge: UIRectEdge, hostView: UIView, isTraversingView: Bool) {
guard let superView = self.superview else { return }
self.state = .showing
self.edge = edge
self.setNeedsDisplay()
let positions = positionValues(hostView)
horizontalConstraint.constant = positions.startBounce.from
superview?.layoutIfNeeded()
let animationValueOne = isTraversingView ? positions.end.from : positions.startBounce.to
let animationValueTwo = isTraversingView ? positions.end.to : positions.start
animation(superView, constraint: horizontalConstraint,
constant: animationValueOne, timing: isTraversingView ? 0.3 : 0.15, options: [.curveEaseIn], finished: {
guard self.state != .restoring else { return /*second show animation cancelled, indicator is restoring*/ }
self.animation(superView, constraint: self.horizontalConstraint,
constant: animationValueTwo, timing: 0.2, options: [.curveEaseOut], finished: {
self.state = .onHold
})
})
}
///Retore the indicator on it's original edge position
///- Parameter hostView: The menu's hostView, to calculate the positions
///- Parameter boomerang: The boomerang type to restore the indicator
///- Parameter initialPosition: The indicator initial position
///- Parameter firstStepDuration: Should equal the time to hide the menu. First animation is 70%, second 30%.
///In boomerang mode, first animation is 125% of that value.
///- Parameter firstStepDone: Called when the first animation is complete, with or without boomerang.
func restore(hostView: UIView,
boomerang: BoomerangType,
initialPosition: CGFloat,
firstStepDuration: Double,
firstStepDone: @escaping () -> Void) {
guard state != .restoring else { return }
self.state = .restoring
let hasBoomerang = boomerang != .none
let positions = positionValues(hostView)
var positionOne: CGFloat, mustSwitchEdge = false //Will the indicator switch of edge ?
var timingAnim1: Double = firstStepDuration * 0.7, timingAnim2: Double = firstStepDuration * 0.3
if hasBoomerang { //Boomerang logic
//the indicator must go out of the view
positionOne = positions.hidingConstant
mustSwitchEdge = (boomerang == .horizontal || boomerang == .originalPosition) && originalEdge != edge
timingAnim1 = firstStepDuration * 1.25
} else {
positionOne = positions.startBounce.from
}
animation(superview!, constraint: horizontalConstraint,
constant: positionOne, timing: timingAnim1, options: [.curveEaseIn], finished: {
if hasBoomerang {
firstStepDone()
let edgeToShow = mustSwitchEdge ? self.edge.opposite() : self.edge
if boomerang == .originalPosition || boomerang == .vertical {
self.topConstraint.constant = self.verticalConstant(for: initialPosition,
hostHeight: hostView.frame.height,
height: self.frame.height)
}
self.state = .onHold
self.show(edge: edgeToShow, hostView: hostView, isTraversingView: false)
} else {
self.animation(self.superview!, constraint: self.horizontalConstraint,
constant: positions.start, timing: timingAnim2, options: [.curveEaseOut], finished: {
firstStepDone()
self.state = .onHold
})
}
})
}
// swiftlint:disable function_parameter_count
///Animate a constraint
///- Parameter view: The view to layoutIfNeeded
///- Parameter constraint: The constraint to animate
///- Parameter constant: The new constant value
///- Parameter timing: The animation duration
///- Parameter options: The animation options
///- Parameter finished: Completion closure, when animation finished
internal func animation(_ view: UIView, constraint: NSLayoutConstraint,
constant: CGFloat, timing: Double,
options: UIViewAnimationOptions,
finished: @escaping () -> Void) {
constraint.constant = constant
UIView.animate(withDuration: timing, delay: 0.0, options: options, animations: {
view.layoutIfNeeded()
}, completion: { _ in finished() })
}
// swiftlint:enable function_parameter_count
///Utility to inverse 2 constraint priorities
///- Parameter main: The highest priority will be applied to that constraint.
///- Parameter second: The lowest priority will be applied to that constraint.
internal func constraintPriorities(main: NSLayoutConstraint,
second: NSLayoutConstraint) {
main.priority = UILayoutPriority(100.0)
second.priority = UILayoutPriority(50.0)
}
///Move the indicator to a specific index, by updating the top constraint value
///- Parameter index: The selection index of the menu, where the indicator will appear
///- Parameter heightForRow: The height of each menu item
func moveTo(index: Int, heightForRow: CGFloat) {
topConstraint.constant = (CGFloat(index) * heightForRow) + ((heightForRow - frame.size.height) / 2.0)
superview?.layoutIfNeeded()
}
///:nodoc:
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
| mit | ef7f46b9e362dc9167caa0cbabc00f15 | 43.160819 | 115 | 0.728001 | 4.156026 | false | false | false | false |
Marquis103/RecipeFinder | RecipeFinder/Recipe.swift | 1 | 819 | //
// Recipe.swift
// RecipeFinder
//
// Created by Marquis Dennis on 5/7/16.
// Copyright © 2016 Marquis Dennis. All rights reserved.
//
import Foundation
typealias Calories = Float
typealias Ingredients = [String]
struct Recipe {
//constants
let title:String
let ingredients: Ingredients
let source: String
//variables
var prepTime: Double?
var cookTime: Double?
var level:Int?
var image:String?
var nutrition:Nutrition?
var url: String?
var imageData:NSData?
//computed properties
var totalTime:Double? {
if let prepTime = prepTime, let cookTime = cookTime {
return prepTime + cookTime
}
return nil
}
}
typealias Grams = Float
typealias Milligrams = Float
struct Nutrition {
let calories:Calories
let fat:Grams
let carbs:Grams
let protein:Grams
let sodium:Milligrams
}
| gpl-3.0 | 95089da6562f42b9a34ddc3a01a6a2f2 | 15.693878 | 57 | 0.726161 | 3.272 | false | false | false | false |
RaviDesai/RSDTesting | Example/Pods/RSDRESTServices/Pod/Classes/Mocks/MockRESTStore.swift | 1 | 11820 | //
// MockRESTStore.swift
// RSDRESTServices
//
// Created by Ravi Desai on 11/05/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Foundation
import RSDSerialization
import OHHTTPStubs
public enum StoreError: ErrorType {
case InvalidId
case NotUnique
case NotFound
case NotAuthorized
case UndefinedError
}
public class MockedRESTStore<T: ModelItem> {
public var host: String?
public var endpoint: String?
private var endpointRegEx: NSRegularExpression?
public var authFilterForReading: (T)->(Bool)
public var authFilterForUpdating: (T)->(Bool)
public var store: [T]
public var createStub: OHHTTPStubsDescriptor?
public var deleteStub: OHHTTPStubsDescriptor?
public var updateStub: OHHTTPStubsDescriptor?
public var getAllStub: OHHTTPStubsDescriptor?
public var getOneStub: OHHTTPStubsDescriptor?
public init(host: String?, endpoint: String, initialValues: [T]?) {
self.host = host
self.endpoint = endpoint
self.authFilterForReading = {(t: T)->(Bool) in return true }
self.authFilterForUpdating = {(t: T)->(Bool) in return true }
let queryPattern = "\(endpoint)/(.+)$"
self.endpointRegEx = try? NSRegularExpression(pattern: queryPattern, options: NSRegularExpressionOptions.CaseInsensitive)
if let initial = initialValues {
self.store = initial
} else {
self.store = []
}
}
public func findIndex(object: T) -> Int? {
for (var index = 0; index < store.count; index++) {
if (store[index] == object) {
return index
}
}
return nil
}
public func verifyUnique(object: T, atIndex: Int?) -> Bool {
for (var index = 0; index < store.count; index++) {
if (index != atIndex) {
if (store[index] ==% object) {
return false
}
}
}
return true
}
public func findIndexOfUUID(id: NSUUID) -> Int? {
for (var index = 0; index < store.count; index++) {
if (store[index].id == id) {
return index
}
}
return nil
}
public func create(object: T) throws -> T? {
if (object.id != nil) {
throw StoreError.InvalidId
}
if (!authFilterForUpdating(object)) {
throw StoreError.NotAuthorized
}
guard verifyUnique(object, atIndex: nil) else {
throw StoreError.NotUnique
}
var item = object
item.id = NSUUID()
store.append(item)
return item
}
public func update(object: T) throws -> T {
guard let index = self.findIndex(object) else {
throw StoreError.NotFound
}
if (!authFilterForUpdating(store[index])) {
throw StoreError.NotAuthorized
}
guard verifyUnique(object, atIndex: index) else {
throw StoreError.NotUnique
}
self.store[index] = object
return object
}
public func delete(uuid: NSUUID) throws -> T? {
guard let index = findIndexOfUUID(uuid) else {
throw StoreError.NotFound
}
if (!authFilterForUpdating(store[index])) {
throw StoreError.NotAuthorized
}
return self.store.removeAtIndex(index)
}
public func get(uuid: NSUUID) throws -> T? {
guard let index = findIndexOfUUID(uuid) else {
throw StoreError.NotFound
}
if (!authFilterForReading(store[index])) {
throw StoreError.NotAuthorized
}
return self.store[index]
}
public func getAll() -> [T] {
return self.store.filter(self.authFilterForReading).sort(<)
}
public func hijackGetAll() {
if (self.getAllStub != nil) { return }
self.getAllStub =
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != self.host) {
return false
}
if (request.URL?.path != self.endpoint) {
return false
}
if (request.HTTPMethod != "GET") {
return false
}
if let queryString = request.URL?.query where queryString != "" {
return false
}
return true
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return MockHTTPResponder<T>.produceArrayResponse(self.getAll(), error: nil)
})
}
public func hijackGetOne() {
if (self.getOneStub != nil) { return }
self.getOneStub =
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != self.host) {
return false
}
if pullIdFromPath(request.URL?.path, regEx: self.endpointRegEx) == nil {
return false
}
if (request.HTTPMethod != "GET") {
return false
}
if let queryString = request.URL?.query where queryString != "" {
return false
}
return true
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return MockHTTPResponder<T>.withIdInPath(request, regEx: self.endpointRegEx, logic: { (requestId) -> OHHTTPStubsResponse in
var response: T?
var responseError: StoreError?
do {
response = try self.get(requestId)
} catch let err as StoreError {
responseError = err
} catch {
responseError = StoreError.UndefinedError
}
return MockHTTPResponder<T>.produceObjectResponse(response, error: responseError)
})
})
}
public func hijackCreate() {
if self.createStub != nil { return }
self.createStub =
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != self.host) {
return false
}
if request.URL?.path != self.endpoint {
return false
}
if (request.HTTPMethod != "POST") {
return false
}
if (MockHTTPResponder<T>.getPostedObject(request) == nil) {
return false
}
return true
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return MockHTTPResponder<T>.withPostedObject(request, logic: { (item) -> OHHTTPStubsResponse in
var response: T?
var responseError: StoreError?
do {
response = try self.create(item)
} catch let err as StoreError {
responseError = err
} catch {
responseError = StoreError.UndefinedError
}
return MockHTTPResponder<T>.produceObjectResponse(response, error: responseError)
})
})
}
public func hijackUpdate() {
if (self.updateStub != nil) { return }
self.updateStub =
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != self.host) {
return false
}
if pullIdFromPath(request.URL?.path, regEx: self.endpointRegEx) == nil {
return false
}
if (request.HTTPMethod != "PUT") {
return false
}
if (MockHTTPResponder<T>.getPostedObject(request) == nil) {
return false
}
return true
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return MockHTTPResponder<T>.withPostedObject(request, logic: { (item) -> OHHTTPStubsResponse in
var response: T?
var responseError: StoreError?
do {
response = try self.update(item)
} catch let err as StoreError {
responseError = err
} catch {
responseError = StoreError.UndefinedError
}
return MockHTTPResponder<T>.produceObjectResponse(response, error: responseError)
})
})
}
public func hijackDelete() {
if (self.deleteStub != nil) { return }
self.deleteStub =
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != self.host) {
return false
}
if pullIdFromPath(request.URL?.path, regEx: self.endpointRegEx) == nil {
return false
}
if (request.HTTPMethod != "DELETE") {
return false
}
return true
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
return MockHTTPResponder<T>.withIdInPath(request, regEx: self.endpointRegEx, logic: { (requestId) -> OHHTTPStubsResponse in
var response: T?
var responseError: StoreError?
do {
response = try self.delete(requestId)
} catch let err as StoreError {
responseError = err
} catch {
responseError = StoreError.UndefinedError
}
return MockHTTPResponder<T>.produceObjectResponse(response, error: responseError)
})
})
}
public func hijackAll() {
self.hijackCreate()
self.hijackDelete()
self.hijackUpdate()
self.hijackGetAll()
self.hijackGetOne()
}
public func unhijackAll() {
if let createStub = self.createStub {
OHHTTPStubs.removeStub(createStub)
self.createStub = nil
}
if let deleteStub = self.deleteStub {
OHHTTPStubs.removeStub(deleteStub)
self.deleteStub = nil
}
if let updateStub = self.updateStub {
OHHTTPStubs.removeStub(updateStub)
self.updateStub = nil
}
if let getAllStub = self.getAllStub {
OHHTTPStubs.removeStub(getAllStub)
self.getAllStub = nil
}
if let getOneStub = self.getOneStub {
OHHTTPStubs.removeStub(getOneStub)
self.getOneStub = nil
}
}
deinit {
self.unhijackAll()
}
}
| mit | 7c200c3d6efb209271704572d36b1a9c | 31.739612 | 143 | 0.483459 | 5.617395 | false | true | false | false |
djones6/swift-benchmarks | jsonEncoderTest.swift | 1 | 3785 | import Foundation
#if os(macOS) || os(iOS)
import Darwin
let CLOCK_MONOTONIC = _CLOCK_MONOTONIC
#else
import Glibc
#endif
let DEBUG = Bool(ProcessInfo.processInfo.environment["DEBUG"] ?? "false") ?? false
let encoder = JSONEncoder()
struct MyValue: Codable {
let int1:Int
let int2:Int
let int3:Int
let int4:Int
let int5:Int
let int6:Int
let int7:Int
let int8:Int
let int9:Int
let int10:Int
init() {
int1 = 1
int2 = 12
int3 = 123
int4 = 1234
int5 = 12345
int6 = 123456
int7 = 1234567
int8 = 12345678
int9 = 123456789
int10 = 1234567890
}
}
// Codable (compatible with JSONEncoder)
let myValue = MyValue()
// Codable dictionary (compatible with JSONEncoder and JSONSerialization)
let myDict: [String:Int] = ["int1": 1, "int2": 12, "int3": 123, "int4": 1234,
"int5": 12345, "int6": 123456, "int7": 1234567, "int8": 12345678,
"int9": 123456789, "int10": 1234567890]
// Array (compatible with JSONSerialization)
//let myArray: [Any] = ["int1", "int2", "int3", "int4", "int5", "int6", "int7", "int8", "int9", "int10", 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890]
// Codable Array (compatible with JSONEncoder and JSONSerialization)
let codableArray: [Int] = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890]
let iterations = 1000
func benchmark(_ work: () -> Void) -> Double {
var start = timespec()
var end = timespec()
clock_gettime(CLOCK_MONOTONIC, &start)
work()
clock_gettime(CLOCK_MONOTONIC, &end)
return (Double(end.tv_sec) * 1.0e9 + Double(end.tv_nsec)) - (Double(start.tv_sec) * 1.0e9 + Double(start.tv_nsec))
}
func jsonEncoder_Struct() {
do {
for i in 1...iterations {
let result = try encoder.encode(myValue)
if DEBUG && i == 1 {
print("Result (JSONEncoder Struct): \(String(data: result, encoding: .utf8) ?? "nil")")
}
}
} catch {
print("Fail")
}
}
func jsonEncoder_Dict() {
do {
for i in 1...iterations {
let result = try encoder.encode(myDict)
if DEBUG && i == 1 {
print("Result (JSONEncoder Dict): \(String(data: result, encoding: .utf8) ?? "nil")")
}
}
} catch {
print("Fail")
}
}
func jsonEncoder_Array() {
do {
for i in 1...iterations {
let result = try encoder.encode(codableArray)
if DEBUG && i == 1 {
print("Result (JSONEncoder Array): \(String(data: result, encoding: .utf8) ?? "nil")")
}
}
} catch {
print("Fail")
}
}
func jsonSerialization_Dict() {
do {
for i in 1...iterations {
let result = try JSONSerialization.data(withJSONObject: myDict)
if DEBUG && i == 1 {
print("Result (JSONSerialization): \(String(data: result, encoding: .utf8) ?? "nil")")
}
}
} catch {
print("Fail")
}
}
func jsonSerialization_Array() {
do {
for i in 1...iterations {
let result = try JSONSerialization.data(withJSONObject: codableArray)
if DEBUG && i == 1 {
print("Result (JSONSerialization): \(String(data: result, encoding: .utf8) ?? "nil")")
}
}
} catch {
print("Fail")
}
}
var timeNanos = benchmark {
jsonEncoder_Struct()
}
print("JSONEncoder (Struct) took \(timeNanos / Double(iterations)) ns")
timeNanos = benchmark {
jsonEncoder_Dict()
}
print("JSONEncoder (Dict) took \(timeNanos / Double(iterations)) ns")
timeNanos = benchmark {
jsonEncoder_Array()
}
print("JSONEncoder (Array) took \(timeNanos / Double(iterations)) ns")
timeNanos = benchmark {
jsonSerialization_Dict()
}
print("JSONSerialization (Dict) took \(timeNanos / Double(iterations)) ns")
timeNanos = benchmark {
jsonSerialization_Array()
}
print("JSONSerialization (Array) took \(timeNanos / Double(iterations)) ns")
| mit | a8badfa809a0f7965f236d13b06c7c40 | 24.233333 | 179 | 0.631176 | 3.412985 | false | false | false | false |
manavgabhawala/UberSDK | UberMacSDK/UberRequestWebView.swift | 1 | 5434 | //
// UberRequestWebView.swift
// UberSDK
//
// Created by Manav Gabhawala on 6/13/15.
//
//
import Cocoa
import WebKit
import CoreLocation
extension UberManager
{
/// Create a new request for the logged in user.
///
/// - parameter startLatitude: The beginning or "pickup" latitude.
/// - parameter startLongitude: The beginning or "pickup" longitude.
/// - parameter endLatitude: The final or destination latitude.
/// - parameter endLongitude: The final or destination longitude.
/// - parameter productID: The unique ID of the product being requested.
/// - parameter view: The view on which to show any surges if applicable.
/// - parameter surge: An optional string that allows you to specify the surge ID returned by Uber if surges are applicable. Don't worry about this parameter just ensure the view passed in is visible and surges will be taken care of automatically.
/// - parameter success: The block of code to be executed on a successful creation of the request.
/// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information.
/// - Warning: User authentication must be completed before calling this function.
@objc public func createRequest(startLatitude startLatitude: Double, startLongitude: Double, endLatitude: Double, endLongitude: Double, productID: String, surgeView view: NSView, surgeID surge : String? = nil, completionBlock success: UberRequestSuccessBlock, errorHandler failure: UberErrorHandler?)
{
createRequest(startLatitude: startLatitude, startLongitude: startLongitude, endLatitude: endLatitude, endLongitude: endLongitude, productID: productID, surgeConfirmation: nil, completionBlock: success, errorHandler: { error in
guard let JSON = error.JSON
else { failure?(error); return }
if error.errorCode == "surge"
{
guard let meta = JSON["meta"], let surgeDict = meta["surge_confirmation"] as? [NSObject : AnyObject], let href = surgeDict["href"] as? String
else
{
failure?(error)
return
}
let webView = WebView(frame: view.frame)
webView.policyDelegate = self
self.surgeLock.lock()
webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: href)!))
view.addSubview(webView)
self.surgeLock.lock()
self.createRequest(startLatitude: startLatitude, startLongitude: startLongitude, endLatitude: endLatitude, endLongitude: endLongitude, productID: productID, surgeView: view, surgeID : self.surgeCode, completionBlock: success, errorHandler: failure)
}
else if error.errorCode == "retry_request"
{
self.createRequest(startLatitude: startLatitude, startLongitude: startLongitude, endLatitude: endLatitude, endLongitude: endLongitude, productID: productID, surgeView: view, surgeID : self.surgeCode, completionBlock: success, errorHandler: failure)
}
else
{
failure?(error)
}
})
}
/// Create a new request for the logged in user.
///
/// - parameter startLocation: The beginning or "pickup" location.
/// - parameter endLocation: The final or destination location.
/// - parameter productID: The unique ID of the product being requested.
/// - parameter view: The view on which to show any surges if applicable.
/// - parameter success: The block of code to be executed on a successful creation of the request.
/// - parameter failure: This block is called if an error occurs. This block takes an `UberError` argument and returns nothing. In most cases a properly formed `UberError` object will be returned but in some very rare cases an Unknown Uber Error can be returned when there it is not possible for us to recover any error information.
/// - Warning: User authentication must be completed before calling this function.
@objc public func createRequest(startLocation: CLLocation, endLocation: CLLocation, productID: String, surgeView view: NSView, completionBlock success: UberRequestSuccessBlock, errorHandler failure: UberErrorHandler?)
{
createRequest(startLatitude: startLocation.coordinate.latitude, startLongitude: startLocation.coordinate.latitude, endLatitude: endLocation.coordinate.latitude, endLongitude: endLocation.coordinate.longitude, productID: productID, surgeView: view, surgeID : self.surgeCode, completionBlock: success, errorHandler: failure)
}
}
extension UberManager : WebPolicyDelegate
{
public func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!)
{
guard let URL = request.URL?.absoluteString where URL.hasPrefix(delegate.surgeConfirmationRedirectURI)
else
{
listener.use()
return
}
var code : String?
if let URLParams = request.URL?.query?.componentsSeparatedByString("&")
{
for param in URLParams
{
let keyValue = param.componentsSeparatedByString("=")
let key = keyValue.first
if key == "code"
{
code = keyValue.last
}
}
}
guard let theCode = code
else
{
listener.use()
return
}
webView.removeFromSuperview()
surgeCode = theCode
surgeLock.unlock()
}
} | apache-2.0 | 5093906051e8a5a8484598330df371bb | 49.324074 | 336 | 0.741627 | 4.222222 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Sawtooth Wave Oscillator Operation.xcplaygroundpage/Contents.swift | 1 | 634 | //: ## Sawtooth Wave Oscillator Operation
//: ### Maybe the most annoying sound ever. Sorry.
import XCPlayground
import AudioKit
//: Set up the operations that will be used to make a generator node
let generator = AKOperationGenerator() { _ in
let freq = AKOperation.jitter(amplitude: 200, minimumFrequency: 1, maximumFrequency: 10) + 200
let amp = AKOperation.randomVertexPulse(minimum: 0, maximum: 0.3, updateFrequency: 1)
return AKOperation.sawtoothWave(frequency: freq, amplitude: amp)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit | 1892213e61bc098aa8e573595711a30e | 32.368421 | 98 | 0.76183 | 4.372414 | false | false | false | false |
benlangmuir/swift | test/Parse/ifconfig_expr.swift | 5 | 4772 | // RUN: %target-typecheck-verify-swift -D CONDITION_1
postfix operator ++
postfix func ++ (_: Int) -> Int { 0 }
struct OneResult {}
struct TwoResult {}
protocol MyProto {
func optionalMethod() -> [Int]?
}
struct MyStruct {
var optionalMember: MyProto? { nil }
func methodOne() -> OneResult { OneResult() }
func methodTwo() -> TwoResult { TwoResult() }
}
func globalFunc<T>(_ arg: T) -> T { arg }
func testBasic(baseExpr: MyStruct) {
baseExpr
#if CONDITION_1
.methodOne() // expected-warning {{result of call to 'methodOne()' is unused}}
#else
.methodTwo()
#endif
}
MyStruct()
#if CONDITION_1
.methodOne() // expected-warning {{result of call to 'methodOne()' is unused}}
#else
.methodTwo()
#endif
func testInvalidContent(baseExpr: MyStruct, otherExpr: Int) {
baseExpr // expected-warning {{expression of type 'MyStruct' is unused}}
#if CONDITION_1
{ $0 + 1 } // expected-error {{closure expression is unused}}
#endif
baseExpr // expected-warning {{expression of type 'MyStruct' is unused}}
#if CONDITION_1
+ otherExpr // expected-error {{unary operator cannot be separated from its operand}}
// expected-warning@-1 {{result of operator '+' is unused}}
#endif
baseExpr
#if CONDITION_1
.methodOne() // expected-warning {{result of call to 'methodOne()' is unused}}
print("debug") // expected-error {{unexpected tokens in '#if' expression body}}
#endif
}
func testExprKind(baseExpr: MyStruct, idx: Int) {
baseExpr
#if CONDITION_1
.optionalMember?.optionalMethod()![idx]++ // expected-warning {{result of operator '++' is unused}}
#else
.otherMethod(arg) {
//...
}
#endif
baseExpr
#if CONDITION_1
.methodOne() + 12 // expected-error {{unexpected tokens in '#if' expression body}}
// expected-warning@-1 {{result of call to 'methodOne()' is unused}}
#endif
}
func emptyElse(baseExpr: MyStruct) {
baseExpr
#if CONDITION_1
.methodOne() // expected-warning {{result of call to 'methodOne()' is unused}}
#elseif CONDITION_2
// OK. Do nothing.
#endif
baseExpr
#if CONDITION_1
.methodOne() // expected-warning {{result of call to 'methodOne()' is unused}}
#elseif CONDITION_2
return // expected-error {{unexpected tokens in '#if' expression body}}
#endif
}
func consecutiveIfConfig(baseExpr: MyStruct) {
baseExpr
#if CONDITION_1
.methodOne()
#endif
#if CONDITION_2
.methodTwo()
#endif
.unknownMethod() // expected-error {{value of type 'OneResult' has no member 'unknownMethod'}}
}
func nestedIfConfig(baseExpr: MyStruct) {
baseExpr
#if CONDITION_1
#if CONDITION_2
.methodOne()
#endif
#if CONDITION_1
.methodTwo() // expected-warning {{result of call to 'methodTwo()' is unused}}
#endif
#else
.unknownMethod1()
#if CONDITION_2
.unknownMethod2()
#endif
#endif
}
func ifconfigExprInExpr(baseExpr: MyStruct) {
globalFunc( // expected-warning {{result of call to 'globalFunc' is unused}}
baseExpr
#if CONDITION_1
.methodOne()
#else
.methodTwo()
#endif
)
}
func canImportVersioned() {
#if canImport(A, _version: 2)
let a = 1
#endif
#if canImport(A, _version: 2.2)
let a = 1
#endif
#if canImport(A, _version: 2.2.2)
let a = 1
#endif
#if canImport(A, _version: 2.2.2.2)
let a = 1
#endif
#if canImport(A, _version: 2.2.2.2.2) // expected-warning {{trailing components of version '2.2.2.2' are ignored}}
let a = 1
#endif
#if canImport(A, _underlyingVersion: 4)
let a = 1
#endif
#if canImport(A, _underlyingVersion: 2.200)
let a = 1
#endif
#if canImport(A, _underlyingVersion: 2.200.1)
let a = 1
#endif
#if canImport(A, _underlyingVersion: 2.200.1.3)
let a = 1
#endif
#if canImport(A, unknown: 2.2) // expected-error {{2nd parameter of canImport should be labeled as _version or _underlyingVersion}}
let a = 1
#endif
#if canImport(A,) // expected-error {{unexpected ',' separator}}
let a = 1
#endif
#if canImport(A, 2.2) // expected-error {{2nd parameter of canImport should be labeled as _version or _underlyingVersion}}
let a = 1
#endif
#if canImport(A, 2.2, 1.1) // expected-error {{canImport can take only two parameters}}
let a = 1
#endif
#if canImport(A, _version:) // expected-error {{expected expression in list of expressions}}
let a = 1
#endif
#if canImport(A, _version: "") // expected-error {{_version argument cannot be empty}}
let a = 1
#endif
#if canImport(A, _version: >=2.2) // expected-error {{cannot parse module version '>=2.2'}}
let a = 1
#endif
#if canImport(A, _version: 20A301) // expected-error {{'A' is not a valid digit in integer literal}}
let a = 1
#endif
#if canImport(A, _version: "20A301") // expected-error {{cannot parse module version '20A301'}}
let a = 1
#endif
}
| apache-2.0 | fa9cef8073336a1aa09e773c6750d06f | 22.741294 | 131 | 0.663663 | 3.313889 | false | false | false | false |
Zewo/JSON | Source/JSONParser.swift | 1 | 15847 | // JSONParser.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
//
// This file has been modified from its original project Swift-JsonSerializer
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public enum JSONParseError: Error, CustomStringConvertible {
case unexpectedTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case insufficientTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case extraTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case nonStringKeyError(reason: String, lineNumber: Int, columnNumber: Int)
case invalidStringError(reason: String, lineNumber: Int, columnNumber: Int)
case invalidNumberError(reason: String, lineNumber: Int, columnNumber: Int)
public var description: String {
switch self {
case .unexpectedTokenError(let r, let l, let c):
return "UnexpectedTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case .insufficientTokenError(let r, let l, let c):
return "InsufficientTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case .extraTokenError(let r, let l, let c):
return "ExtraTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case .nonStringKeyError(let r, let l, let c):
return "NonStringKeyError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case .invalidStringError(let r, let l, let c):
return "InvalidStringError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case .invalidNumberError(let r, let l, let c):
return "InvalidNumberError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
}
}
}
public struct JSONParser {
public init() {}
public func parse(data: Data) throws -> JSON {
return try GenericJSONParser(data).parse()
}
}
class GenericJSONParser<ByteSequence: Collection> where ByteSequence.Iterator.Element == UInt8 {
typealias Source = ByteSequence
typealias Char = Source.Iterator.Element
let source: Source
var cur: Source.Index
let end: Source.Index
var lineNumber = 1
var columnNumber = 1
init(_ source: Source) {
self.source = source
self.cur = source.startIndex
self.end = source.endIndex
}
func parse() throws -> JSON {
let JSON = try parseValue()
skipWhitespaces()
if (cur == end) {
return JSON
} else {
throw JSONParseError.extraTokenError(
reason: "extra tokens found",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
}
// MARK: - Private
extension GenericJSONParser {
fileprivate func parseValue() throws -> JSON {
skipWhitespaces()
if cur == end {
throw JSONParseError.insufficientTokenError(
reason: "unexpected end of tokens",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
switch currentChar {
case Char(ascii: "n"): return try parseSymbol("null", JSON.null)
case Char(ascii: "t"): return try parseSymbol("true", JSON.boolean(true))
case Char(ascii: "f"): return try parseSymbol("false", JSON.boolean(false))
case Char(ascii: "-"), Char(ascii: "0") ... Char(ascii: "9"): return try parseNumber()
case Char(ascii: "\""): return try parseString()
case Char(ascii: "{"): return try parseObject()
case Char(ascii: "["): return try parseArray()
case (let c): throw JSONParseError.unexpectedTokenError(
reason: "unexpected token: \(c)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private var currentChar: Char {
return source[cur]
}
private var nextChar: Char {
return source[source.index(after: cur)]
}
private var currentSymbol: Character {
return Character(UnicodeScalar(currentChar))
}
private func parseSymbol(_ target: StaticString, _ iftrue: @autoclosure (Void) -> JSON) throws -> JSON {
if expect(target) {
return iftrue()
} else {
throw JSONParseError.unexpectedTokenError(
reason: "expected \"\(target)\" but \(currentSymbol)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private func parseString() throws -> JSON {
assert(currentChar == Char(ascii: "\""), "points a double quote")
advance()
var buffer: [CChar] = []
LOOP: while cur != end {
switch currentChar {
case Char(ascii: "\\"):
advance()
if (cur == end) {
throw JSONParseError.invalidStringError(
reason: "unexpected end of a string literal",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
if let c = parseEscapedChar() {
for u in String(c).utf8 {
buffer.append(CChar(bitPattern: u))
}
} else {
throw JSONParseError.invalidStringError(
reason: "invalid escape sequence",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
case Char(ascii: "\""): break LOOP
default: buffer.append(CChar(bitPattern: currentChar))
}
advance()
}
if !expect("\"") {
throw JSONParseError.invalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
buffer.append(0)
let s = String(validatingUTF8: buffer)!
return .string(s)
}
private func parseEscapedChar() -> UnicodeScalar? {
let c = UnicodeScalar(currentChar)
if c == "u" {
var length = 0
var value: UInt32 = 0
while let d = hexToDigit(nextChar) {
advance()
length += 1
if length > 8 {
break
}
value = (value << 4) | d
}
if length < 2 {
return nil
}
return UnicodeScalar(value)
} else {
let c = UnicodeScalar(currentChar)
return unescapeMapping[c] ?? c
}
}
private func parseNumber() throws -> JSON {
let sign = expect("-") ? -1.0 : 1.0
var integer: Int64 = 0
switch currentChar {
case Char(ascii: "0"): advance()
case Char(ascii: "1") ... Char(ascii: "9"):
while cur != end {
if let value = digitToInt(currentChar) {
integer = (integer * 10) + Int64(value)
} else {
break
}
advance()
}
default:
throw JSONParseError.invalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
if integer != Int64(Double(integer)) {
throw JSONParseError.invalidNumberError(
reason: "too large number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
var fraction: Double = 0.0
if expect(".") {
var factor = 0.1
var fractionLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
fraction += (Double(value) * factor)
factor /= 10
fractionLength += 1
} else {
break
}
advance()
}
if fractionLength == 0 {
throw JSONParseError.invalidNumberError(
reason: "insufficient fraction part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
var exponent: Int64 = 0
if expect("e") || expect("E") {
var expSign: Int64 = 1
if expect("-") {
expSign = -1
} else if expect("+") {}
exponent = 0
var exponentLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
exponent = (exponent * 10) + Int64(value)
exponentLength += 1
} else {
break
}
advance()
}
if exponentLength == 0 {
throw JSONParseError.invalidNumberError(
reason: "insufficient exponent part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
exponent *= expSign
}
return .number(JSON.Number.double(sign * (Double(integer) + fraction) * pow(10, Double(exponent))))
}
private func parseObject() throws -> JSON {
assert(currentChar == Char(ascii: "{"), "points \"{\"")
advance()
skipWhitespaces()
var object: [String: JSON] = [:]
LOOP: while cur != end && !expect("}") {
let keyValue = try parseValue()
switch keyValue {
case .string(let key):
skipWhitespaces()
if !expect(":") {
throw JSONParseError.unexpectedTokenError(
reason: "missing colon (:)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
skipWhitespaces()
let value = try parseValue()
object[key] = value
skipWhitespaces()
if expect(",") {
break
} else if expect("}") {
break LOOP
} else {
throw JSONParseError.unexpectedTokenError(
reason: "missing comma (,)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
default:
throw JSONParseError.nonStringKeyError(
reason: "unexpected value for object key",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return .object(object)
}
private func parseArray() throws -> JSON {
assert(currentChar == Char(ascii: "["), "points \"[\"")
advance()
skipWhitespaces()
var array: [JSON] = []
LOOP: while cur != end && !expect("]") {
let JSON = try parseValue()
skipWhitespaces()
array.append(JSON)
if expect(",") {
continue
} else if expect("]") {
break LOOP
} else {
throw JSONParseError.unexpectedTokenError(
reason: "missing comma (,) (token: \(currentSymbol))",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return .array(array)
}
private func expect(_ target: StaticString) -> Bool {
if cur == end {
return false
}
if !isIdentifier(target.utf8Start.pointee) {
if target.utf8Start.pointee == currentChar {
advance()
return true
} else {
return false
}
}
let start = cur
let l = lineNumber
let c = columnNumber
var p = target.utf8Start
let endp = p.advanced(by: Int(target.utf8CodeUnitCount))
while p != endp {
if p.pointee != currentChar {
cur = start
lineNumber = l
columnNumber = c
return false
}
p += 1
advance()
}
return true
}
// only "true", "false", "null" are identifiers
private func isIdentifier(_ char: Char) -> Bool {
switch char {
case Char(ascii: "a") ... Char(ascii: "z"):
return true
default:
return false
}
}
private func advance() {
assert(cur != end, "out of range")
cur = source.index(after: cur)
if cur != end {
switch currentChar {
case Char(ascii: "\n"):
lineNumber += 1
columnNumber = 1
default:
columnNumber += 1
}
}
}
fileprivate func skipWhitespaces() {
while cur != end {
switch currentChar {
case Char(ascii: " "), Char(ascii: "\t"), Char(ascii: "\r"), Char(ascii: "\n"):
break
default:
return
}
advance()
}
}
}
let unescapeMapping: [UnicodeScalar: UnicodeScalar] = [
"t": "\t",
"r": "\r",
"n": "\n"
]
let escapeMapping: [Character: String] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
"\r\n": "\\r\\n"
]
let hexMapping: [UnicodeScalar: UInt32] = [
"0": 0x0,
"1": 0x1,
"2": 0x2,
"3": 0x3,
"4": 0x4,
"5": 0x5,
"6": 0x6,
"7": 0x7,
"8": 0x8,
"9": 0x9,
"a": 0xA, "A": 0xA,
"b": 0xB, "B": 0xB,
"c": 0xC, "C": 0xC,
"d": 0xD, "D": 0xD,
"e": 0xE, "E": 0xE,
"f": 0xF, "F": 0xF
]
let digitMapping: [UnicodeScalar:Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
]
public func escapeAsJSON(_ source : String) -> String {
var s = "\""
for c in source.characters {
if let escapedSymbol = escapeMapping[c] {
s.append(escapedSymbol)
} else {
s.append(c)
}
}
s.append("\"")
return s
}
func digitToInt(_ byte: UInt8) -> Int? {
return digitMapping[UnicodeScalar(byte)]
}
func hexToDigit(_ byte: UInt8) -> UInt32? {
return hexMapping[UnicodeScalar(byte)]
}
| mit | 76041bd1bfab2b28a108b40ef3ed1b5d | 27.97075 | 108 | 0.50224 | 4.791956 | false | false | false | false |
bitjammer/swift | test/SILGen/specialize_attr.swift | 1 | 4898 | // RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s
// CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float)
// CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
@_specialize(where T == Int, U == Float)
func specializeThis<T, U>(_ t: T, u: U) {}
public protocol PP {
associatedtype PElt
}
public protocol QQ {
associatedtype QElt
}
public struct RR : PP {
public typealias PElt = Float
}
public struct SS : QQ {
public typealias QElt = Int
}
public struct GG<T : PP> {}
// CHECK-LABEL: public class CC<T> where T : PP {
// CHECK-NEXT: @_specialize(exported: false, kind: full, where T == RR, U == SS)
// CHECK-NEXT: @inline(never) public func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ
public class CC<T : PP> {
@inline(never)
@_specialize(where T == RR, U == SS)
public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4Thisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
// -----------------------------------------------------------------------------
// Test user-specialized subscript accessors.
public protocol TestSubscriptable {
associatedtype Element
subscript(i: Int) -> Element { get set }
}
public class ASubscriptable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
get {
return storage[i]
}
@_specialize(where Element == Int)
set(rhs) {
storage[i] = rhs
}
}
}
// ASubscriptable.subscript.getter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
// ASubscriptable.subscript.setter with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
// ASubscriptable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_T015specialize_attr14ASubscriptableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
public class Addressable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(where Element == Int)
unsafeAddress {
return UnsafePointer<Element>(storage + i)
}
@_specialize(where Element == Int)
unsafeMutableAddress {
return UnsafeMutablePointer<Element>(storage + i)
}
}
}
// Addressable.subscript.getter with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_T015specialize_attr11AddressableC9subscriptxSicfg : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
// Addressable.subscript.unsafeAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicflu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
// Addressable.subscript.setter with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_T015specialize_attr11AddressableC9subscriptxSicfs : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
// Addressable.subscript.unsafeMutableAddressor with _specialize
// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableC9subscriptxSicfau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
// Addressable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_T015specialize_attr11AddressableC9subscriptxSicfm : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
| apache-2.0 | 04b5a15d659c3cd8abab8c0575815afc | 44.351852 | 284 | 0.701307 | 3.844584 | false | false | false | false |
terryokay/learnAnimationBySwift | learnAnimation/learnAnimation/AppDelegate.swift | 1 | 1459 | //
// AppDelegate.swift
// learnAnimation
//
// Created by likai on 2017/4/14.
// Copyright © 2017年 terry. All rights reserved.
//
import UIKit
/*
Swift version Animations - https://github.com/YouXianMing/Swift-Animations
Lateast no warning version : Xcode Version 8.2.1 (8C1002)
QQ 705786299
Email [email protected]
http://www.cnblogs.com/YouXianMing/
https://github.com/YouXianMing
https://github.com/YouXianMing/YoCelsius
AppStore : https://itunes.apple.com/us/app/yocelsius/id967721892?l=zh&ls=1&mt=8
Video : http://my.jikexueyuan.com/YouXianMing/record/
*/
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
window.backgroundColor = UIColor.white
let controller = AnimationsListViewController()
let rootViewController = RootNavigationViewController(rootViewController: controller, hideTabBar: true)
window.rootViewController = rootViewController
window.makeKeyAndVisible()
}
return true
}
}
| mit | ef36512cf5ede432adc2ff15e81085b7 | 22.111111 | 144 | 0.635989 | 4.564263 | false | false | false | false |
SimonFairbairn/SwiftyMarkdown | Playground/SwiftyMarkdown.playground/Sources/SwiftyMarkdown.swift | 1 | 15217 | import Foundation
import UIKit
enum CharacterStyle : CharacterStyling {
case none
case bold
case italic
case code
case link
case image
}
enum MarkdownLineStyle : LineStyling {
var shouldTokeniseLine: Bool {
switch self {
case .codeblock:
return false
default:
return true
}
}
case h1
case h2
case h3
case h4
case h5
case h6
case previousH1
case previousH2
case body
case blockquote
case codeblock
case unorderedList
func styleIfFoundStyleAffectsPreviousLine() -> LineStyling? {
switch self {
case .previousH1:
return MarkdownLineStyle.h1
case .previousH2:
return MarkdownLineStyle.h2
default :
return nil
}
}
}
@objc public enum FontStyle : Int {
case normal
case bold
case italic
case boldItalic
}
@objc public protocol FontProperties {
var fontName : String? { get set }
var color : UIColor { get set }
var fontSize : CGFloat { get set }
var fontStyle : FontStyle { get set }
}
@objc public protocol LineProperties {
var alignment : NSTextAlignment { get set }
}
/**
A class defining the styles that can be applied to the parsed Markdown. The `fontName` property is optional, and if it's not set then the `fontName` property of the Body style will be applied.
If that is not set, then the system default will be used.
*/
@objc open class BasicStyles : NSObject, FontProperties {
public var fontName : String?
public var color = UIColor.black
public var fontSize : CGFloat = 0.0
public var fontStyle : FontStyle = .normal
}
@objc open class LineStyles : NSObject, FontProperties, LineProperties {
public var fontName : String?
public var color = UIColor.black
public var fontSize : CGFloat = 0.0
public var fontStyle : FontStyle = .normal
public var alignment: NSTextAlignment = .left
}
/// A class that takes a [Markdown](https://daringfireball.net/projects/markdown/) string or file and returns an NSAttributedString with the applied styles. Supports Dynamic Type.
@objc open class SwiftyMarkdown: NSObject {
static let lineRules = [
LineRule(token: "=", type: MarkdownLineStyle.previousH1, removeFrom: .entireLine, changeAppliesTo: .previous),
LineRule(token: "-", type: MarkdownLineStyle.previousH2, removeFrom: .entireLine, changeAppliesTo: .previous),
LineRule(token: " ", type: MarkdownLineStyle.codeblock, removeFrom: .leading, shouldTrim: false),
LineRule(token: "\t", type: MarkdownLineStyle.codeblock, removeFrom: .leading, shouldTrim: false),
LineRule(token: ">",type : MarkdownLineStyle.blockquote, removeFrom: .leading),
LineRule(token: "- ",type : MarkdownLineStyle.unorderedList, removeFrom: .leading),
LineRule(token: "###### ",type : MarkdownLineStyle.h6, removeFrom: .both),
LineRule(token: "##### ",type : MarkdownLineStyle.h5, removeFrom: .both),
LineRule(token: "#### ",type : MarkdownLineStyle.h4, removeFrom: .both),
LineRule(token: "### ",type : MarkdownLineStyle.h3, removeFrom: .both),
LineRule(token: "## ",type : MarkdownLineStyle.h2, removeFrom: .both),
LineRule(token: "# ",type : MarkdownLineStyle.h1, removeFrom: .both)
]
static let characterRules = [
CharacterRule(openTag: "", escapeCharacter: "\\", styles: [1 : [CharacterStyle.image]], maxTags: 1),
CharacterRule(openTag: "[", intermediateTag: "](", closingTag: ")", escapeCharacter: "\\", styles: [1 : [CharacterStyle.link]], maxTags: 1),
CharacterRule(openTag: "`", intermediateTag: nil, closingTag: nil, escapeCharacter: "\\", styles: [1 : [CharacterStyle.code]], maxTags: 1, cancels: .allRemaining),
CharacterRule(openTag: "*", intermediateTag: nil, closingTag: nil, escapeCharacter: "\\", styles: [1 : [CharacterStyle.italic], 2 : [CharacterStyle.bold], 3 : [CharacterStyle.bold, CharacterStyle.italic]], maxTags: 3),
CharacterRule(openTag: "_", intermediateTag: nil, closingTag: nil, escapeCharacter: "\\", styles: [1 : [CharacterStyle.italic], 2 : [CharacterStyle.bold], 3 : [CharacterStyle.bold, CharacterStyle.italic]], maxTags: 3)
]
let lineProcessor = SwiftyLineProcessor(rules: SwiftyMarkdown.lineRules, defaultRule: MarkdownLineStyle.body)
let tokeniser = SwiftyTokeniser(with: SwiftyMarkdown.characterRules)
/// The styles to apply to any H1 headers found in the Markdown
open var h1 = LineStyles()
/// The styles to apply to any H2 headers found in the Markdown
open var h2 = LineStyles()
/// The styles to apply to any H3 headers found in the Markdown
open var h3 = LineStyles()
/// The styles to apply to any H4 headers found in the Markdown
open var h4 = LineStyles()
/// The styles to apply to any H5 headers found in the Markdown
open var h5 = LineStyles()
/// The styles to apply to any H6 headers found in the Markdown
open var h6 = LineStyles()
/// The default body styles. These are the base styles and will be used for e.g. headers if no other styles override them.
open var body = LineStyles()
/// The styles to apply to any blockquotes found in the Markdown
open var blockquotes = LineStyles()
/// The styles to apply to any links found in the Markdown
open var link = BasicStyles()
/// The styles to apply to any bold text found in the Markdown
open var bold = BasicStyles()
/// The styles to apply to any italic text found in the Markdown
open var italic = BasicStyles()
/// The styles to apply to any code blocks or inline code text found in the Markdown
open var code = BasicStyles()
public var underlineLinks : Bool = false
var currentType : MarkdownLineStyle = .body
let string : String
let tagList = "!\\_*`[]()"
let validMarkdownTags = CharacterSet(charactersIn: "!\\_*`[]()")
/**
- parameter string: A string containing [Markdown](https://daringfireball.net/projects/markdown/) syntax to be converted to an NSAttributedString
- returns: An initialized SwiftyMarkdown object
*/
public init(string : String ) {
self.string = string
super.init()
if #available(iOS 13.0, *) {
self.setFontColorForAllStyles(with: .label)
}
}
/**
A failable initializer that takes a URL and attempts to read it as a UTF-8 string
- parameter url: The location of the file to read
- returns: An initialized SwiftyMarkdown object, or nil if the string couldn't be read
*/
public init?(url : URL ) {
do {
self.string = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) as String
} catch {
self.string = ""
return nil
}
super.init()
if #available(iOS 13.0, *) {
self.setFontColorForAllStyles(with: .label)
}
}
/**
Set font size for all styles
- parameter size: size of font
*/
open func setFontSizeForAllStyles(with size: CGFloat) {
h1.fontSize = size
h2.fontSize = size
h3.fontSize = size
h4.fontSize = size
h5.fontSize = size
h6.fontSize = size
body.fontSize = size
italic.fontSize = size
bold.fontSize = size
code.fontSize = size
link.fontSize = size
link.fontSize = size
}
open func setFontColorForAllStyles(with color: UIColor) {
h1.color = color
h2.color = color
h3.color = color
h4.color = color
h5.color = color
h6.color = color
body.color = color
italic.color = color
bold.color = color
code.color = color
link.color = color
blockquotes.color = color
}
open func setFontNameForAllStyles(with name: String) {
h1.fontName = name
h2.fontName = name
h3.fontName = name
h4.fontName = name
h5.fontName = name
h6.fontName = name
body.fontName = name
italic.fontName = name
bold.fontName = name
code.fontName = name
link.fontName = name
blockquotes.fontName = name
}
/**
Generates an NSAttributedString from the string or URL passed at initialisation. Custom fonts or styles are applied to the appropriate elements when this method is called.
- returns: An NSAttributedString with the styles applied
*/
open func attributedString() -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: "")
self.lineProcessor.processEmptyStrings = MarkdownLineStyle.body
let foundAttributes : [SwiftyLine] = lineProcessor.process(self.string)
for line in foundAttributes {
let finalTokens = self.tokeniser.process(line.line)
attributedString.append(attributedStringFor(tokens: finalTokens, in: line))
attributedString.append(NSAttributedString(string: "\n"))
}
return attributedString
}
}
extension SwiftyMarkdown {
func font( for line : SwiftyLine, characterOverride : CharacterStyle? = nil ) -> UIFont {
let textStyle : UIFont.TextStyle
var fontName : String?
var fontSize : CGFloat?
var globalBold = false
var globalItalic = false
let style : FontProperties
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1:
style = self.h1
if #available(iOS 9, *) {
textStyle = UIFont.TextStyle.title1
} else {
textStyle = UIFont.TextStyle.headline
}
case .h2:
style = self.h2
if #available(iOS 9, *) {
textStyle = UIFont.TextStyle.title2
} else {
textStyle = UIFont.TextStyle.headline
}
case .h3:
style = self.h3
if #available(iOS 9, *) {
textStyle = UIFont.TextStyle.title2
} else {
textStyle = UIFont.TextStyle.subheadline
}
case .h4:
style = self.h4
textStyle = UIFont.TextStyle.headline
case .h5:
style = self.h5
textStyle = UIFont.TextStyle.subheadline
case .h6:
style = self.h6
textStyle = UIFont.TextStyle.footnote
case .codeblock:
style = self.code
textStyle = UIFont.TextStyle.body
case .blockquote:
style = self.blockquotes
textStyle = UIFont.TextStyle.body
default:
style = self.body
textStyle = UIFont.TextStyle.body
}
fontName = style.fontName
fontSize = style.fontSize
switch style.fontStyle {
case .bold:
globalBold = true
case .italic:
globalItalic = true
case .boldItalic:
globalItalic = true
globalBold = true
case .normal:
break
}
if fontName == nil {
fontName = body.fontName
}
if let characterOverride = characterOverride {
switch characterOverride {
case .code:
fontName = code.fontName ?? fontName
fontSize = code.fontSize
case .link:
fontName = link.fontName ?? fontName
fontSize = link.fontSize
case .bold:
fontName = bold.fontName ?? fontName
fontSize = bold.fontSize
globalBold = true
case .italic:
fontName = italic.fontName ?? fontName
fontSize = italic.fontSize
globalItalic = true
default:
break
}
}
fontSize = fontSize == 0.0 ? nil : fontSize
var font : UIFont
if let existentFontName = fontName {
font = UIFont.preferredFont(forTextStyle: textStyle)
let finalSize : CGFloat
if let existentFontSize = fontSize {
finalSize = existentFontSize
} else {
let styleDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
finalSize = styleDescriptor.fontAttributes[.size] as? CGFloat ?? CGFloat(14)
}
if let customFont = UIFont(name: existentFontName, size: finalSize) {
let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
font = fontMetrics.scaledFont(for: customFont)
} else {
font = UIFont.preferredFont(forTextStyle: textStyle)
}
} else {
font = UIFont.preferredFont(forTextStyle: textStyle)
}
if globalItalic, let italicDescriptor = font.fontDescriptor.withSymbolicTraits(.traitItalic) {
font = UIFont(descriptor: italicDescriptor, size: 0)
}
if globalBold, let boldDescriptor = font.fontDescriptor.withSymbolicTraits(.traitBold) {
font = UIFont(descriptor: boldDescriptor, size: 0)
}
return font
}
func color( for line : SwiftyLine ) -> UIColor {
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1, .previousH1:
return h1.color
case .h2, .previousH2:
return h2.color
case .h3:
return h3.color
case .h4:
return h4.color
case .h5:
return h5.color
case .h6:
return h6.color
case .body:
return body.color
case .codeblock:
return code.color
case .blockquote:
return blockquotes.color
case .unorderedList:
return body.color
}
}
func attributedStringFor( tokens : [Token], in line : SwiftyLine ) -> NSAttributedString {
var finalTokens = tokens
let finalAttributedString = NSMutableAttributedString()
var attributes : [NSAttributedString.Key : AnyObject] = [:]
let lineProperties : LineProperties
switch line.lineStyle as! MarkdownLineStyle {
case .h1:
lineProperties = self.h1
case .h2:
lineProperties = self.h2
case .h3:
lineProperties = self.h3
case .h4:
lineProperties = self.h4
case .h5:
lineProperties = self.h5
case .h6:
lineProperties = self.h6
case .codeblock:
lineProperties = body
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 20.0
attributes[.paragraphStyle] = paragraphStyle
case .blockquote:
lineProperties = self.blockquotes
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 20.0
attributes[.paragraphStyle] = paragraphStyle
case .unorderedList:
lineProperties = body
finalTokens.insert(Token(type: .string, inputString: "・ "), at: 0)
default:
lineProperties = body
break
}
if lineProperties.alignment != .left {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = lineProperties.alignment
attributes[.paragraphStyle] = paragraphStyle
}
for token in finalTokens {
attributes[.font] = self.font(for: line)
attributes[.foregroundColor] = self.color(for: line)
guard let styles = token.characterStyles as? [CharacterStyle] else {
continue
}
if styles.contains(.italic) {
attributes[.font] = self.font(for: line, characterOverride: .italic)
attributes[.foregroundColor] = self.italic.color
}
if styles.contains(.bold) {
attributes[.font] = self.font(for: line, characterOverride: .bold)
attributes[.foregroundColor] = self.bold.color
}
if styles.contains(.link), let url = token.metadataString {
attributes[.foregroundColor] = self.link.color
attributes[.font] = self.font(for: line, characterOverride: .link)
attributes[.link] = url as AnyObject
if underlineLinks {
attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue as AnyObject
}
}
if styles.contains(.image), let imageName = token.metadataString {
let image1Attachment = NSTextAttachment()
image1Attachment.image = UIImage(named: imageName)
let str = NSAttributedString(attachment: image1Attachment)
finalAttributedString.append(str)
continue
}
if styles.contains(.code) {
attributes[.foregroundColor] = self.code.color
attributes[.font] = self.font(for: line, characterOverride: .code)
} else {
// Switch back to previous font
}
let str = NSAttributedString(string: token.outputString, attributes: attributes)
finalAttributedString.append(str)
}
return finalAttributedString
}
}
| mit | 101e43e1a86c133a219b86fa9711cdac | 28.315992 | 220 | 0.701347 | 3.710071 | false | false | false | false |
mindforce/Projector | Projector/AppDelegate.swift | 1 | 6174 | //
// AppDelegate.swift
// RedmineProject-3.0
//
// Created by Volodymyr Tymofiychuk on 13.01.15.
// Copyright (c) 2015 Volodymyr Tymofiychuk. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Asp.RedmineProject_3_0" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("RedmineProject_3_0", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("RedmineProject_3_0.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| gpl-2.0 | ccd40c2225d74ef36bf04909bec09330 | 54.621622 | 290 | 0.717363 | 5.679853 | false | false | false | false |
hujiaweibujidao/Gank | Gank/Class/TurnChannel/AHTurnChannelViewController.swift | 2 | 5067 | //
// AHTurnChannelViewController.swift
// Gank
//
// Created by CoderAhuan on 2016/12/10.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
class AHTurnChannelViewController: BaseViewController {
// MARK: - property
/// 回调
var turnChannelClouse: ((_ showTags: [String], _ moreTags: [String]) -> Void)?
/// 已显示的tags
var showTagsArray: [String] = [String]()
/// 未显示的tags
var moreTagsArray: [String] = [String]()
fileprivate let listViewY: CGFloat = 70
// MARK: - control
lazy var closeBtn: UIButton = {
let closeBtn = UIButton()
let btnW: CGFloat = 30
let btnF = CGRect(x: kScreen_W - btnW - 5, y: 30, width: btnW, height: btnW)
closeBtn.setImage(UIImage(named: "icon_close_block"), for: .normal)
closeBtn.frame = btnF
closeBtn.addTarget(self, action: #selector(close), for: .touchUpInside)
return closeBtn
}()
lazy var titleView: UIView = {
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: kScreen_W, height: 35));
let titleLable = UILabel(frame: titleView.bounds)
titleLable.text = "频道管理"
titleLable.textAlignment = .center
titleLable.font = UIFont.systemFont(ofSize: 15)
titleLable.textColor = UIColorTextBlock
titleView.addSubview(titleLable)
let lineView = UIView(frame: CGRect(x: 0, y: 34, width: kScreen_W, height: 1))
lineView.backgroundColor = RGBColor(r: 222, g: 222, b: 222, alpha: 1)
titleView.addSubview(lineView)
return titleView
}()
lazy var contentView: UIScrollView = {
let contentView = UIScrollView(frame: self.view.bounds)
return contentView
}()
lazy var listView: AHListView = {
let listView = AHListView(frame: CGRect(x: 0, y: self.listViewY, width: kScreen_W, height: 0))
listView.addTags(titles: self.showTagsArray)
listView.listViewMoveTagClouse = { [unowned self] title in
self.moreListView.addTag(tagTitle: title)
}
return listView
}()
lazy var moreListView: AHMoreListView = {
let moreListView = AHMoreListView(frame: CGRect(x: 0, y: self.listView.MaxY, width: kScreen_W, height: 0))
moreListView.addTags(titles: self.moreTagsArray)
moreListView.listViewAddTagClouse = { [unowned self] title in
self.listView.addTag(tagTitle: title)
}
return moreListView
}()
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.listView.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
self.moreListView.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
self.title = "频道"
view.backgroundColor = UIColorMainBG
contentView.contentSize = CGSize(width: kScreen_W, height: self.moreListView.Height + self.listView.Height + listViewY)
view.addSubview(contentView)
// contentView.addSubview(titleView)
contentView.addSubview(closeBtn)
// 先添加moreListView, 再添加listView
// 确保listView上的btn移动时, 不会被moreListView遮挡
contentView.addSubview(moreListView)
contentView.addSubview(listView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .default
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = .lightContent
}
deinit {
self.listView.removeObserver(self, forKeyPath: "frame")
self.moreListView.removeObserver(self, forKeyPath: "frame")
}
// MARK: - event && methods
func close() {
if turnChannelClouse != nil {
turnChannelClouse!(listView.tagTitleArray, moreListView.tagTitleArray)
}
self.dismiss(animated: true, completion: {})
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" {
let object = object as AnyObject
if object.isKind(of: AHListView.self) {
guard case let frame as CGRect = change?[NSKeyValueChangeKey.newKey] else {
return
}
// 根据AHListView的frame变化更新moreListView的Y
self.moreListView.Y = frame.maxY
} else if object.isKind(of: AHMoreListView.self) {
// 根据moreListView的frame变化更新contentSize.height
contentView.contentSize.height = self.moreListView.Height + self.listView.Height + listViewY
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
| mit | 8bc65cb0abcaefea062347ff6c1b4ad8 | 35.514706 | 151 | 0.625453 | 4.402482 | false | false | false | false |
gabrielPeart/SwiftStructures | Source/Structures/AVLTree.swift | 10 | 7594 | //
// AVLNode.swift
// SwiftStructures
//
// Created by Wayne Bishop on 6/26/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
/* An AVL Tree is another name for a balanced binary search tree*/
public class AVLTree<T: Comparable> {
var key: T?
var left: AVLTree?
var right: AVLTree?
var height: Int
init() {
//set math purposes
self.height = -1
}
//TODO: Build computed count property for class
//function to add item based on its value
func addNode(key: T) {
//check for the root node
if (self.key == nil) {
self.key = key
self.height = 0
return
}
//check the left side of the tree
if (key < self.key) {
if (self.left != nil) {
left?.addNode(key)
}
else {
//create a new left node
let leftChild : AVLTree = AVLTree()
leftChild.key = key
leftChild.height = 0
self.left = leftChild
}
//recalculate node height for hierarchy
self.setNodeHeight()
print("traversing left side. node \(self.key!) with height: \(self.height)...")
//check AVL property
self.isValidAVLTree()
} //end if
//check the left side of the tree
if (key > self.key) {
if (self.right != nil) {
right?.addNode(key)
}
else {
//create a new right node
let rightChild : AVLTree = AVLTree()
rightChild.key = key
rightChild.height = 0
self.right = rightChild
}
//recalculate node height for hierarchy
self.setNodeHeight()
print("traversing right side. node \(self.key!) with height: \(self.height)...")
//check AVL property
self.isValidAVLTree()
} //end if
} //end function
// MARK: - tree balancing algorithms
//retrieve the height of a node
func getNodeHeight(aNode: AVLTree!) -> Int {
if (aNode == nil) {
return -1
}
else {
return aNode.height
}
}
//calculate the height of a node
func setNodeHeight() -> Bool {
//check for a nil condition
if (self.key == nil) {
print("no key provided..")
return false
}
//println("key: \(self.key!)")
//initialize leaf variables
var nodeHeight: Int = 0
//do comparision and calculate node height
nodeHeight = max(getNodeHeight(self.left), getNodeHeight(self.right)) + 1
self.height = nodeHeight
return true
}
//determine if the tree is "balanced" - operations on a balanced tree is O(log n)
func isTreeBalanced() -> Bool {
//check for a nil condition
if (self.key == nil) {
print("no key provided..")
return false
}
//use absolute value to manage right and left imbalances
if (abs(getNodeHeight(self.left) - getNodeHeight(self.right)) <= 1) {
return true
}
else {
return false
}
} //end function
//check to ensure node meets avl property
func isValidAVLTree() -> Bool! {
//check for valid scenario
if (self.key == nil) {
print("no key provided..")
return false
}
if (self.isTreeBalanced() == true) {
print("node \(self.key!) already balanced..")
return true
}
//determine rotation type
else {
//create a new leaf node
let childToUse : AVLTree = AVLTree()
childToUse.height = 0
childToUse.key = self.key
if (getNodeHeight(self.left) - getNodeHeight(self.right) > 1) {
print("\n starting right rotation on \(self.key!)..")
//reset the root node
self.key = self.left?.key
self.height = getNodeHeight(self.left)
//assign the new right node
self.right = childToUse
//adjust the left node
self.left = self.left?.left
self.left?.height = 0
print("root is: \(self.key!) | left is : \(self.left!.key!) | right is : \(self.right!.key!)..")
return true
}
if (getNodeHeight(self.right) - getNodeHeight(self.left) > 1) {
print("\n starting left rotation on \(self.key!)..")
//reset the root node
self.key = self.right?.key
self.height = getNodeHeight(self.right)
//assign the new left node
self.left = childToUse
//adjust the right node
self.right = self.right?.right
self.right?.height = 0
print("root is: \(self.key!) | left is : \(self.left!.key!) | right is : \(self.right!.key!)..")
return true
}
return nil
} //end if
} //end function
// MARK: traversal algorithms
//use dfs with trailing closure to update all values
func traverse(formula: AVLTree<T> -> T) {
//check for a nil condition
if self.key == nil {
print("no key provided..")
return
}
//process the left side
if self.left != nil {
left?.traverse(formula)
}
//invoke formula - apply results
let newKey: T = formula(self)
self.key! = newKey
print("...the updated value is: \(self.key!) - height: \(self.height)..")
//process the right side
if self.right != nil {
right?.traverse(formula)
}
}
//traverse all values
func traverse() {
//check for a nil condition
if self.key == nil {
print("no key provided..")
return
}
//process the left side
if self.left != nil {
left?.traverse()
}
print("...the value is: \(self.key!) - height: \(self.height)..")
//process the right side
if self.right != nil {
right?.traverse()
}
}
} //end class | mit | cd7b20c843f899cdf187f8efe4387c11 | 21.671642 | 112 | 0.425336 | 5.389638 | false | false | false | false |
daferpi/p5App | p5App/Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARAnnotationView.swift | 1 | 1911 | //
// ARAnnotationView.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 23/04/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
/**
Responsible for presenting annotations visually. Analogue to MKAnnotationView.
It is usually subclassed to provide custom look.
Annotation views should be lightweight, try to avoid xibs and autolayout.
*/
open class ARAnnotationView: UIView
{
//===== Public
/**
Normally, center of annotationView points to real location of POI, but this property can be used to alter that.
E.g. if bottom-left edge of annotationView should point to real location, centerOffset should be (0, 1)
*/
open var centerOffset = CGPoint(x: 0.5, y: 0.5)
open weak var annotation: ARAnnotation?
// Used internally for stacking
internal var arStackOffset = CGPoint(x: 0, y: 0)
internal var arStackAlternateFrame: CGRect = CGRect.zero
internal var arStackAlternateFrameExists: Bool = false
fileprivate var initialized: Bool = false
public init()
{
super.init(frame: CGRect.zero)
self.initializeInternal()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.initializeInternal()
}
override init(frame: CGRect)
{
super.init(frame: frame)
self.initializeInternal()
}
fileprivate func initializeInternal()
{
if self.initialized
{
return
}
self.initialized = true;
self.initialize()
}
open override func awakeFromNib()
{
self.bindUi()
}
/// Will always be called once, no need to call super
open func initialize()
{
}
/// Called when distance/azimuth changes, intended to be used in subclasses
open func bindUi()
{
}
}
| mit | 45cadd6412de35566c9f07b7c32c2325 | 22.8875 | 116 | 0.636316 | 4.528436 | false | false | false | false |
neonichu/UXCatalog | UICatalog/CustomSearchBarViewController.swift | 1 | 1824 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to customize a UISearchBar.
*/
import UIKit
class CustomSearchBarViewController: UIViewController, UISearchBarDelegate {
// MARK: Properties
@IBOutlet weak var searchBar: UISearchBar!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureSearchBar()
}
// MARK: Configuration
func configureSearchBar() {
searchBar.showsCancelButton = true
searchBar.showsBookmarkButton = true
searchBar.tintColor = UIColor.applicationPurpleColor()
searchBar.backgroundImage = UIImage(named: "search_bar_background")
// Set the bookmark image for both normal and highlighted states.
let bookmarkImage = UIImage(named: "bookmark_icon")
searchBar.setImage(bookmarkImage, forSearchBarIcon: .Bookmark, state: .Normal)
let bookmarkHighlightedImage = UIImage(named: "bookmark_icon_highlighted")
searchBar.setImage(bookmarkHighlightedImage, forSearchBarIcon: .Bookmark, state: .Highlighted)
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
NSLog("The custom search bar keyboard search button was tapped: \(searchBar).")
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
NSLog("The custom search bar cancel button was tapped.")
searchBar.resignFirstResponder()
}
func searchBarBookmarkButtonClicked(searchBar: UISearchBar) {
NSLog("The custom bookmark button inside the search bar was tapped.")
}
}
| mit | 2a776cdacb43afaeed0841994ad642e4 | 28.868852 | 102 | 0.689352 | 5.588957 | false | false | false | false |
Zengzhihui/CycleScrollView | CycleScrollView/Source/GZCycleScrollView.swift | 1 | 6458 | //
// GZCycleScrollView.swift
// CycleScrollView
//
// Created by zzh on 16/1/4.
// Copyright © 2016年 Gavin Zeng. All rights reserved.
//
import Foundation
import UIKit
//MARK: GZCycleScrollViewDelegate
@objc protocol GZCycleScrollViewDelegate {
func numberOfCells() -> Int
func setUpCell() -> UIView
func setCellModel(view: UIView, index:Int)
func didClickCellAtIndex(index: Int)
}
//MARK: GZCycleScrollView
class GZCycleScrollView: UIView, UIScrollViewDelegate{
private var contentScrollView: UIScrollView!
private var currentCell: UIView!
private var nextCell: UIView!
private var preCell: UIView!
private var autoScrollTimer: NSTimer?
private var currentIndex: Int = 0
weak var delegate: GZCycleScrollViewDelegate?{
didSet{
if let _ = delegate{
reloadData()
}
}
}
var isAutoScroll: Bool = false{
didSet{
if isAutoScroll{
startTimer()
}
}
}
var timerInterval: NSTimeInterval = 3{
didSet{
if isAutoScroll{
startTimer()
}
}
}
//MARK: init
override init(frame: CGRect) {
super.init(frame: frame)
setUpSubViews()
}
//MARK: reload
func reloadData(){
setCellModel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: setup subviews
private func setUpSubViews(){
contentScrollView = UIScrollView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
contentScrollView.contentSize = CGSizeMake(self.frame.size.width * 3, 0)
contentScrollView.delegate = self
contentScrollView.bounces = false
contentScrollView.pagingEnabled = true
contentScrollView.showsHorizontalScrollIndicator = false
addSubview(contentScrollView)
setUpCells()
setCellModel()
contentScrollView.setContentOffset(CGPointMake(self.frame.size.width, 0), animated: false)
}
private func setUpCells(){
if let tmpDelegate = delegate where currentCell == nil{
currentCell = tmpDelegate.setUpCell()
currentCell.frame = CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)
currentCell.clipsToBounds = true
contentScrollView.addSubview(currentCell)
//添加点击事件
let cellTapGesture = UITapGestureRecognizer(target: self, action: Selector("currentCellClick:"))
currentCell.addGestureRecognizer(cellTapGesture)
currentCell.userInteractionEnabled = true
preCell = tmpDelegate.setUpCell()
preCell.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)
preCell.clipsToBounds = true
contentScrollView.addSubview(preCell)
nextCell = tmpDelegate.setUpCell()
nextCell.frame = CGRectMake(self.frame.size.width * 2, 0, self.frame.size.width, self.frame.size.height)
nextCell.clipsToBounds = true
contentScrollView.addSubview(nextCell)
if tmpDelegate.numberOfCells() > 1{
contentScrollView.scrollEnabled = true
}else{
contentScrollView.scrollEnabled = false
}
}
}
private func setCellModel(){
setUpCells()
if let tmpDelegate = delegate{
tmpDelegate.setCellModel(nextCell, index: getNextCellIndex())
tmpDelegate.setCellModel(preCell, index: getPreCellIndex())
tmpDelegate.setCellModel(currentCell, index: currentIndex)
}
}
//MARK: helper
private func isHasCells() -> Bool{
if let tmpDalegate = delegate where tmpDalegate.numberOfCells() > 0{
return true
}else{
return false
}
}
private func getPreCellIndex() -> Int{
if !isHasCells(){
return 0
}
let tempIndex = currentIndex - 1
if let tmpDelegate = delegate where tempIndex == -1 {
return tmpDelegate.numberOfCells() - 1
}else{
return tempIndex
}
}
private func getNextCellIndex() -> Int
{
if !isHasCells(){
return 0
}
let tempIndex = currentIndex + 1
if let tmpDelegate = delegate{
return tempIndex < tmpDelegate.numberOfCells() ? tempIndex : 0
}else{
return 0
}
}
//MRAK: click
@objc private func currentCellClick(tap: UITapGestureRecognizer){
delegate?.didClickCellAtIndex(currentIndex)
}
//MARK: scrollView delegate
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
if isAutoScroll{
autoScrollTimer?.invalidate()
autoScrollTimer = nil
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
if offset == 0 {
currentIndex = getPreCellIndex()
}else if offset == self.frame.size.width * 2 {
currentIndex = getNextCellIndex()
}
//reset data
setCellModel()
scrollView.setContentOffset(CGPointMake(self.frame.size.width, 0), animated: false)
//restart timer
startTimer()
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
scrollViewDidEndDecelerating(contentScrollView)
}
//MARK: timer
private func startTimer(){
stopTimer()
if isAutoScroll && isHasCells(){
autoScrollTimer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}
}
@objc private func timerAction() {
contentScrollView?.setContentOffset(CGPointMake(self.frame.size.width*2, 0), animated: true)
}
private func stopTimer(){
autoScrollTimer?.invalidate()
autoScrollTimer = nil
}
} | mit | d83479fac49bb8b713f4f33cc443dca8 | 29.540284 | 152 | 0.607326 | 5.217004 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/CardTableView/CardTableView/CardTableViewCell.swift | 1 | 6079 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of CosmicMind 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 UIKit
import Material
import Motion
import Graph
class CardTableViewCell: TableViewCell {
private var spacing: CGFloat = 10
/// A boolean that indicates whether the cell is the last cell.
public var isLast = false
public lazy var card: PresenterCard = PresenterCard()
/// Toolbar views.
private var toolbar: Toolbar!
private var profileImage: UIImageView!
private var moreButton: IconButton!
/// Presenter area.
private var presenterImageView: UIImageView!
/// Content area.
private var contentLabel: UILabel!
/// Bottom Bar views.
private var bottomBar: Bar!
private var dateFormatter: DateFormatter!
private var dateLabel: UILabel!
private var favoriteButton: IconButton!
private var shareButton: IconButton!
public var data: Entity? {
didSet {
layoutSubviews()
}
}
override func layoutSubviews() {
super.layoutSubviews()
guard let d = data else {
return
}
toolbar.title = d["title"] as? String
toolbar.detail = d["detail"] as? String
if let image = d["photo"] as? UIImage {
presenterImageView.frame.size.height = image.height
Motion.async { [weak self, image = image] in
self?.presenterImageView.image = image
}
}
if let image = d["author"] as? UIImage {
profileImage.frame.size.height = image.height
Motion.async { [weak self, image = image] in
self?.profileImage.image = image
}
}
contentLabel.text = d["content"] as? String
dateLabel.text = dateFormatter.string(from: d.createdDate)
card.frame.origin.x = 0
card.frame.origin.y = 0
card.frame.size.width = bounds.width
frame.size.height = card.bounds.height
}
open override func prepare() {
super.prepare()
layer.rasterizationScale = Screen.scale
layer.shouldRasterize = true
pulseAnimation = .none
backgroundColor = nil
prepareDateFormatter()
prepareDateLabel()
prepareProfileImage()
prepareMoreButton()
prepareToolbar()
prepareFavoriteButton()
prepareShareButton()
preparePresenterImageView()
prepareContentLabel()
prepareBottomBar()
preparePresenterCard()
}
private func prepareDateFormatter() {
dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
}
private func prepareDateLabel() {
dateLabel = UILabel()
dateLabel.font = RobotoFont.regular(with: 12)
dateLabel.textColor = Color.blueGrey.base
dateLabel.textAlignment = .center
}
private func prepareProfileImage() {
profileImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 48, height: 48))
profileImage.shapePreset = .circle
}
private func prepareMoreButton() {
moreButton = IconButton(image: Icon.cm.moreVertical, tintColor: Color.blueGrey.base)
}
private func prepareFavoriteButton() {
favoriteButton = IconButton(image: Icon.favorite, tintColor: Color.red.base)
}
private func prepareShareButton() {
shareButton = IconButton(image: Icon.cm.share, tintColor: Color.blueGrey.base)
}
private func prepareToolbar() {
toolbar = Toolbar()
toolbar.heightPreset = .xlarge
toolbar.contentEdgeInsetsPreset = .square3
toolbar.titleLabel.textAlignment = .left
toolbar.detailLabel.textAlignment = .left
toolbar.leftViews = [profileImage]
toolbar.rightViews = [moreButton]
}
private func preparePresenterImageView() {
presenterImageView = UIImageView()
presenterImageView.contentMode = .scaleAspectFill
}
private func prepareContentLabel() {
contentLabel = UILabel()
contentLabel.numberOfLines = 0
contentLabel.font = RobotoFont.regular(with: 14)
}
private func prepareBottomBar() {
bottomBar = Bar()
bottomBar.heightPreset = .xlarge
bottomBar.contentEdgeInsetsPreset = .square3
bottomBar.centerViews = [dateLabel]
bottomBar.leftViews = [favoriteButton]
bottomBar.rightViews = [shareButton]
bottomBar.dividerColor = Color.grey.lighten2
}
private func preparePresenterCard() {
card.toolbar = toolbar
card.presenterView = presenterImageView
card.contentView = contentLabel
card.contentViewEdgeInsetsPreset = .square3
card.contentViewEdgeInsets.bottom = 0
card.bottomBar = bottomBar
card.depthPreset = .none
contentView.addSubview(card)
}
}
| bsd-3-clause | dec1059726b383bfbc18ad736e34453b | 29.547739 | 88 | 0.709163 | 4.679754 | false | false | false | false |
Ferrari-lee/firefox-ios | Utils/Extensions/UIImage+Extensions.swift | 25 | 3769 | /* 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 UIImage {
class func createWithColor(size: CGSize, color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let context = UIGraphicsGetCurrentContext();
let rect = CGRect(origin: CGPointZero, size: size)
color.setFill()
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return image
}
func createScaled(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
public class ImageOperation : NSObject, SDWebImageOperation {
public var cacheOperation: NSOperation?
var cancelled: Bool {
if let cacheOperation = cacheOperation {
return cacheOperation.cancelled
}
return false
}
@objc public func cancel() {
if let cacheOperation = cacheOperation {
cacheOperation.cancel()
}
}
}
// This is an extension to SDWebImage's api to allow passing in a cache to be used for lookup.
public typealias CompletionBlock = (img: UIImage?, err: NSError, type: SDImageCacheType, key: String) -> Void
extension UIImageView {
// This is a helper function for custom async loaders. It starts an operation that will check for the image in
// a cache (either one passed in or the default if none is specified). If its found in the cache its returned,
// otherwise, block is run and should return an image to show.
private func runBlockIfNotInCache(key: String, var cache: SDImageCache? = nil, completed: CompletionBlock, block: () -> UIImage?) {
self.sd_cancelCurrentImageLoad()
let operation = ImageOperation()
if cache == nil {
cache = SDImageCache.sharedImageCache()
}
operation.cacheOperation = cache!.queryDiskCacheForKey(key, done: { (var image, cacheType) -> Void in
let err = NSError(domain: "UIImage+Extensions.runBlockIfNotInCache", code: 0, userInfo: nil)
// If this was cancelled, don't bother notifying the caller
if operation.cancelled {
return
}
// If it was found in the cache, we can just use it
if let image = image {
self.image = image
self.setNeedsLayout()
} else {
// Otherwise, the block has a chance to load it
image = block()
if image != nil {
self.image = image
cache!.storeImage(image, forKey: key)
}
}
completed(img: image, err: err, type: cacheType, key: key)
})
self.sd_setImageLoadOperation(operation, forKey: "UIImageViewImageLoad")
}
public func moz_getImageFromCache(key: String, cache: SDImageCache, completed: CompletionBlock) {
// This cache is filled outside of here. If we don't find the key in it, nothing to do here.
runBlockIfNotInCache(key, cache: cache, completed: completed) { _ in return nil}
}
// Looks up an asset in local storage.
public func moz_loadAsset(named: String, completed: CompletionBlock) {
runBlockIfNotInCache(named, completed: completed) {
return UIImage(named: named)
}
}
} | mpl-2.0 | 03736742d0b58e5dd817e9ba654d644d | 38.270833 | 135 | 0.6381 | 4.875809 | false | false | false | false |
Ahrodite/LigaFix | LigaFix/DataModel/UserSingleton.swift | 1 | 8635 | //
// UserSingleton.swift
// LigaFix
//
// Created by JiaDuan on 15/12/25.
// Copyright © 2015年 JiaDuan. All rights reserved.
//
import Foundation
import CoreData
class UserSingleton {
class var sharedInstance: UserSingleton {
struct Static {
static var instance: UserSingleton = UserSingleton()
}
if Static.instance.user == nil {
Static.instance.user = Static.instance.getActiveUser()
}
return Static.instance
}
var user: User?
internal func getAllUsers() -> NSArray? {
var users: NSArray?
let fetchUsers = NSFetchRequest(entityName: "User")
let userPredicate = NSPredicate(format: "isActive = %@ or isActive = %@", true, false)
fetchUsers.predicate = userPredicate
do {
users = try appDelegate.managedObjectContext.executeFetchRequest(fetchUsers)
} catch let error as NSError {
print("=============error=============")
print("getAllUsers() error")
print("fetch all users error")
print(error.localizedDescription)
}
return users
}
private func getActiveUser() -> User {
var user: User
let fetchActiveUser = NSFetchRequest(entityName: "User")
let activeUserPredicate = NSPredicate(format: "isActive = %@", true)
fetchActiveUser.predicate = activeUserPredicate
var activeUser: NSArray?
do {
activeUser = try appDelegate.managedObjectContext.executeFetchRequest(fetchActiveUser)
} catch let error as NSError {
print("=============error=============")
print("getActiveUser() error")
print("fetch active user error")
print(error.localizedDescription)
}
if activeUser != nil && activeUser?.count > 0 {
user = activeUser![0] as! User
} else { // 没有活跃用户,插入一个新用户
user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: appDelegate.managedObjectContext) as! User
user.id = IDDictSingleton.sharedInstance.getUserID()
user.isActive = true
user.name = String(user.id!)
self.saveContext("getActiveUser()")
}
return user
}
internal func getNewUser() -> User {
var user: User
let fetchUnusedUser = NSFetchRequest(entityName: "User")
let unusedUserPredicate = NSPredicate(format: "name = null")
fetchUnusedUser.predicate = unusedUserPredicate
var unusedUsers: NSArray?
do {
unusedUsers = try appDelegate.managedObjectContext.executeFetchRequest(fetchUnusedUser)
} catch let error as NSError {
print("=============error=============")
print("getUnusedUser() error")
print("fetch unused user error")
print(error.localizedDescription)
}
if unusedUsers != nil && unusedUsers?.count > 0 {
user = unusedUsers![0] as! User
user.isActive = true
} else { // 没有活跃用户,插入一个新用户
user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: appDelegate.managedObjectContext) as! User
user.id = IDDictSingleton.sharedInstance.getUserID()
user.isActive = true
user.name = String(user.id!)
self.saveContext("getActiveUser()")
}
return user
}
private func saveContext(funcName: String) {
do {
try appDelegate.managedObjectContext.save()
} catch let error as NSError{
print("=============error=============")
print(funcName + " error")
print("context save error")
print(error.localizedDescription)
}
}
// name get & set
internal func getActiveUsername() -> String? {
return self.user?.name
}
internal func setActiveUsername(newName: String?) {
self.user?.name = newName
saveContext("setAvtiveUsername(newName: String?)")
}
// sex get & set
internal func getGender() -> String? {
if self.user?.sex != nil {
if self.user?.sex == 0 {
return "女"
} else {
return "男"
}
}
return nil
}
internal func setGender(gender: String?) {
if gender == "女" {
self.user?.sex = 0
} else {
self.user?.sex = 1
}
saveContext("setGender(gender: String?)")
}
// age get & set
internal func getAge() -> String? {
let birthday = self.user?.birthday
var ret: String?
if birthday != nil {
let component = NSCalendar.currentCalendar().components(.Year, fromDate: birthday!, toDate: NSDate(), options: NSCalendarOptions.MatchStrictly)
let age = component.year
ret = String(age) + "岁"
}
return ret
}
internal func setBirthday(date: NSDate?) {
self.user?.birthday = date
saveContext("setBirthday(date: NSDate?)")
}
internal func getCurrentCase() -> RecoveryCase? {
var currentCase: RecoveryCase?
if let currentCaseID = self.user?.currentCaseID {
var cases: NSArray?
let fetchCases = NSFetchRequest(entityName: "RecoveryCase")
let casesPredicate = NSPredicate(format: "userID = %@ and id = %@", self.user!.id!, currentCaseID)
fetchCases.predicate = casesPredicate
do {
cases = try appDelegate.managedObjectContext.executeFetchRequest(fetchCases)
} catch let error as NSError {
print("=============error=============")
print("getCurrentCase() error")
print("fetch current case error")
print(error.localizedDescription)
}
if cases != nil && cases!.count > 0 {
currentCase = cases![0] as? RecoveryCase
}
}
return currentCase
}
internal func getCurrentCaseDateString() -> String? {
var dateString: String?
let currentCase = self.getCurrentCase()
if currentCase != nil {
dateString = currentCase!.getDateString()
}
return dateString
}
internal func getAllCases() -> NSArray? {
var cases: NSArray?
let fetchCases = NSFetchRequest(entityName: "RecoveryCase")
let casesPredicate = NSPredicate(format: "userID = %@", self.user!.id!)
fetchCases.predicate = casesPredicate
do {
cases = try appDelegate.managedObjectContext.executeFetchRequest(fetchCases)
} catch let error as NSError {
print("=============error=============")
print("getAllCases() error")
print("fetch all cases error")
print(error.localizedDescription)
}
return cases
}
internal func setCurrentCase(caseID: NSNumber?) {
if let id = caseID {
self.user?.currentCaseID = id
}
}
internal func getElapseDaysFromOperation() -> String? {
var elapse: String?
let currentCase = self.getCurrentCase()
if let operationDate = currentCase?.operationDate {
let component = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: operationDate, toDate: NSDate(), options: NSCalendarOptions.MatchStrictly)
let days = component.day
elapse = String(days)
}
return elapse
}
internal func addNewCase(date: NSDate?) {
if let d = date {
let context = appDelegate.managedObjectContext
let newCase = RecoveryCase(entity: NSEntityDescription.entityForName("RecoveryCase", inManagedObjectContext: context)!, insertIntoManagedObjectContext: context)
newCase.id = IDDictSingleton.sharedInstance.getCaseID()
self.user?.currentCaseID = newCase.id
newCase.operationDate = d
newCase.userID = self.user?.id
newCase.belongToUser = self.user
saveContext("addNewCase(date: NSDate)")
// self.user?.hasCasees
}
}
// active status change
internal func changeActiveStatus() {
self.user!.changeActiveStatus()
saveContext("changeActiveStatus()")
}
}
| mit | 3851580db50235832e98f13f3f77bb04 | 33.135458 | 175 | 0.572012 | 5.084866 | false | false | false | false |
ixx1232/SwiftBlank | SwiftBlank/SwiftBlank/ViewController.swift | 1 | 2857 | //
// ViewController.swift
// SwiftBlank
//
// Created by apple on 16/1/19.
// Copyright © 2016年 www.ixx.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
// 使用已有类型构建按钮
let commonBtn = UIButton(type: UIButtonType.ContactAdd)
// 修改按钮位置及大小
commonBtn.center = self.view.center
self.view.backgroundColor = UIColor.lightGrayColor()
// 添加到界面
self.view.addSubview(commonBtn)
// 添加点击事件
commonBtn.addTarget(self, action: "commonAction:", forControlEvents: UIControlEvents.TouchUpInside)
commonBtn.tag = 1
}
func commonAction(commonBtn:UIButton) {
print("点我了?")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 自定义按钮
let customButton = UIButton(frame: CGRectMake(self.view.frame.width/2 - 100, 400, 200, 200))
// 设置按钮标题
customButton.setTitle("custom", forState: UIControlState.Normal)
// 设置按钮标题颜色
customButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
// 设置按钮标题阴影
customButton.setTitleShadowColor(UIColor.blackColor(), forState: UIControlState.Normal)
// 设置按钮阴影
customButton.titleLabel?.shadowOffset = CGSizeMake(1.0, 1.0)
// 设置按钮标题字体样式
customButton.titleLabel!.font = UIFont.systemFontOfSize(17)
// 设置按钮标题换行模式
customButton.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
// 设置按钮背景色
customButton.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0)
// 设置按钮内部内容边距
customButton.contentEdgeInsets = UIEdgeInsetsMake(-100, 0, 0, 0)
// 去掉高亮状态下的图像颜色加深
customButton.adjustsImageWhenHighlighted = false
// 去掉禁用状态下的图像颜色加深
customButton.adjustsImageWhenDisabled = false
// 添加按钮按下发光效果
customButton.showsTouchWhenHighlighted = true
customButton.addTarget(self, action: "btnAction:", forControlEvents: UIControlEvents.TouchUpInside)
// 设置按钮标签
customButton.tag = 2
self.view.addSubview(customButton)
}
func btnAction(sender: UIButton!) {
print(sender.tag)
}
}
| apache-2.0 | a7efa9c65a728793ce80104ea95a7850 | 26.526882 | 107 | 0.602734 | 4.740741 | false | false | false | false |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Source/Core/HeaderFooterView.swift | 7 | 5310 | // HeaderFooterView.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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
/**
Enumeration used to generate views for the header and footer of a section.
- Class: Will generate a view of the specified class.
- Callback->ViewType: Will generate the view as a result of the given closure.
- NibFile: Will load the view from a nib file.
*/
public enum HeaderFooterProvider<ViewType: UIView> {
/**
* Will generate a view of the specified class.
*/
case `class`
/**
* Will generate the view as a result of the given closure.
*/
case callback(()->ViewType)
/**
* Will load the view from a nib file.
*/
case nibFile(name: String, bundle: Bundle?)
internal func createView() -> ViewType {
switch self {
case .class:
return ViewType()
case .callback(let builder):
return builder()
case .nibFile(let nibName, let bundle):
return (bundle ?? Bundle(for: ViewType.self)).loadNibNamed(nibName, owner: nil, options: nil)![0] as! ViewType
}
}
}
/**
* Represents headers and footers of sections
*/
public enum HeaderFooterType {
case header, footer
}
/**
* Struct used to generate headers and footers either from a view or a String.
*/
public struct HeaderFooterView<ViewType: UIView> : ExpressibleByStringLiteral, HeaderFooterViewRepresentable {
/// Holds the title of the view if it was set up with a String.
public var title: String?
/// Generates the view.
public var viewProvider: HeaderFooterProvider<ViewType>?
/// Closure called when the view is created. Useful to customize its appearance.
public var onSetupView: ((_ view: ViewType, _ section: Section) -> ())?
/// A closure that returns the height for the header or footer view.
public var height: (()->CGFloat)?
/**
This method can be called to get the view corresponding to the header or footer of a section in a specific controller.
- parameter section: The section from which to get the view.
- parameter type: Either header or footer.
- parameter controller: The controller from which to get that view.
- returns: The header or footer of the specified section.
*/
public func viewForSection(_ section: Section, type: HeaderFooterType) -> UIView? {
var view: ViewType?
if type == .header {
view = section.headerView as? ViewType ?? {
let result = viewProvider?.createView()
section.headerView = result
return result
}()
}
else {
view = section.footerView as? ViewType ?? {
let result = viewProvider?.createView()
section.footerView = result
return result
}()
}
guard let v = view else { return nil }
onSetupView?(v, section)
return v
}
/**
Initiates the view with a String as title
*/
public init?(title: String?){
guard let t = title else { return nil }
self.init(stringLiteral: t)
}
/**
Initiates the view with a view provider, ideal for customized headers or footers
*/
public init(_ provider: HeaderFooterProvider<ViewType>){
viewProvider = provider
}
/**
Initiates the view with a String as title
*/
public init(unicodeScalarLiteral value: String) {
self.title = value
}
/**
Initiates the view with a String as title
*/
public init(extendedGraphemeClusterLiteral value: String) {
self.title = value
}
/**
Initiates the view with a String as title
*/
public init(stringLiteral value: String) {
self.title = value
}
}
extension UIView {
func eurekaInvalidate() {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
setNeedsLayout()
}
}
| mit | 42246b5621c02417594baa0980a54df5 | 31.378049 | 123 | 0.62693 | 4.957983 | false | false | false | false |
ahoppen/swift | test/Interpreter/SDK/objc_swift_getObjectType.swift | 31 | 1395 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
protocol P: class { }
class AbstractP: P { }
class DelegatedP<D: P>: AbstractP {
init(_ d: D) { }
}
class AnyP: DelegatedP<AbstractP> {
init<D: P>(_ d: D) {
super.init(DelegatedP<D>(d))
}
}
extension P {
var anyP: AnyP {
return AnyP(self)
}
}
// SR-4363
// Test several paths through swift_getObjectType()
// instance of a Swift class that conforms to P
class O: NSObject, P { }
var o = O()
let obase: NSObject = o
print(NSStringFromClass(object_getClass(o)!))
_ = (o as P).anyP
_ = (obase as! P).anyP
// CHECK: {{^}}main.O{{$}}
// ... and KVO's artificial subclass thereof
o.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil)
print(NSStringFromClass(object_getClass(o)!))
_ = (o as P).anyP
_ = (obase as! P).anyP
// CHECK-NEXT: NSKVONotifying_main.O
// instance of an ObjC class that conforms to P
extension NSLock: P { }
var l = NSLock()
let lbase: NSObject = l
print(NSStringFromClass(object_getClass(l)!))
_ = (l as P).anyP
_ = (lbase as! P).anyP
// CHECK-NEXT: NSLock
// ... and KVO's artificial subclass thereof
l.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil)
print(NSStringFromClass(object_getClass(l)!))
_ = (l as P).anyP
_ = (lbase as! P).anyP
// CHECK-NEXT: NSKVONotifying_NSLock
| apache-2.0 | a357b1251b9fdffa6dd05daa1de76320 | 22.25 | 75 | 0.660932 | 3.065934 | false | false | false | false |
nerdishbynature/OysterKit | Common/Framework/Parsing/OKScriptParser.swift | 1 | 20759 | /*
Copyright (c) 2014, RED When Excited
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public class OKScriptTokenizer : Tokenizer {
public override init(){
super.init()
//Eventually this will be it's own file
self.branch(
Characters(from:" \t\n,"),
Delimited(delimiter: "\"", states:
Repeat(state:Branch().branch(
LoopingCharacters(except: "\"\\").token("character"),
Characters(from:"\\").branch(
Characters(from:"x").branch(
Repeat(state: Branch().branch(
Characters(from: "0123456789abcdefABCDEF").token("hex")
),min: 2,max: 2).token("character")
),
Characters(from:"trn\"\\").token("character")
)
), min: 1, max: nil).token("Char")
).token("quote"),
Delimited(delimiter: "'", states:
Repeat(state:Branch().branch(
LoopingCharacters(except: "'\\").token("character"),
Characters(from:"\\").branch(
Characters(from:"'\\").token("character")
)
), min: 1).token("delimiter")
).token("single-quote"),
Characters(from: "!").token("not"),
Characters(from: "-").sequence(
Characters(from:">").token("token")
),
Characters(from:"^").token("exit-state"),
Characters(from:"*").token("loop"),
Characters(from:".").token("then"),
Characters(from:"{").token("start-branch"),
Characters(from:"}").token("end-branch"),
Characters(from:"(").token("start-repeat"),
Characters(from:")").token("end-repeat"),
Characters(from:"<").token("start-delimited"),
Characters(from:">").token("end-delimited"),
Characters(from:"[").token("start-keyword"),
Characters(from:"]").token("end-keyword"),
Characters(from:"=").token("assign"),
Keywords(validStrings: ["begin"]).branch(
LoopingCharacters(from:lowerCaseLetterString+upperCaseLetterString+decimalDigitString+"_").token("variable"),
Exit().token("tokenizer")
),
Characters(from:"@").token("keyword").branch(
Characters(from:lowerCaseLetterString+upperCaseLetterString).sequence(
LoopingCharacters(from:lowerCaseLetterString+upperCaseLetterString+decimalDigitString+"_").token("state-name")
)
),
OKStandard.number,
OKStandard.Code.variableName
)
}
}
class State:Token{
var state : TokenizationState
init(state:TokenizationState){
self.state = state
super.init(name: "state",withCharacters: "")
}
override var description:String {
return "State: "+state.description+state.pseudoTokenNameSuffix()
}
}
class Operator : Token {
init(characters:String){
super.init(name: "operator", withCharacters: characters)
}
func applyTo(token:Token, parser:OKScriptParser)->Token?{
return nil
}
}
class EmitTokenOperator : Operator {
override func applyTo(token: Token, parser:OKScriptParser) -> Token? {
//TODO: Probably an error, should report that
if !parser.hasTokens() {
parser.errors.append("Expected a state to assign the token to")
return nil
}
let topToken = parser.popToken()!
if let stateToken = topToken as? State {
stateToken.state.token(token.characters)
return stateToken
} else {
if topToken.name == "state-name" {
var error = "Trying to emit a token from a named state '\(topToken.characters)', but named state does not exist in: "
var first = true
for (name,_) in parser.definedNamedStates {
if !first {
error+=", "
} else {
first = false
}
error+="'\(name)'"
}
parser.errors.append(error)
} else {
parser.errors.append("Only states can emit tokens, and I received a \(topToken)")
}
parser.pushToken(topToken)
}
return nil
}
}
class ChainStateOperator : Operator {
}
public class OKScriptParser:StackParser{
var invert:Bool = false
var loop:Bool = false
public var errors = [String]()
var finishedNamedStates = false
var definedNamedStates = [String:Named]()
public override init(){
super.init()
}
func invokeOperator(onToken:Token){
if hasTokens() {
if topToken()! is Operator {
let op = popToken()! as! Operator
if let newToken = op.applyTo(onToken, parser: self) {
pushToken(newToken)
}
} else {
errors.append("Expected an operator")
pushToken(onToken)
}
} else {
errors.append("Expected an operator, there were none")
pushToken(onToken)
}
}
override public func pushToken(symbol: Token) {
if let state = symbol as? State {
if let topTokenName = topToken()?.name {
if topTokenName == "assign" {
popToken()
if let _ = topToken()?.name {
let stateName = popToken()!
//Now we need to create a named state, we only specify the root state
//we won't know the end state for some time
let namedState = Named(name: stateName.characters, root:state.state)
super.pushToken(State(state: namedState))
return
} else {
errors.append("Expected a state name to assign to the state")
}
}
}
}
super.pushToken(symbol)
}
func popTo(tokenNamed:String)->Array<Token> {
var tokenArray = Array<Token>()
var token = popToken()
if token == nil {
errors.append("Failed to pop to \(tokenNamed), there were no tokens on the stack")
return tokenArray
}
while (token!.name != tokenNamed) {
if let nextToken = token{
tokenArray.append(nextToken)
} else {
errors.append("Stack exhausted before finding \(tokenNamed) token")
return tokenArray
}
token = popToken()
if token == nil {
errors.append("Stack exhausted before finding \(tokenNamed) token")
return Array<Token>()
}
}
//Now we have an array of either states, or chains of states
//and the chains need to be unwound and entire array reversed
var finalArray = Array<Token>()
var op : ChainStateOperator?
for token in tokenArray {
if let stateToken = token as? State {
if op != nil {
//The last state needs to be removed,
//chained to this state,
///and this state added to final
if finalArray.count == 0 {
errors.append("Incomplete state definition")
return Array<Token>()
}
let lastToken = finalArray.removeLast()
if let lastStateToken = lastToken as? State {
stateToken.state.branch(lastStateToken.state)
op = nil
} else {
errors.append("Only states can emit tokens")
return Array<Token>()
}
}
finalArray.append(stateToken)
} else if token is ChainStateOperator {
op = token as? ChainStateOperator
} else {
//It's just a parameter
finalArray.append(token)
}
}
return Array(finalArray.reverse())
}
func endBranch(){
let branch = Branch()
for token in popTo("start-branch"){
if let stateToken = token as? State {
branch.branch(stateToken.state)
}
}
pushToken(State(state: branch))
}
func endRepeat(){
var parameters = popTo("start-repeat")
if (parameters.count == 0){
errors.append("At least a state is required")
return
}
if !(parameters[0] is State) {
errors.append("Expected a state")
return
}
var minimum = 1
var maximum : Int? = nil
let repeatingState = parameters[0] as! State
if parameters.count > 1 {
if let minimumNumberToken = parameters[1] as? NumberToken {
minimum = Int(minimumNumberToken.numericValue)
if parameters.count > 2 {
if let maximumNumberToken = parameters[2] as? NumberToken {
maximum = Int(maximumNumberToken.numericValue)
} else {
errors.append("Expected a number")
return
}
}
} else {
errors.append("Expected a number")
return
}
}
let `repeat` = Repeat(state: repeatingState.state, min: minimum, max: maximum)
pushToken(State(state:`repeat`))
}
func endDelimited(){
var parameters = popTo("start-delimited")
if parameters.count < 2 || parameters.count > 3{
errors.append("At least two parameters are required for a delimited state")
return
}
if parameters[0].name != "delimiter" {
errors.append("At least one delimiter must be specified")
return
}
var openingDelimiter = parameters[0].characters
var closingDelimiter = openingDelimiter
if parameters.count == 3{
if parameters[1].name != "delimiter" {
errors.append("Expected delimiter character as second parameter")
return
}
closingDelimiter = parameters[1].characters
}
openingDelimiter = unescapeDelimiter(openingDelimiter)
closingDelimiter = unescapeDelimiter(closingDelimiter)
if let delimitedStateToken = parameters[parameters.endIndex-1] as? State {
let delimited = Delimited(open: openingDelimiter, close: closingDelimiter, states: delimitedStateToken.state)
pushToken(State(state:delimited))
} else {
errors.append("Final parameter must be a state")
return
}
}
func endKeywords(){
let keyWordCharTokens = popTo("start-keyword")
var keywordsArray = [String]()
for token in keyWordCharTokens {
if let stateToken = token as? State {
if let charState = stateToken.state as? Characters {
keywordsArray.append("\(charState.allowedCharacters)")
} else {
errors.append("Expected a char state but got \(stateToken.state)")
}
} else {
errors.append("Only comma seperated strings expected for keywords, got \(token)")
}
}
pushToken(State(state: Keywords(validStrings: keywordsArray)))
}
func unescapeChar(characters:String)->String{
if characters.characters.count == 1 {
return characters
}
let simpleTokenizer = Tokenizer()
simpleTokenizer.branch(
OKStandard.eot.token("ignore"),
Characters(from:"\\").branch(
Characters(from:"\\").token("backslash"),
Characters(from:"\"").token("quote"),
Characters(from:"n").token("newline"),
Characters(from:"r").token("return"),
Characters(from:"t").token("tab"),
Characters(from:"x").branch(
Repeat(state: Branch().branch(Characters(from: "0123456789ABCDEFabcdef").token("hex")), min: 2, max: 4).token("unicode")
)
),
Characters(except: "\\").token("character")
)
var output = ""
for token in simpleTokenizer.tokenize(characters){
switch token.name {
case "unicode":
let hexDigits = token.characters[token.characters.startIndex.successor().successor()..<token.characters.endIndex]
if let intValue = Int(hexDigits) {
let unicodeCharacter = UnicodeScalar(intValue)
output += "\(unicodeCharacter)"
} else {
errors.append("Could not create unicode scalar from \(token.characters)")
}
case "return":
output+="\r"
case "tab":
output+="\t"
case "newline":
output+="\n"
case "quote":
output+="\""
case "backslash":
output+="\\"
case "ignore":
output += ""
default:
output+=token.characters
}
}
return output
}
func unescapeDelimiter(character:String)->String{
if character == "\\'" {
return "'"
} else if character == "\\\\" {
return "\\"
}
return character
}
func createCharState(characters:String, inverted:Bool, looped:Bool)->State{
var state : TokenizationState
if inverted {
state = looped ? LoopingCharacters(except:characters) : Characters(except:characters)
} else {
state = looped ? LoopingCharacters(from:characters) : Characters(from:characters)
}
return State(state: state)
}
func debugState(){
if __okDebug {
print("Current stack is:")
for token in symbolStack {
print("\t\(token)")
}
print("\n")
}
}
override public func parse(token: Token) -> Bool {
switch token.name {
case "loop":
loop = true
case "not":
invert = true
case "Char":
pushToken(createCharState(unescapeChar(token.characters), inverted: invert, looped: loop))
invert = false
loop = false
case "then":
pushToken(ChainStateOperator(characters:token.characters))
case "token":
pushToken(EmitTokenOperator(characters:token.characters))
case "state-name":
if let namedState = definedNamedStates[token.characters] {
pushToken(State(state:namedState.clone()))
debugState()
return true
}
fallthrough
case "delimiter","assign":
pushToken(token)
case "integer":
pushToken(NumberToken(usingToken: token))
case "variable":
invokeOperator(token)
case "exit-state":
pushToken(State(state: Exit()))
case "end-repeat":
endRepeat()
case "end-branch":
endBranch()
case "end-delimited":
endDelimited()
case "end-keyword":
endKeywords()
case "tokenizer":
foldUpNamedStates()
case let name where name.hasPrefix("start"):
invert = false
pushToken(token)
default:
return true
}
debugState()
return true
}
func parseState(string:String) ->TokenizationState {
OKScriptTokenizer().tokenize(string,newToken:parse)
_ = Tokenizer()
if let rootState = popToken() as? State {
let flattened = rootState.state.flatten()
return flattened
} else {
errors.append("Could not create root state")
return Branch()
}
}
func registerNamedState(inout stateSequence:[TokenizationState], inout endState:TokenizationState?)->Bool{
//The last item in the list should be the named state, anything else should be a sequence
if let namedState = stateSequence.removeLast() as? Named {
if stateSequence.count > 0 {
namedState.sequence(Array(stateSequence.reverse()))
namedState.endState = endState!
}
definedNamedStates[namedState.name] = namedState
endState = nil
} else {
errors.append("Expected a named state, but didn't get one. Aborting named state processing")
return false
}
return true
}
func foldUpNamedStates(){
var endState:TokenizationState?
var stateSequence = [TokenizationState]()
var concatenate = false
while hasTokens() {
debugState()
if let topStateToken = popToken()! as? State {
if concatenate {
stateSequence.append(topStateToken.state)
} else {
//Is this the start of a chain?
if endState == nil {
endState = topStateToken.state
stateSequence.removeAll(keepCapacity: false)
stateSequence.append(endState!)
} else {
//This is actually the start of the next chain, put it back and unwind the chain
pushToken(topStateToken)
if !registerNamedState(&stateSequence, endState: &endState){
return
}
}
}
concatenate = false
} else {
//This should be the then token
concatenate = true
}
}
if stateSequence.count > 0 {
registerNamedState(&stateSequence, endState: &endState)
}
debugState()
}
public func parse(string: String) -> Tokenizer {
let tokenizer = Tokenizer()
tokenizer.branch(parseState(string))
tokenizer.namedStates = definedNamedStates
tokenizer.flatten()
return tokenizer
}
} | bsd-2-clause | ce4e5a1740898fa7443def70dfc1c5a3 | 33.890756 | 144 | 0.517318 | 5.272797 | false | false | false | false |
igroomgrim/swift101 | swift101/Day10_GenericCollection_Set.swift | 1 | 1397 | //
// Day10_GenericCollection_Set.swift
// swift101
//
// Created by Anak Mirasing on 1/9/2559 BE.
// Copyright © 2559 iGROOMGRiM. All rights reserved.
//
import Foundation
func playSet() {
// Initialzes an empty Set of the String
var myStringSet = Set<String>()
//Initializes a mutable set of the String type with initial values
var stringSet = Set(["DataOne", "DataTwo", "DataThree"])
// Insert item into a Set
myStringSet.insert("DataOne")
myStringSet.insert("DataTwo")
// Count item in a Set
let setCount = myStringSet.count
// Checking whether a set contains an item
let contain = myStringSet.contains("DataTwo")
// Remove items in a Set
let removedItem = myStringSet.remove("DataTwo")
// Remove all item
myStringSet.removeAll()
// Remove first
let firstItem = myStringSet.removeFirst()
// Day 9 - Set operations
var set1 = Set([1,2,3,])
var set2 = Set([3,4,5])
// union and unionInPlace
let newUnionSet = set1.union(set2) // [1,2,3,4,5]
// subtract and subtractInPlace
let newSubtractSet = set1.subtract(set2) // [2,3]
// intersect and intersectInPlace
let newIntersectSet = set1.intersect(set2) // [3]
// exclusiveOr and exclusiveOrInPlace
let newExclusiveOrSet = set1.exclusiveOr(set2) // [1,2,4,5]
} | mit | 1e123fbd05318786f9d71d35dac77c4f | 24.87037 | 70 | 0.635387 | 3.783198 | false | false | false | false |
tus/TUSKit | TUSKitExample/TUSKitExample/PhotoPicker.swift | 1 | 2848 | //
// PhotoPicker.swift
// TUSKitExample
//
// Created by Tjeerd in ‘t Veen on 14/09/2021.
//
import SwiftUI
import UIKit
import PhotosUI
import TUSKit
/// In this example you can see how you can pass on imagefiles to the TUSClient.
struct PhotoPicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentationMode
let tusClient: TUSClient
init(tusClient: TUSClient) {
self.tusClient = tusClient
}
func makeUIViewController(context: Context) -> PHPickerViewController {
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
configuration.selectionLimit = 30
configuration.filter = .images
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self, tusClient: tusClient)
}
// Use a Coordinator to act as your PHPickerViewControllerDelegate
class Coordinator: PHPickerViewControllerDelegate {
private let parent: PhotoPicker
private let tusClient: TUSClient
init(_ parent: PhotoPicker, tusClient: TUSClient) {
self.parent = parent
self.tusClient = tusClient
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
var images = [Data]()
for result in results {
result.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { [weak self] (object, error) in
guard let self = self else { return }
if let image = object as? UIImage {
if let imageData = image.jpegData(compressionQuality: 0.7) {
images.append(imageData)
} else {
print("Could not retrieve image data")
}
if results.count == images.count {
print("Received \(images.count) images")
do {
try self.tusClient.uploadMultiple(dataFiles: images)
} catch {
print("Error is \(error)")
}
}
} else {
print(object)
print(error)
}
})
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
| mit | f86765e696768034c48538dd4ccffbdc | 32.880952 | 121 | 0.534434 | 5.820041 | false | true | false | false |
vikingosegundo/TaCoPopulator | Example/TaCoPopulator/TableViewController.swift | 1 | 977 | //
// ViewController.swift
// Populator
//
// Created by Manuel Meyer on 03.12.16.
// Copyright © 2016 Manuel Meyer. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private var datasource: ViewControllerDataSource<UITableView>?
override func viewDidLoad() {
super.viewDidLoad()
self.datasource = ViewControllerDataSource(with: tableView)
self.datasource?.intSelected = {
[weak self] int, indexPath in
guard let `self` = self else { return }
print("\(int) @ \(indexPath) @ \(String(describing: self.tableView.cellForRow(at: indexPath)))")
}
self.datasource?.stringSelected = {
[weak self] str, indexPath in
guard let `self` = self else { return }
print("\(str) @ \(indexPath) @ \(String(describing: self.tableView.cellForRow(at: indexPath)))")
}
}
}
| mit | 8c6afad2623deaae2aa7cf4f105f9089 | 30.483871 | 108 | 0.626025 | 4.539535 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Controllers/UI/MapContainer/MapController.swift | 1 | 4206 | //
// MapController.swift
// TrolleyTracker
//
// Created by Austin Younts on 7/30/17.
// Copyright © 2017 Code For Greenville. All rights reserved.
//
import UIKit
import MapKit
protocol MapControllerDelegate: class {
func annotationSelected(_ annotation: MKAnnotationView?,
userLocation: MKUserLocation?)
func handleNoTrolleysUpdate(_ trolleysPresent: Bool)
}
class MapController: FunctionController {
typealias Dependencies = HasModelController
weak var delegate: MapControllerDelegate?
private let viewController: MapViewController
private let dependencies: Dependencies
private let locationManager = CLLocationManager()
private let mapDelegate = TrolleyMapViewDelegate()
private let refreshTimer = RefreshTimer(interval: 60)
private var modelController: ModelController {
return dependencies.modelController
}
init(dependencies: Dependencies) {
self.dependencies = dependencies
self.viewController = MapViewController()
}
func prepare() -> UIViewController {
viewController.delegate = self
locationManager.requestWhenInUseAuthorization()
modelController.trolleyObservers.add(handleTrolleyUpdate(_:))
viewController.mapView.showsUserLocation = true
viewController.mapView.setRegionToDowntownGreenville()
viewController.mapView.delegate = mapDelegate
mapDelegate.annotationSelectionAction = { view in
self.undimAllItems()
let user = self.viewController.mapView.userLocation
self.delegate?.annotationSelected(view,
userLocation: user)
self.dimItemsNotRelated(toView: view)
}
mapDelegate.annotationDeselectionAction = { view in
self.delegate?.annotationSelected(nil, userLocation: nil)
self.undimAllItems()
}
refreshTimer.action = loadRoutes
return viewController
}
private func handleTrolleyUpdate(_ trolleys: [Trolley]) {
viewController.mapView.addOrUpdateTrolley(trolleys)
delegate?.handleNoTrolleysUpdate(!trolleys.isEmpty)
}
private func loadRoutes() {
modelController.loadTrolleyRoutes { routes in
self.viewController.mapView.replaceCurrentRoutes(with: routes)
}
}
private func dimItemsNotRelated(toView view: MKAnnotationView) {
guard let trolleyView = view as? TrolleyAnnotationView,
let trolley = trolleyView.annotation as? Trolley,
let route = modelController.route(for: trolley) else {
return
}
mapDelegate.highlightedTrolley = trolley
mapDelegate.highlightedRoute = route
mapDelegate.shouldDimStops = true
viewController.mapView.setStops(faded: true)
viewController.mapView.reloadRouteOverlays()
viewController.dimTrolleysOtherThan(trolley)
}
private func undimAllItems() {
mapDelegate.highlightedTrolley = nil
mapDelegate.highlightedRoute = nil
mapDelegate.shouldDimStops = false
viewController.mapView.undimAllTrolleyAnnotations()
viewController.mapView.reloadRouteOverlays()
viewController.mapView.setStops(faded: false)
}
func unobscure(_ view: UIView) {
guard
let annotationView = view as? MKAnnotationView,
let annotation = annotationView.annotation
else { return }
viewController.mapView.setCenter(annotation.coordinate, animated: true)
}
}
extension MapController: MapVCDelegate {
func locateMeButtonTapped() {
viewController.mapView.centerOnUser(context: viewController)
}
func annotationSelected(_ annotation: MKAnnotationView?,
userLocation: MKUserLocation?) {
delegate?.annotationSelected(annotation, userLocation: userLocation)
}
func viewAppeared() {
loadRoutes()
modelController.startTrackingTrolleys()
refreshTimer.start()
}
func viewDisappeared() {
refreshTimer.stop()
modelController.stopTrackingTrolleys()
}
}
| mit | 107fed02d66f38900f7c6fcd56a422c5 | 30.148148 | 79 | 0.679667 | 5.461039 | false | false | false | false |
me-abhinav/NumberMorphView | Pod/Classes/NumberMorphView.swift | 1 | 19040 | //
// NumberMorphView.swift
// Pods
//
// Created by Abhinav Chauhan on 14/03/16.
//
//
import Foundation
import UIKit
import QuartzCore
public protocol InterpolatorProtocol {
func getInterpolation(_ x: CGFloat) -> CGFloat;
}
// Recommended ration for width : height is 13 : 24
@IBDesignable open class NumberMorphView: UIView {
fileprivate static let DEFAULT_FONT_SIZE: CGFloat = 24;
// *************************************************************************************************
// * IBInspectable properties
// *************************************************************************************************
@IBInspectable open var fontSize: CGFloat = NumberMorphView.DEFAULT_FONT_SIZE {
didSet {
self.lineWidth = fontSize / 16;
invalidateIntrinsicContentSize();
}
}
@IBInspectable open var lineWidth: CGFloat = 2 {
didSet {
path.lineWidth = lineWidth;
shapeLayer.lineWidth = lineWidth;
}
}
@IBInspectable open var fontColor: UIColor = UIColor.black.withAlphaComponent(0.6) {
didSet {
self.shapeLayer.strokeColor = fontColor.cgColor;
}
}
@IBInspectable open var animationDuration: Double = 0.5 {
didSet {
if let displayLink = displayLink, displayLink.duration > 0 {
maxFrames = Int(animationDuration / displayLink.duration);
}
}
}
// *************************************************************************************************
// * Private properties
// *************************************************************************************************
fileprivate var endpoints_original: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 5), count: 10);
fileprivate var controlPoints1_original: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 4), count: 10);
fileprivate var controlPoints2_original: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 4), count: 10);
fileprivate var endpoints_scaled: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 5), count: 10);
fileprivate var controlPoints1_scaled: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 4), count: 10);
fileprivate var controlPoints2_scaled: [[[CGFloat]]] = Array(repeating: Array(repeating: Array(repeating: 0, count: 2), count: 4), count: 10);
fileprivate var paths = [UIBezierPath]();
fileprivate var maxFrames = 0; // will be initialized in first update() call
fileprivate var _currentDigit = 0;
fileprivate var _nextDigit = 0;
fileprivate var currentFrame = 1;
fileprivate var displayLink: CADisplayLink?;
fileprivate var path = UIBezierPath();
fileprivate var shapeLayer = CAShapeLayer();
// *************************************************************************************************
// * Constructors
// *************************************************************************************************
override init(frame: CGRect) {
super.init(frame: frame);
initialize();
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initialize();
}
override open func layoutSubviews() {
super.layoutSubviews();
scalePoints();
initializePaths();
shapeLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height);
if nil == displayLink || displayLink!.isPaused {
drawDigitWithoutAnimation(_currentDigit);
}
}
override open var intrinsicContentSize : CGSize {
return CGSize(width: fontSize * 0.65, height: fontSize * 1.2);
}
// *************************************************************************************************
// * Method overrides
// *************************************************************************************************
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return self.intrinsicContentSize;
}
// *************************************************************************************************
// * Public properties and methods
// *************************************************************************************************
open var interpolator: InterpolatorProtocol = OvershootInterpolator(tension: 1.3);
open var currentDigit: Int {
get {
return _currentDigit;
}
set {
_currentDigit = newValue;
_nextDigit = _currentDigit;
}
}
open var nextDigit: Int {
get {
return _nextDigit;
}
set {
animateToDigit(newValue);
}
}
open func animateToDigit(_ digit: Int) {
_currentDigit = _nextDigit;
_nextDigit = digit;
currentFrame = 1;
displayLink?.isPaused = false;
}
open func animateToDigit_withCABasicAnimation(_ digit: Int) {
_currentDigit = _nextDigit;
_nextDigit = digit;
let anim = CABasicAnimation(keyPath: "path");
anim.duration = 0.2;
anim.fromValue = paths[_currentDigit].cgPath;
anim.toValue = paths[_nextDigit].cgPath;
anim.repeatCount = 0;
anim.fillMode = kCAFillModeForwards;
anim.isRemovedOnCompletion = false;
anim.autoreverses = false;
CATransaction.begin();
CATransaction.setCompletionBlock() {
self._currentDigit = self._nextDigit;
print("completed");
}
shapeLayer.add(anim, forKey: "path");
CATransaction.commit();
}
// *************************************************************************************************
// * Helper / utility methods
// *************************************************************************************************
fileprivate func drawDigitWithoutAnimation(_ digit: Int) {
let p = endpoints_scaled[digit];
let cp1 = controlPoints1_scaled[digit];
let cp2 = controlPoints2_scaled[digit];
path.removeAllPoints();
path.move(to: CGPoint(x: p[0][0], y: p[0][1]));
for i in 1..<p.count {
let endpoint = CGPoint(x: p[i][0], y: p[i][1]);
let cp1 = CGPoint(x: cp1[i-1][0], y: cp1[i-1][1]);
let cp2 = CGPoint(x: cp2[i-1][0], y: cp2[i-1][1]);
path.addCurve(to: endpoint, controlPoint1: cp1, controlPoint2: cp2);
}
shapeLayer.path = path.cgPath;
}
@objc func updateAnimationFrame() {
if maxFrames <= 0 {
if let displayLink = displayLink {
maxFrames = Int(animationDuration / displayLink.duration);
}
}
let pCur = endpoints_scaled[_currentDigit];
let cp1Cur = controlPoints1_scaled[_currentDigit];
let cp2Cur = controlPoints2_scaled[_currentDigit];
let pNext = endpoints_scaled[_nextDigit];
let cp1Next = controlPoints1_scaled[_nextDigit];
let cp2Next = controlPoints2_scaled[_nextDigit];
path.removeAllPoints();
let factor: CGFloat = interpolator.getInterpolation((CGFloat)(currentFrame) / (CGFloat)(maxFrames));
path.move(to: CGPoint(x: pCur[0][0] + (pNext[0][0] - pCur[0][0]) * factor, y: pCur[0][1] + (pNext[0][1] - pCur[0][1]) * factor));
for i in 1..<pCur.count {
let ex = pCur[i][0] + (pNext[i][0] - pCur[i][0]) * factor
let ey = pCur[i][1] + (pNext[i][1] - pCur[i][1]) * factor;
let endpoint = CGPoint(x: ex, y: ey);
let iMinus1 = i-1;
let cp1x = cp1Cur[iMinus1][0] + (cp1Next[iMinus1][0] - cp1Cur[iMinus1][0]) * factor;
let cp1y = cp1Cur[iMinus1][1] + (cp1Next[iMinus1][1] - cp1Cur[iMinus1][1]) * factor;
let cp1 = CGPoint(x: cp1x, y: cp1y);
let cp2x = cp2Cur[iMinus1][0] + (cp2Next[iMinus1][0] - cp2Cur[iMinus1][0]) * factor;
let cp2y = cp2Cur[iMinus1][1] + (cp2Next[iMinus1][1] - cp2Cur[iMinus1][1]) * factor;
let cp2 = CGPoint(x: cp2x, y: cp2y);
path.addCurve(to: endpoint, controlPoint1: cp1, controlPoint2: cp2);
}
shapeLayer.path = path.cgPath;
currentFrame += 1;
if currentFrame > maxFrames {
currentFrame = 1;
currentDigit = _nextDigit;
displayLink?.isPaused = true;
drawDigitWithoutAnimation(currentDigit);
}
}
fileprivate func initialize() {
path.lineJoinStyle = .round;
path.lineCapStyle = .round;
path.miterLimit = -10;
path.lineWidth = self.lineWidth;
shapeLayer.fillColor = UIColor.clear.cgColor;
shapeLayer.strokeColor = self.fontColor.cgColor;
shapeLayer.lineWidth = self.lineWidth;
shapeLayer.contentsScale = UIScreen.main.scale;
shapeLayer.shouldRasterize = false;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.lineJoin = kCALineJoinRound;
self.layer.addSublayer(shapeLayer);
displayLink = CADisplayLink(target: self, selector: #selector(NumberMorphView.updateAnimationFrame));
displayLink?.frameInterval = 1;
displayLink?.isPaused = true;
displayLink?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes);
endpoints_original[0] = [[500, 800], [740, 400], [500, 0], [260, 400], [500, 800]];
endpoints_original[1] = [[383, 712], [500, 800], [500, 0], [500, 800], [383, 712]];
endpoints_original[2] = [[300, 640], [700, 640], [591, 369], [300, 0], [700, 0]];
endpoints_original[3] = [[300, 600], [700, 600], [500, 400], [700, 200], [300, 200]];
endpoints_original[4] = [[650, 0], [650, 140], [650, 800], [260, 140], [760, 140]];
endpoints_original[5] = [[645, 800], [400, 800], [300, 480], [690, 285], [272, 92]];
endpoints_original[6] = [[640, 800], [321, 458], [715, 144], [257, 146], [321, 458]];
endpoints_original[7] = [[275, 800], [725, 800], [586, 544], [424, 262], [275, 0]];
endpoints_original[8] = [[500, 400], [500, 0], [500, 400], [500, 800], [500, 400]];
endpoints_original[9] = [[679, 342], [743, 654], [285, 656], [679, 342], [360, 0]];
controlPoints1_original[0] = [[650, 800], [740, 200], [350, 0], [260, 600]];
controlPoints1_original[1] = [[383, 712], [500, 488], [500, 488], [383, 712]];
controlPoints1_original[2] = [[335, 853], [710, 538], [477, 213], [450, 0]];
controlPoints1_original[3] = [[300, 864], [700, 400], [500, 400], [700, -64]];
controlPoints1_original[4] = [[650, 50], [650, 340], [502, 572], [350, 140]];
controlPoints1_original[5] = [[550, 800], [400, 800], [495, 567], [717, 30]];
controlPoints1_original[6] = [[578, 730], [492, 613], [634, -50], [208, 264]];
controlPoints1_original[7] = [[350, 800], [676, 700], [538, 456], [366, 160],];
controlPoints1_original[8] = [[775, 400], [225, 0], [225, 400], [775, 800]];
controlPoints1_original[9] = [[746, 412], [662, 850], [164, 398], [561, 219]];
controlPoints2_original[0] = [[740, 600], [650, 0], [260, 200], [350, 800]];
controlPoints2_original[1] = [[500, 800], [500, 312], [500, 312], [500, 800]];
controlPoints2_original[2] = [[665, 853], [658, 461], [424, 164], [544, 1]];
controlPoints2_original[3] = [[700, 864], [500, 400], [700, 400], [300, -64]];
controlPoints2_original[4] = [[650, 100], [650, 600], [356, 347], [680, 140]];
controlPoints2_original[5] = [[450, 800], [300, 480], [672, 460], [410, -100]];
controlPoints2_original[6] = [[455, 602], [840, 444], [337, -46], [255, 387]];
controlPoints2_original[7] = [[500, 800], [634, 631], [487, 372], [334, 102]];
controlPoints2_original[8] = [[775, 0], [225, 400], [225, 800], [775, 400]];
controlPoints2_original[9] = [[792, 536], [371, 840], [475, 195], [432, 79]];
for digit in 0..<endpoints_original.count {
for pointIndex in 0..<endpoints_original[digit].count {
endpoints_original[digit][pointIndex][1] = 800 - endpoints_original[digit][pointIndex][1];
if pointIndex < 4 {
controlPoints1_original[digit][pointIndex][1] = 800 - controlPoints1_original[digit][pointIndex][1];
controlPoints2_original[digit][pointIndex][1] = 800 - controlPoints2_original[digit][pointIndex][1];
}
} // for pointIndex
} // for digit
}
fileprivate func scalePoints() {
let width = self.bounds.width;
let height = self.bounds.height;
for digit in 0..<endpoints_original.count {
for pointIndex in 0..<endpoints_original[digit].count {
endpoints_scaled[digit][pointIndex][0] = (endpoints_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width;
endpoints_scaled[digit][pointIndex][1] = (endpoints_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height;
if pointIndex < 4 {
controlPoints1_scaled[digit][pointIndex][0] = (controlPoints1_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width;
controlPoints1_scaled[digit][pointIndex][1] = (controlPoints1_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height;
controlPoints2_scaled[digit][pointIndex][0] = (controlPoints2_original[digit][pointIndex][0] / 1000.0 * 1.4 - 0.2) * width;
controlPoints2_scaled[digit][pointIndex][1] = (controlPoints2_original[digit][pointIndex][1] / 800.0 * 0.6 + 0.2) * height;
}
} // for pointIndex
} // for digit
}
fileprivate func initializePaths() {
paths.removeAll();
for digit in 0...9 {
paths.append(UIBezierPath());
var p = endpoints_scaled[digit];
var cp1 = controlPoints1_scaled[digit];
var cp2 = controlPoints2_scaled[digit];
paths[digit].move(to: CGPoint(x: p[0][0], y: p[0][1]));
for i in 1..<p.count {
let endpoint = CGPoint(x: p[i][0], y: p[i][1]);
let cp1 = CGPoint(x: cp1[i-1][0], y: cp1[i-1][1]);
let cp2 = CGPoint(x: cp2[i-1][0], y: cp2[i-1][1]);
paths[digit].addCurve(to: endpoint, controlPoint1: cp1, controlPoint2: cp2);
}
}
}
// *************************************************************************************************
// * Interpolators for rate of change of animation
// *************************************************************************************************
open class LinearInterpolator: InterpolatorProtocol {
public init() {
}
open func getInterpolation(_ x: CGFloat) -> CGFloat {
return x;
}
}
open class OvershootInterpolator: InterpolatorProtocol {
fileprivate var tension: CGFloat;
public convenience init() {
self.init(tension: 2.0);
}
public init(tension: CGFloat) {
self.tension = tension;
}
open func getInterpolation(_ x: CGFloat) -> CGFloat {
let x2 = x - 1.0;
return x2 * x2 * ((tension + 1) * x2 + tension) + 1.0;
}
}
open class SpringInterpolator: InterpolatorProtocol {
fileprivate var tension: CGFloat;
fileprivate let PI = CGFloat(Double.pi);
public convenience init() {
self.init(tension: 0.3);
}
public init(tension: CGFloat) {
self.tension = tension;
}
open func getInterpolation(_ x: CGFloat) -> CGFloat {
return pow(2, -10 * x) * sin((x - tension / 4) * (2 * PI) / tension) + 1;
}
}
open class BounceInterpolator: InterpolatorProtocol {
public init() {
}
func bounce(_ t: CGFloat) -> CGFloat { return t * t * 8; }
open func getInterpolation(_ x: CGFloat) -> CGFloat {
if (x < 0.3535) {
return bounce(x)
} else if (x < 0.7408) {
return bounce(x - 0.54719) + 0.7;
} else if (x < 0.9644) {
return bounce(x - 0.8526) + 0.9;
} else {
return bounce(x - 1.0435) + 0.95;
}
}
}
open class AnticipateOvershootInterpolator: InterpolatorProtocol {
fileprivate var tension: CGFloat = 2.0;
public convenience init() {
self.init(tension: 2.0);
}
public init(tension: CGFloat) {
self.tension = tension;
}
fileprivate func anticipate(_ x: CGFloat, tension: CGFloat) -> CGFloat { return x * x * ((tension + 1) * x - tension); }
fileprivate func overshoot(_ x: CGFloat, tension: CGFloat) -> CGFloat { return x * x * ((tension + 1) * x + tension); }
open func getInterpolation(_ x: CGFloat) -> CGFloat {
if x < 0.5 {
return 0.5 * anticipate(x * 2.0, tension: tension);
} else {
return 0.5 * (overshoot(x * 2.0 - 2.0, tension: tension) + 2.0);
}
}
}
open class CubicHermiteInterpolator: InterpolatorProtocol {
fileprivate var tangent0: CGFloat;
fileprivate var tangent1: CGFloat;
public convenience init() {
self.init(tangent0: 2.2, tangent1: 2.2);
}
public init(tangent0: CGFloat, tangent1: CGFloat) {
self.tangent0 = tangent0;
self.tangent1 = tangent1;
}
func cubicHermite(_ t: CGFloat, start: CGFloat, end: CGFloat, tangent0: CGFloat, tangent1: CGFloat) -> CGFloat {
let t2 = t * t;
let t3 = t2 * t;
return (2 * t3 - 3 * t2 + 1) * start + (t3 - 2 * t2 + t) * tangent0 + (-2 * t3 + 3 * t2) * end + (t3 - t2) * tangent1;
}
open func getInterpolation(_ x: CGFloat) -> CGFloat {
return cubicHermite(x, start: 0, end: 1, tangent0: tangent0, tangent1: tangent1);
}
}
}
| mit | e33e96846f41a41ea837510f68d13de1 | 38.338843 | 148 | 0.505252 | 4.22454 | false | false | false | false |
mcxiaoke/learning-ios | cocoa_programming_for_osx/24_Sheets/Dice/Dice/DieView.swift | 1 | 12897 | //
// DieView.swift
// Dice
//
// Created by mcxiaoke on 16/5/5.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
@IBDesignable class DieView: NSView, NSDraggingSource {
var rollsRemaining: Int = 0
var mouseDownEvent: NSEvent?
var numberOfTimesToRoll: Int = 10
var color: NSColor = NSColor.whiteColor() {
didSet {
needsDisplay = true
}
}
var highlightFroDragging: Bool = false {
didSet {
needsDisplay = true
}
}
var highlighted: Bool = false {
didSet {
needsDisplay = true
}
}
var intValue : Int? = 5 {
didSet {
needsDisplay = true
}
}
var pressed: Bool = false {
didSet {
needsDisplay = true
}
}
func setup(){
self.registerForDraggedTypes([NSPasteboardTypeString])
randomize()
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override var intrinsicContentSize: NSSize {
return NSSize(width: 40, height: 40)
}
override var focusRingMaskBounds: NSRect {
return bounds
}
override func drawFocusRingMask() {
NSBezierPath.fillRect(bounds)
}
override var acceptsFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
return true
}
override func resignFirstResponder() -> Bool {
return true
}
override func keyDown(theEvent: NSEvent) {
interpretKeyEvents([theEvent])
}
override func insertTab(sender: AnyObject?) {
window?.selectNextKeyView(sender)
}
override func insertBacktab(sender: AnyObject?) {
window?.selectPreviousKeyView(sender)
}
override func insertText(insertString: AnyObject) {
let text = insertString as! String
if let number = Int(text) {
intValue = number
}
}
override func mouseEntered(theEvent: NSEvent) {
highlighted = true
window?.makeFirstResponder(self)
}
override func mouseExited(theEvent: NSEvent) {
highlighted = false
}
override func viewDidMoveToWindow() {
window?.acceptsMouseMovedEvents = true
// let options: NSTrackingAreaOptions = .MouseEnteredAndExited | .ActiveAlways | .InVisibleRect
// Swift 2 fix
// http://stackoverflow.com/questions/36560189/no-candidates-produce-the-expected-contextual-result-type-nstextstorageedit
let options: NSTrackingAreaOptions = [.MouseEnteredAndExited, .ActiveAlways, .InVisibleRect ]
let trackingArea = NSTrackingArea(rect: NSRect(), options: options, owner: self, userInfo: nil)
addTrackingArea(trackingArea)
}
func randomize() {
intValue = Int(arc4random_uniform(5)+1)
}
func roll() {
rollsRemaining = numberOfTimesToRoll
NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(rollTick), userInfo: nil, repeats: true)
window?.makeFirstResponder(nil)
}
func rollTick(sender:NSTimer){
let lastIntValue = intValue
while intValue == lastIntValue {
randomize()
}
rollsRemaining -= 1
if rollsRemaining == 0 {
sender.invalidate()
window?.makeFirstResponder(self)
}
}
override func mouseDown(theEvent: NSEvent) {
mouseDownEvent = theEvent
let pointInView = convertPoint(theEvent.locationInWindow, fromView: nil)
// let dieFrame = metricsForSize(bounds.size).dieFrame
// pressed = dieFrame.contains(pointInView)
pressed = diePathWithSize(bounds.size).containsPoint(pointInView)
}
override func mouseDragged(theEvent: NSEvent) {
// Swift.print("mouse dragged, location: \(theEvent.locationInWindow)")
let downPoint = mouseDownEvent!.locationInWindow
let dragPoint = theEvent.locationInWindow
let distanceDragged = hypot(downPoint.x - dragPoint.x, downPoint.y - dragPoint.y)
if distanceDragged < 3 { return }
pressed = false
if let intValue = intValue {
let imageSize = bounds.size
let image = NSImage(size: imageSize, flipped: false) { (imageBounds) in
self.drawDieWithSize(imageBounds.size)
return true
}
let draggingFrameOrigin = convertPoint(downPoint, fromView: nil)
let draggingFrame = NSRect(origin: draggingFrameOrigin, size: imageSize)
.offsetBy(dx: -imageSize.width/2, dy: -imageSize.height/2)
let pbItem = NSPasteboardItem()
let bitmap = self.bitmapImageRepForCachingDisplayInRect(self.bounds)!
self.cacheDisplayInRect(self.bounds, toBitmapImageRep: bitmap)
pbItem.setString("\(intValue)", forType: NSPasteboardTypeString)
pbItem.setData(bitmap.representationUsingType(.NSPNGFileType, properties: [:]), forType: NSPasteboardTypePNG)
let item = NSDraggingItem(pasteboardWriter: pbItem)
item.draggingFrame = draggingFrame
item.imageComponentsProvider = {
let component = NSDraggingImageComponent(key: NSDraggingImageComponentIconKey)
component.contents = image
component.frame = NSRect(origin: NSPoint(), size: imageSize)
return [component]
}
beginDraggingSessionWithItems([item], event: mouseDownEvent!, source: self)
}
}
override func mouseUp(theEvent: NSEvent) {
// Swift.print("mouse up click count: \(theEvent.clickCount)")
if theEvent.clickCount == 2 {
roll()
}
pressed = false
}
// dragging source
func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext) -> NSDragOperation {
return [.Copy, .Delete]
}
func draggingSession(session: NSDraggingSession, endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) {
if operation == .Delete {
intValue = nil
}
}
// dragging destination
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if sender.draggingSource() as? DieView == self {
return .None
}
highlightFroDragging = true
return sender.draggingSourceOperationMask()
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
Swift.print("operation mask = \(sender.draggingSourceOperationMask().rawValue)")
if sender.draggingSource() === self {
return .None
}
return [.Copy,.Delete]
}
override func draggingExited(sender: NSDraggingInfo?) {
highlightFroDragging = false
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
return readFromPasteboard(sender.draggingPasteboard())
}
override func concludeDragOperation(sender: NSDraggingInfo?) {
highlightFroDragging = false
}
override func drawRect(dirtyRect: NSRect) {
let bgColor = NSColor.lightGrayColor()
bgColor.set()
NSBezierPath.fillRect(bounds)
// NSColor.greenColor().set()
// let path = NSBezierPath()
// path.moveToPoint(NSPoint(x: 0, y: 0))
// path.lineToPoint(NSPoint(x: bounds.width, y: bounds.height))
// path.stroke()
if highlightFroDragging {
let gradient = NSGradient(startingColor: color,
endingColor: NSColor.grayColor())
gradient?.drawInRect(bounds, relativeCenterPosition: NSZeroPoint)
}else{
// if highlighted {
// NSColor.redColor().set()
// let rect = CGRect(x: 5, y: bounds.height - 15, width: 10, height: 10)
// NSBezierPath(ovalInRect:rect).fill()
// }
drawDieWithSize(bounds.size)
}
}
func metricsForSize(size:CGSize) -> (edgeLength: CGFloat, dieFrame: CGRect, drawingBounds:CGRect) {
let edgeLength = min(size.width, size.height)
let padding = edgeLength / 10.0
// at center
let ox = (size.width - edgeLength )/2
let oy = (size.height - edgeLength)/2
let drawingBounds = CGRect(x: ox, y: oy, width: edgeLength, height: edgeLength)
var dieFrame = drawingBounds.insetBy(dx: padding, dy: padding)
if pressed {
dieFrame = dieFrame.offsetBy(dx: 0, dy: -edgeLength/40)
}
return (edgeLength, dieFrame, drawingBounds)
}
func diePathWithSize(size:CGSize) -> NSBezierPath {
let (edgeLength, dieFrame, _) = metricsForSize(size)
let cornerRadius:CGFloat = edgeLength / 5.0
return NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius)
}
func drawDieWithSize(size:CGSize) {
if let intValue = intValue {
let (edgeLength, dieFrame, drawingBounds) = metricsForSize(size)
let cornerRadius:CGFloat = edgeLength / 5.0
let dotRadius = edgeLength / 12.0
let dotFrame = dieFrame.insetBy(dx: dotRadius * 2.5, dy: dotRadius * 2.5)
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -1)
shadow.shadowBlurRadius = ( pressed ? edgeLength/100 : edgeLength / 20)
shadow.set()
color.set()
NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius).fill()
NSGraphicsContext.restoreGraphicsState()
// NSColor.redColor().set()
NSColor.blackColor().set()
let gradient = NSGradient(startingColor: NSColor.redColor(), endingColor: NSColor.greenColor())
// gradient?.drawInRect(drawingBounds, angle: 180.0)
func drawDot(u: CGFloat, v:CGFloat) {
let dotOrigin = CGPoint(x: dotFrame.minX + dotFrame.width * u,
y: dotFrame.minY + dotFrame.height * v)
let dotRect = CGRect(origin: dotOrigin, size: CGSizeZero).insetBy(dx: -dotRadius, dy: -dotRadius)
let path = NSBezierPath(ovalInRect: dotRect)
path.fill()
}
if (1...6).indexOf(intValue) != nil {
if [1,3,5].indexOf(intValue) != nil {
drawDot(0.5, v: 0.5)
}
if (2...6).indexOf(intValue) != nil {
drawDot(0, v: 1)
drawDot(1, v: 0)
}
if (4...6).indexOf(intValue) != nil {
drawDot(1, v: 1)
drawDot(0, v: 0)
}
if intValue == 6 {
drawDot(0, v: 0.5)
drawDot(1, v: 0.5)
}
}else{
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let font = NSFont.systemFontOfSize(edgeLength * 0.5)
let attrs = [
NSForegroundColorAttributeName: NSColor.blackColor(),
NSFontAttributeName: font,
NSParagraphStyleAttributeName: paraStyle
]
let string = "\(intValue)" as NSString
string.drawCenteredInRect(dieFrame, withAttributes: attrs)
}
}
}
@IBAction func saveAsPDF(sender: AnyObject!) {
let sp = NSSavePanel()
sp.allowedFileTypes = ["pdf"]
sp.beginSheetModalForWindow(window!) { [unowned sp] (result) in
if result == NSModalResponseOK {
//
let data = self.dataWithPDFInsideRect(self.bounds)
do {
try data.writeToURL(sp.URL!, options: NSDataWritingOptions.DataWritingAtomic)
}catch {
let alert = NSAlert()
alert.messageText = "Save Error"
alert.informativeText = "Can not save as PDF!"
alert.runModal()
}
}
}
}
// pasteboard
func writeToPasteboard(pasteboard: NSPasteboard) {
if let value = intValue {
let text = "\(value)"
let image = self.bitmapImageRepForCachingDisplayInRect(self.bounds)!
self.cacheDisplayInRect(self.bounds, toBitmapImageRep: image)
pasteboard.clearContents()
pasteboard.setString(text, forType: NSPasteboardTypeString)
pasteboard.setData(image.representationUsingType(.NSPNGFileType, properties: [:]), forType: NSPasteboardTypePNG)
self.writePDFInsideRect(self.bounds, toPasteboard: pasteboard)
}
}
func readFromPasteboard(pasteboard: NSPasteboard) -> Bool {
let objects = pasteboard.readObjectsForClasses([NSString.self], options: [:]) as! [String]
if let str = objects.first {
intValue = Int(str)
return true
}
return false
}
@IBAction func cut(sender: AnyObject?) {
writeToPasteboard(NSPasteboard.generalPasteboard())
intValue = nil
}
@IBAction func copy(sender:AnyObject?) {
writeToPasteboard(NSPasteboard.generalPasteboard())
}
@IBAction func paste(sender:AnyObject?) {
readFromPasteboard(NSPasteboard.generalPasteboard())
}
@IBAction func delete(sener: AnyObject?) {
intValue = nil
}
override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(copy(_:)):
return intValue != nil
case #selector(cut(_:)):
return intValue != nil
case #selector(delete(_:)):
return intValue != nil
default:
return super.validateMenuItem(menuItem)
}
}
}
| apache-2.0 | d67b08c012325d1e5b7298d300427576 | 28.709677 | 137 | 0.657127 | 4.440083 | false | false | false | false |
mthistle/SendHapticSwift | SendHapticSwift/BandManager.swift | 2 | 2993 | //
// BandManager.swift
// Blitz Talk
//
// Created by Mark Thistle on 3/16/15.
// Copyright (c) 2015 New Thistle LLC. All rights reserved.
//
import Foundation
let kConnectionChangedNotification = "kConnectionChangedNotification"
let kConnectionFailedNotification = "kConnectionFailedNotification"
private let _SharedBandManagerInstance = BandManager()
class BandManager : NSObject, MSBClientManagerDelegate {
private(set) var client: MSBClient?
private var connectionBlock: ((Bool) -> ())?
private var discoveredClients = [MSBClient]()
private var clientManager = MSBClientManager.sharedManager()
class var sharedInstance: BandManager {
return _SharedBandManagerInstance
}
override init() {
super.init()
self.clientManager.delegate = self
}
func attachedClients() -> [MSBClient]? {
if let manager = self.clientManager {
self.discoveredClients = [MSBClient]()
for client in manager.attachedClients() {
self.discoveredClients.append(client as! MSBClient)
}
}
return self.discoveredClients
}
func disconnectClient(client: MSBClient) {
if (!client.isDeviceConnected) {
return;
}
if let manager = self.clientManager {
manager.cancelClientConnection(client)
self.client = nil
}
}
func connectClient(client: MSBClient, completion: (connected: Bool) -> Void) {
if (client.isDeviceConnected && self.client == client) {
if (self.connectionBlock != nil)
{
self.connectionBlock!(true)
}
return;
}
if let connectedClient = self.client {
self.disconnectClient(client)
}
self.connectionBlock = completion;
self.clientManager.connectClient(client)
}
func clientManager(clientManager: MSBClientManager!, clientDidConnect client: MSBClient!) {
if (self.connectionBlock != nil) {
self.client = client
self.connectionBlock!(true)
self.connectionBlock = nil
}
self.fireClientChangeNotification(client)
}
func clientManager(clientManager: MSBClientManager!, clientDidDisconnect client: MSBClient!) {
self.fireClientChangeNotification(client)
}
func clientManager(clientManager: MSBClientManager!, client: MSBClient!, didFailToConnectWithError error: NSError!) {
if error != nil {
println(error)
}
NSNotificationCenter.defaultCenter().postNotificationName(kConnectionFailedNotification, object: self, userInfo: ["client": client])
}
func fireClientChangeNotification(client: MSBClient) {
NSNotificationCenter.defaultCenter().postNotificationName(kConnectionChangedNotification, object: self, userInfo: ["client": client])
}
}
| mit | a4a7b057dffd60887b2dd1427335e695 | 30.505263 | 141 | 0.637153 | 4.858766 | false | false | false | false |
clostra/dcdn | ios/vpn/NewNode VPN/FontUpdater.swift | 1 | 1765 | //
// FontUpdater.swift
// NewNode VPN
//
// Created by Mikhail Koroteev on 06/02/21.
// Copyright © 2021 Clostra. All rights reserved.
//
import Foundation
import UIKit
extension UIFont {
func with(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont {
guard let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits).union(self.fontDescriptor.symbolicTraits)) else {
return self
}
return UIFont(descriptor: descriptor, size: 0)
}
func without(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont {
guard let descriptor = self.fontDescriptor.withSymbolicTraits(self.fontDescriptor.symbolicTraits.subtracting(UIFontDescriptor.SymbolicTraits(traits))) else {
return self
}
return UIFont(descriptor: descriptor, size: 0)
}
}
extension UIButton {
func underline( bold: Bool ) {
guard let text = self.titleLabel?.text else { return }
guard let color = self.titleColor(for: .normal) else { return }
guard var font = self.titleLabel?.font else { return }
if bold {
font = font.with(.traitBold)
} else {
font = font.without(.traitBold)
}
let attributedString = NSMutableAttributedString(string: text)
let range = NSRange(location: 0, length: text.count)
let attributes: [NSAttributedString.Key : Any] =
[.font : font,
.underlineColor : color,
.foregroundColor : color,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
attributedString.addAttributes(attributes, range: range)
self.setAttributedTitle(attributedString, for: .normal)
}
}
| gpl-2.0 | df7211b8c09db18b2948029e678accb2 | 32.923077 | 165 | 0.645125 | 4.859504 | false | false | false | false |
tehprofessor/SwiftyFORM | Example/Usecases/SignUpViewController.swift | 1 | 5451 | // MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class SignUpViewController: FormViewController {
override func loadView() {
super.loadView()
form_installSubmitButton()
}
override func populate(builder: FormBuilder) {
builder.navigationTitle = "Sign Up"
builder.toolbarMode = .Simple
builder.demo_showInfo("SocialNetwork 123\nSign up form")
builder += SectionHeaderTitleFormItem().title("Details")
builder += userName
builder += password
builder += email
builder += maleOrFemale
builder += birthday
builder.alignLeft([userName, password, email])
builder += SectionFormItem()
builder += subscribeToNewsletter
builder += SectionFooterTitleFormItem().title("There is no way to unsubscribe our service")
builder += metaData
builder += SectionHeaderTitleFormItem().title("Buttons")
builder += randomizeButton
builder += jsonButton
}
lazy var userName: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("User Name").placeholder("required")
instance.keyboardType = .ASCIICapable
instance.autocorrectionType = .No
instance.validate(CharacterSetSpecification.lowercaseLetterCharacterSet(), message: "Must be lowercase letters")
instance.submitValidate(CountSpecification.min(6), message: "Length must be minimum 6 letters")
instance.validate(CountSpecification.max(8), message: "Length must be maximum 8 letters")
return instance
}()
lazy var maleOrFemale: ViewControllerFormItem = {
let instance = ViewControllerFormItem()
instance.title("Male or Female").placeholder("required")
instance.createViewController = { (dismissCommand: CommandProtocol) in
let vc = MaleFemaleViewController(dismissCommand: dismissCommand)
return vc
}
instance.willPopViewController = { (context: ViewControllerFormItemPopContext) in
if let x = context.returnedObject as? SwiftyFORM.OptionRowFormItem {
context.cell.detailTextLabel?.text = x.title
} else {
context.cell.detailTextLabel?.text = nil
}
}
return instance
}()
lazy var password: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("PIN Code").password().placeholder("required")
instance.keyboardType = .NumberPad
instance.autocorrectionType = .No
instance.validate(CharacterSetSpecification.decimalDigitCharacterSet(), message: "Must be digits")
instance.submitValidate(CountSpecification.min(4), message: "Length must be minimum 4 digits")
instance.validate(CountSpecification.max(6), message: "Length must be maximum 6 digits")
return instance
}()
lazy var email: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("Email").placeholder("[email protected]")
instance.keyboardType = .EmailAddress
instance.submitValidate(CountSpecification.min(6), message: "Length must be minimum 6 letters")
instance.validate(CountSpecification.max(60), message: "Length must be maximum 60 letters")
instance.softValidate(EmailSpecification(), message: "Must be a valid email address")
return instance
}()
func offsetDate(date: NSDate, years: Int) -> NSDate? {
let dateComponents = NSDateComponents()
dateComponents.year = years
let calendar = NSCalendar.currentCalendar()
return calendar.dateByAddingComponents(dateComponents, toDate: date, options: NSCalendarOptions(rawValue: 0))
}
lazy var birthday: DatePickerFormItem = {
let today = NSDate()
let instance = DatePickerFormItem()
instance.title("Birthday")
instance.datePickerMode = .Date
instance.minimumDate = self.offsetDate(today, years: -150)
instance.maximumDate = today
return instance
}()
lazy var subscribeToNewsletter: SwitchFormItem = {
let instance = SwitchFormItem()
instance.title("Subscribe to newsletter")
instance.value = true
return instance
}()
lazy var metaData: MetaFormItem = {
let instance = MetaFormItem()
var dict = Dictionary<String, AnyObject>()
dict["key0"] = "I'm hidden text"
dict["key1"] = "I'm included when exporting to JSON"
dict["key2"] = "Can be used to pass extra info along with the JSON"
instance.value(dict).elementIdentifier("metaData")
return instance
}()
lazy var randomizeButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title("Randomize")
instance.action = { [weak self] in
self?.randomize()
}
return instance
}()
func pickRandom(strings: [String]) -> String {
if strings.count == 0 {
return ""
}
let i = randomInt(0, strings.count - 1)
return strings[i]
}
func pickRandomDate() -> NSDate? {
let i = randomInt(20, 60)
let today = NSDate()
return offsetDate(today, years: -i)
}
func pickRandomBoolean() -> Bool {
let i = randomInt(0, 1)
return i == 0
}
func randomize() {
userName.value = pickRandom(["john", "Jane", "steve", "Bill", "einstein", "Newton"])
password.value = pickRandom(["1234", "0000", "111111", "abc", "111122223333"])
email.value = pickRandom(["[email protected]", "[email protected]", "[email protected]", "[email protected]", "not-a-valid-email"])
birthday.value = self.pickRandomDate()
subscribeToNewsletter.value = pickRandomBoolean()
}
lazy var jsonButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title("JSON")
instance.action = { [weak self] in
if let vc = self {
DebugViewController.showJSON(vc, jsonData: vc.formBuilder.dump())
}
}
return instance
}()
}
| mit | 8a8813d1b31507eca7feca3fc8b3cf81 | 32.857143 | 139 | 0.730508 | 3.930065 | false | false | false | false |
blstream/AugmentedSzczecin_iOS | AugmentedSzczecin/AugmentedSzczecin/ASAnnotationView.swift | 1 | 1454 | //
// ASAnnotationView.swift
// AugmentedSzczecin
//
// Created by Sebastian Jędruszkiewicz on 30/04/15.
// Copyright (c) 2015 BLStream. All rights reserved.
//
import UIKit
class ASAnnotationView : BLSAugmentedAnnotationView {
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
class func nibName() -> String {
return "ASAnnotationView"
}
class func view() -> ASAnnotationView? {
let bundle = NSBundle(forClass: ASAnnotationView.classForCoder())
return UIView.loadFromNibNamed(ASAnnotationView.nibName(), bundle: bundle) as? ASAnnotationView
}
class func view(withPOI: ASPOI, location: CLLocation) ->ASAnnotationView? {
let view = UIView.loadFromNibNamed(ASAnnotationView.nibName(), bundle: NSBundle(forClass: ASAnnotationView.classForCoder())) as? ASAnnotationView
var destinationLat = withPOI.latitude as! CLLocationDegrees
var destinationLon = withPOI.longitude as! CLLocationDegrees
var destinationLoc = CLLocation(latitude: destinationLat, longitude: destinationLon)
view?.distanceLabel.text = String(stringInterpolationSegment: destinationLoc.distanceFromLocation(location))
withPOI.getAddress(CLGeocoder(), completionHandler: { (address) -> Void in
view?.addressLabel.text = address!.name
})
return view
}
}
| apache-2.0 | 4e2a3e3659ae8b9b5e1769e3a66f76f0 | 34.439024 | 153 | 0.688231 | 4.942177 | false | false | false | false |
keatongreve/fastlane | fastlane/swift/main.swift | 11 | 1484 | //
// main.swift
// FastlaneSwiftRunner
//
// Created by Joshua Liebowitz on 8/26/17.
//
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
let argumentProcessor = ArgumentProcessor(args: CommandLine.arguments)
let timeout = argumentProcessor.commandTimeout
class MainProcess {
var doneRunningLane = false
var thread: Thread!
@objc func connectToFastlaneAndRunLane() {
runner.startSocketThread(port: argumentProcessor.port)
let completedRun = Fastfile.runLane(named: argumentProcessor.currentLane, parameters: argumentProcessor.laneParameters())
if completedRun {
runner.disconnectFromFastlaneProcess()
}
doneRunningLane = true
}
func startFastlaneThread() {
thread = Thread(target: self, selector: #selector(connectToFastlaneAndRunLane), object: nil)
thread.name = "worker thread"
thread.start()
}
}
let process: MainProcess = MainProcess()
process.startFastlaneThread()
while (!process.doneRunningLane && (RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 2)))) {
// no op
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
| mit | b68dffaa4464cf213c1dc1217f5364eb | 27.538462 | 136 | 0.701482 | 4.180282 | false | false | false | false |
bi3mer/WorkSpace | Swift/printINt/printINt/main.swift | 1 | 566 | //
// main.swift
// printINt
//
// Created by colan biemer on 3/28/15.
// Copyright (c) 2015 colan biemer. All rights reserved.
//
import Foundation
var int: Int = 1
var double: Double = 2
let float: Float = 3
// Implicist conversion
let testInt = "testing \(int) string"
let testDouble = "testing \(double) string"
let testFloat = "testing \(float) string"
println("int: " + String(int));
println("Double: " + NSString(format:"%.2f",double))
println("Float: " + NSString(format:"%.2f",float));
println(testInt)
println(testDouble)
println(testFloat)
| mit | 5d20675e021c3fc90d7caa785b781c75 | 19.962963 | 57 | 0.676678 | 3.076087 | false | true | false | false |
testpress/ios-app | ios-app/UI/ContentDetailDataSource.swift | 1 | 6403 | //
// ContentDetailDataSource.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
import RealmSwift
class ContentDetailDataSource: NSObject, UIPageViewControllerDataSource {
var contents: [Content]!
var initialPosition: Int!
var contentAttemptCreationDelegate: ContentAttemptCreationDelegate?
init(_ contents: [Content], _ contentAttemptCreationDelegate: ContentAttemptCreationDelegate?) {
super.init()
self.contents = contents
self.contentAttemptCreationDelegate = contentAttemptCreationDelegate
}
func viewControllerAtIndex(_ index: Int) -> UIViewController? {
if (contents.count == 0) || (index >= contents.count) {
return nil
}
let content = contents[index]
try! Realm().write {
content.index = index
}
let storyboard = UIStoryboard(name: Constants.CHAPTER_CONTENT_STORYBOARD, bundle: nil)
if content.getContentType() == .Quiz {
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.START_QUIZ_EXAM_VIEW_CONTROLLER) as! StartQuizExamViewController
viewController.content = content
return viewController
} else if content.exam != nil {
if content.attemptsCount > 0 {
let viewController = storyboard.instantiateViewController(
withIdentifier: Constants.CONTENT_EXAM_ATTEMPS_TABLE_VIEW_CONTROLLER
) as! ContentExamAttemptsTableViewController
viewController.content = content
return viewController
} else {
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.CONTENT_START_EXAM_VIEW_CONTROLLER) as! StartExamScreenViewController
viewController.content = content
return viewController
}
} else if content.attachment != nil {
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.ATTACHMENT_DETAIL_VIEW_CONTROLLER) as! AttachmentDetailViewController
viewController.content = content
viewController.contentAttemptCreationDelegate = contentAttemptCreationDelegate
return viewController
} else if (content.video != nil && content.video!.embedCode.isEmpty) {
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.VIDEO_CONTENT_VIEW_CONTROLLER) as! VideoContentViewController
viewController.content = content
viewController.contents = contents
return viewController
} else if (content.getContentType() == .VideoConference) {
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.VIDEO_CONFERENCE_VIEW_CONTROLLER) as! VideoConferenceViewController
viewController.content = content
return viewController
} else {
let viewController = HtmlContentViewController()
viewController.content = content
viewController.contentAttemptCreationDelegate = contentAttemptCreationDelegate
return viewController
}
}
func indexOfViewController(_ viewController: UIViewController) -> Int {
if viewController is ContentExamAttemptsTableViewController {
return (viewController as! ContentExamAttemptsTableViewController).content.index
} else if viewController is StartExamScreenViewController {
return (viewController as! StartExamScreenViewController).content.index
} else if viewController is AttachmentDetailViewController {
return (viewController as! AttachmentDetailViewController).content.index
} else if viewController is VideoContentViewController {
return (viewController as! VideoContentViewController).content.index
} else if viewController is StartQuizExamViewController{
return (viewController as! StartQuizExamViewController).content.index
} else if viewController is VideoConferenceViewController {
return (viewController as! VideoConferenceViewController).content.index
} else {
return (viewController as! HtmlContentViewController).content.index
}
}
// MARK: - Page View Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore
viewController: UIViewController) -> UIViewController? {
var index = indexOfViewController(viewController)
if index == 0 {
return nil
}
index -= 1
return viewControllerAtIndex(index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter
viewController: UIViewController) -> UIViewController? {
var index = indexOfViewController(viewController)
index += 1
if index == contents.count {
return nil
}
return viewControllerAtIndex(index)
}
}
| mit | df35062d197f80ba9d597657e911e3c6 | 44.084507 | 100 | 0.680256 | 5.900461 | false | false | false | false |
sbooth/SFBAudioEngine | Device/AudioTransportManager.swift | 1 | 6519 | //
// Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
import CoreAudio
/// A HAL audio transport manager object
///
/// This class has a single scope (`kAudioObjectPropertyScopeGlobal`) and a single element (`kAudioObjectPropertyElementMaster`)
/// - remark: This class correponds to objects with base class `kAudioTransportManagerClassID`
public class AudioTransportManager: AudioPlugIn {
/// Returns the available audio transport managers
/// - remark: This corresponds to the property`kAudioHardwarePropertyTransportManagerList` on `kAudioObjectSystemObject`
public class func transportManagers() throws -> [AudioTransportManager] {
return try AudioSystemObject.instance.getProperty(PropertyAddress(kAudioHardwarePropertyTransportManagerList), elementType: AudioObjectID.self).map { AudioObject.make($0) as! AudioTransportManager }
}
/// Returns an initialized `AudioTransportManager` with `bundleID` or `nil` if unknown
/// - remark: This corresponds to the property `kAudioHardwarePropertyTranslateBundleIDToTransportManager` on `kAudioObjectSystemObject`
/// - parameter bundleID: The bundle ID of the desired transport manager
public class func makeTransportManager(forBundleID bundleID: String) throws -> AudioTransportManager? {
guard let objectID = try AudioSystemObject.instance.transportManagerID(forBundleID: bundleID) else {
return nil
}
return (AudioObject.make(objectID) as! AudioTransportManager)
}
// A textual representation of this instance, suitable for debugging.
public override var debugDescription: String {
do {
return "<\(type(of: self)): 0x\(String(objectID, radix: 16, uppercase: false)), [\(try endpointList().map({ $0.debugDescription }).joined(separator: ", "))]>"
}
catch {
return super.debugDescription
}
}
}
extension AudioTransportManager {
/// Creates and returns a new endpoint device
/// - remark: This corresponds to the property `kAudioTransportManagerCreateEndPointDevice`
/// - parameter composition: The composition of the new endpoint device
/// - note: The constants for `composition` are defined in `AudioHardware.h`
func createEndpointDevice(composition: [AnyHashable: Any]) throws -> AudioEndpointDevice {
var qualifier = composition as CFDictionary
return AudioObject.make(try getProperty(PropertyAddress(kAudioTransportManagerCreateEndPointDevice), type: AudioObjectID.self, qualifier: PropertyQualifier(&qualifier))) as! AudioEndpointDevice
}
/// Destroys an endpoint device
/// - remark: This corresponds to the property `kAudioTransportManagerDestroyEndPointDevice`
func destroyEndpointDevice(_ endpointDevice: AudioEndpointDevice) throws {
_ = try getProperty(PropertyAddress(kAudioTransportManagerDestroyEndPointDevice), type: UInt32.self, initialValue: endpointDevice.objectID)
}
/// Returns the audio endpoints provided by the transport manager
/// - remark: This corresponds to the property `kAudioTransportManagerPropertyEndPointList`
public func endpointList() throws -> [AudioEndpoint] {
return try getProperty(PropertyAddress(kAudioTransportManagerPropertyEndPointList), elementType: AudioObjectID.self).map { AudioObject.make($0) as! AudioEndpoint }
}
/// Returns the audio endpoint provided by the transport manager with the specified UID or `nil` if unknown
/// - remark: This corresponds to the property `kAudioTransportManagerPropertyTranslateUIDToEndPoint`
/// - parameter uid: The UID of the desired endpoint
public func endpoint(forUID uid: String) throws -> AudioEndpoint? {
var qualifierData = uid as CFString
let endpointObjectID = try getProperty(PropertyAddress(kAudioTransportManagerPropertyTranslateUIDToEndPoint), type: AudioObjectID.self, qualifier: PropertyQualifier(&qualifierData))
guard endpointObjectID != kAudioObjectUnknown else {
return nil
}
return (AudioObject.make(endpointObjectID) as! AudioEndpoint)
}
/// Returns the transport type
/// - remark: This corresponds to the property `kAudioTransportManagerPropertyTransportType`
public func transportType() throws -> AudioDevice.TransportType {
return AudioDevice.TransportType(rawValue: try getProperty(PropertyAddress(kAudioTransportManagerPropertyTransportType), type: UInt32.self))
}
}
extension AudioTransportManager {
/// Returns `true` if `self` has `selector`
/// - parameter selector: The selector of the desired property
public func hasSelector(_ selector: AudioObjectSelector<AudioTransportManager>) -> Bool {
return hasProperty(PropertyAddress(PropertySelector(selector.rawValue)))
}
/// Returns `true` if `selector` is settable
/// - parameter selector: The selector of the desired property
/// - throws: An error if `self` does not have the requested property
public func isSelectorSettable(_ selector: AudioObjectSelector<AudioTransportManager>) throws -> Bool {
return try isPropertySettable(PropertyAddress(PropertySelector(selector.rawValue)))
}
/// Registers `block` to be performed when `selector` changes
/// - parameter selector: The selector of the desired property
/// - parameter block: A closure to invoke when the property changes or `nil` to remove the previous value
/// - throws: An error if the property listener could not be registered
public func whenSelectorChanges(_ selector: AudioObjectSelector<AudioTransportManager>, perform block: PropertyChangeNotificationBlock?) throws {
try whenPropertyChanges(PropertyAddress(PropertySelector(selector.rawValue)), perform: block)
}
}
extension AudioObjectSelector where T == AudioTransportManager {
/// The property selector `kAudioTransportManagerCreateEndPointDevice`
// public static let createEndpointDevice = Selector(kAudioTransportManagerCreateEndPointDevice)
/// The property selector `kAudioTransportManagerDestroyEndPointDevice`
// public static let destroyEndpointDevice = Selector(kAudioTransportManagerDestroyEndPointDevice)
/// The property selector `kAudioTransportManagerPropertyEndPointList`
public static let endpointList = AudioObjectSelector(kAudioTransportManagerPropertyEndPointList)
/// The property selector `kAudioTransportManagerPropertyTranslateUIDToEndPoint`
public static let translateUIDToEndpoint = AudioObjectSelector(kAudioTransportManagerPropertyTranslateUIDToEndPoint)
/// The property selector `kAudioTransportManagerPropertyTransportType`
public static let transportType = AudioObjectSelector(kAudioTransportManagerPropertyTransportType)
}
| mit | 057aac87dd3f21c9fc4c53cf8c219e16 | 54.717949 | 200 | 0.799816 | 4.502072 | false | false | false | false |
salvonos/CityPicker | Pod/Classes/CityPickerClass.swift | 1 | 1315 | //
// CityPickerClass.swift
// Noemi Official
//
// Created by LIVECT LAB on 13/03/2016.
// Copyright © 2016 LIVECT LAB. All rights reserved.
//
import UIKit
class cityPickerClass {
class func getNations() -> (nations:[String], allValues:NSDictionary){
var nations = [String]()
var allValues = NSDictionary()
let podBundle = NSBundle(forClass: self)
if let path = podBundle.pathForResource("countriesToCities", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
do {
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let nationsArray = jsonResult.allKeys as! [String]
let sortedNations = nationsArray.sort { $0 < $1 }
nations = sortedNations
allValues = jsonResult
} catch {}
} catch {}
}
return (nations, allValues)
}
}
| mit | 4b3bc2f9c59ce3b1203d82104dfa1ca3 | 25.816327 | 169 | 0.520548 | 5.615385 | false | false | false | false |
spf-iOS/WebJSBridge | WebJSBridgeDemo/WebJSBridgeDemo/WebJSBridge.swift | 1 | 9102 | //
// WebJSBridge.swift
// TextJS
//
// Created by song on 2017/3/4.
// Copyright © 2017年 song. All rights reserved.
//
import UIKit
import JavaScriptCore
/*! 回调数据 */
typealias WebJSResponseCallback = (_ responseData:Any?) -> ()
/*! js回调App的block */
typealias WebJBHandler = ( _ data:Any?, _ responseCallback:WebJSResponseCallback) -> ()
/*! webView与JS的初始化回调 */
typealias WebJSInitHandler = ( _ success:Bool, _ error:String) -> ()
/*
* WebJSBridge
*
/// 初始化桥接功能
*init(_ webView:UIWebView,_ jsKey:String,webViewDelegate:UIWebViewDelegate?,handler:WebJSInitHandler?)
*
*
/// js调用App回调
*func registerHandler(handlerName:String,webJBHandler: @escaping WebJBHandler)
*
*
/// 移除回调监听
*func removeHandler(handlerName:String)
*
*
/// 移除所有的监听
*func reset()
*
*
/// App调用js中方法
*func callHandler(handlerName:String,data:Any?,responseCallback:WebJSResponseCallback?)
*
*/
@objc class WebJSBridge: NSObject,WebJSDelegate {
fileprivate var appHandler: WebJSDelegate.JSHandler!
fileprivate var webView:UIWebView
fileprivate var jsContext:JSContext
fileprivate var jsModelDict:[String:WebJSModel] = [String:WebJSModel]()
fileprivate weak var webViewDelegate:UIWebViewDelegate?
fileprivate var isFinishLoad = false
fileprivate var cacheCallDict:[String:Any?] = [String:Any?]()
/// 初始化桥接功能
///
/// - Parameters:
/// - webView: 需要加载的webView
/// - jsKey: h5中调用iOS方法的对象
/// - webViewDelegate: webView.delegate所在的VC
/// - handler: 是否桥接成功的回调
init(_ webView:UIWebView,_ jsKey:String,webViewDelegate:UIWebViewDelegate?,handler:WebJSInitHandler?) {
self.webView = webView
self.webViewDelegate = webViewDelegate
if let context = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext {
jsContext = context
}
else
{
print("无法获取webView的JSContext")
jsContext = JSContext()
if let `handler` = handler {
handler(false,"无法获取webView的JSContext,请检查webView")
}
super.init()
return
}
super.init()
jsContext.setObject(self, forKeyedSubscript: jsKey as (NSCopying & NSObjectProtocol)?)
if let `handler` = handler {
handler(true,"JS与iOS桥接成功")
}
initRegisterHandler()
webView.delegate = self
}
/// js调用App回调
///
/// - Parameters:
/// - handlerName: 双方约定的Key
/// - webJBHandler: 里面的data:给App的数据,responseCallback:App给js的响应结果
func registerHandler(handlerName:String,webJBHandler: @escaping WebJBHandler){
let model = WebJSModel()
model.handlerName = handlerName
model.isCall = false
model.webJBHandler = webJBHandler
let responseCallback:WebJSResponseCallback = {
[weak self] (responseData) in
guard let `self` = self else { return }
if let callName = model.callName, let jsParamsFunc = self.jsContext.objectForKeyedSubscript(callName) {
var arr = [Any]()
if let data = responseData {
arr.append(data)
}
jsParamsFunc.call(withArguments: arr)
}
}
model.responseCallback = responseCallback
jsModelDict[handlerName] = model
}
/// 移除回调监听
///
/// - Parameter handlerName: 双方约定的Key
func removeHandler(handlerName:String){
jsModelDict.removeValue(forKey: handlerName)
}
/// 移除所有的监听
func reset(){
jsModelDict.removeAll()
}
/// App调用js中方法
///
/// - Parameters:
/// - handlerName: handlerName: 双方约定的Key
/// - data: 给js的数据
/// - responseCallback: js给App的响应结果
func callHandler(handlerName:String,data:Any?,responseCallback:WebJSResponseCallback?){
if let _ = responseCallback {
let model = WebJSModel()
model.handlerName = handlerName
model.isCall = true
model.responseCallback = responseCallback
jsModelDict[handlerName] = model
}
if isFinishLoad {
if let jsParamsFunc = jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let callData = data {
arr.append(callData)
}
jsParamsFunc.call(withArguments: arr)
}
}
else
{
cacheCallDict[handlerName] = data
}
}
/*! 真实js回调APP的地方 */
private func initRegisterHandler(){
appHandler = {
[weak self] (handlerName,data,callBack) in
guard let `self` = self else { return }
if let jsModle = self.jsModelDict[handlerName] {
//监听js调App isCall一定等于false
if let webJBHandler = jsModle.webJBHandler{
jsModle.callName = callBack
if let responseCallback = jsModle.responseCallback {
webJBHandler(data,responseCallback)
}
else
{
let responseCallback:WebJSResponseCallback = {
[weak self] (responseData) in
guard let `self` = self else { return }
if let jsParamsFunc = self.jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let data = responseData {
arr.append(data)
}
jsParamsFunc.call(withArguments: arr)
}
}
webJBHandler(data,responseCallback)
}
}
else if let responseCallback = jsModle.responseCallback { //isCall一定等于true
responseCallback(data)
// self.jsModelDict.removeValue(forKey: handlerName)
}
//这里有两种情况会销毁js给App的响应结果 1,call js后 js给App的响应结果 2.call js后 js没有给App响应结果 接下来有了 call App的动作
for (handlerName, jsModel) in self.jsModelDict {
if jsModel.isCall {
self.jsModelDict.removeValue(forKey: handlerName)
}
}
}
}
}
/*! h5加载成功后才能Call到js */
fileprivate func callCache(){
cacheCallDict.forEach {
[weak self](handlerName, data) in
guard let `self` = self else { return }
if let jsParamsFunc = self.jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let callData = data {
arr.append(callData)
}
jsParamsFunc.call(withArguments: arr)
}
}
cacheCallDict.removeAll()
}
}
/*! 这里是为了使用webViewDidFinishLoad 但必须将其回调到所在的VC中 */
extension WebJSBridge:UIWebViewDelegate{
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
if let boo = webViewDelegate?.webView?(webView, shouldStartLoadWith: request, navigationType: navigationType) {
return boo
}
return true
}
func webViewDidStartLoad(_ webView: UIWebView){
isFinishLoad = false
webViewDelegate?.webViewDidStartLoad?(webView)
}
func webViewDidFinishLoad(_ webView: UIWebView) {
isFinishLoad = true
callCache()
webViewDelegate?.webViewDidFinishLoad?(webView)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
webViewDelegate?.webView?(webView, didFailLoadWithError: error)
}
}
/*
*
* 增加属性为了H5中调用
*/
@objc fileprivate protocol WebJSDelegate: JSExport {
/*! js与APP的实际参数 */
typealias JSHandler = (_ handlerName:String,_ data:Any?,_ callBack:String?) -> ()
/*! h5中统一调用该属性*/
var appHandler:JSHandler! { get set }
}
/*
*
* 该对象主要处理WebJSDelegate中registerHandler和方法的对接
*/
fileprivate class WebJSModel: NSObject {
var handlerName:String = ""
var isCall = false //true:App调用js false:js调用APP
var webJBHandler:WebJBHandler?
var responseCallback:WebJSResponseCallback?
var callName:String?
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | d2024947dc2f66d665b31de91f5b1959 | 31.093985 | 129 | 0.58018 | 4.847814 | false | false | false | false |
Bixelcog/StreamingAudio | Streaming Audio/ViewController.swift | 1 | 1120 | //
// ViewController.swift
// Streaming Audio
//
// Created by Ben Johnson on 3/17/15.
// Copyright (c) 2015 Bixelcog LLC. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerController: AVPlayerViewController? = nil
@IBOutlet weak var URLTextField: UITextField!
private struct StoryboardConstant {
static let playerSegue = "PlayerSegue"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == StoryboardConstant.playerSegue {
if let playerViewController = segue.destinationViewController as? AVPlayerViewController {
playerController = playerViewController
}
}
}
@IBAction func handlePlayButtonPressed(sender: UIButton) {
guard let text = URLTextField.text, URL = NSURL(string: text) else { return }
playerController?.player = AVPlayer(URL: URL)
playerController?.player?.play()
}
}
| mit | 02cf278b4c47d14d5d04277d7cc4a8e0 | 27 | 102 | 0.670536 | 5.090909 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/views/ColorPicker/BrightnessView.swift | 3 | 4778 | //
// BrightnessView.swift
// SwiftHSVColorPicker
//
// Created by johankasperi on 2015-08-20.
//
import UIKit
protocol BrightnessViewDelegate: class {
func brightnessSelected(_ brightness: CGFloat)
}
class BrightnessView: UIView {
weak var delegate: BrightnessViewDelegate?
var colorLayer: CAGradientLayer!
var point: CGPoint!
var indicator = CAShapeLayer()
var indicatorColor: CGColor = UIColor.lightGray.cgColor
var indicatorBorderWidth: CGFloat = 2.0
init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
// Init the point at the correct position
point = getPointFromColor(color)
// Clear the background
backgroundColor = UIColor.clear
// Create a gradient layer that goes from black to white
// Create a gradient layer that goes from black to white
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
colorLayer = CAGradientLayer()
colorLayer.colors = [
UIColor.black.cgColor,
UIColor(hue: hue, saturation: saturation, brightness: 1, alpha: 1).cgColor
]
colorLayer.locations = [0.0, 1.0]
colorLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
colorLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
colorLayer.frame = CGRect(x: 0, y: 2, width: self.frame.size.width, height: 24)
// Insert the colorLayer into this views layer as a sublayer
self.layer.insertSublayer(colorLayer, below: layer)
// Add the indicator
indicator.strokeColor = indicatorColor
indicator.fillColor = indicatorColor
indicator.lineWidth = indicatorBorderWidth
self.layer.addSublayer(indicator)
drawIndicator()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touchHandler(touches)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touchHandler(touches)
}
func touchHandler(_ touches: Set<UITouch>) {
// Set reference to the location of the touchesMoved in member point
if let touch = touches.first {
point = touch.location(in: self)
}
point.y = self.frame.height/2
point.x = getXCoordinate(point.x)
// Notify delegate of the new brightness
delegate?.brightnessSelected(getBrightnessFromPoint())
drawIndicator()
}
func getXCoordinate(_ coord: CGFloat) -> CGFloat {
// Offset the x coordinate to fit the view
if (coord < 1) {
return 1
}
if (coord > frame.size.width - 1 ) {
return frame.size.width - 1
}
return coord
}
func drawIndicator() {
// Draw the indicator
if (point != nil) {
indicator.path = UIBezierPath(roundedRect: CGRect(x: point.x-3, y: 0, width: 6, height: 28), cornerRadius: 3).cgPath
}
}
func getBrightnessFromPoint() -> CGFloat {
// Get the brightness value for a given point
return point.x/self.frame.width
}
func getPointFromColor(_ color: UIColor) -> CGPoint {
// Update the indicator position for a given color
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
return CGPoint(x: brightness * frame.width, y: frame.height / 2)
}
func setViewColor(_ color: UIColor!) {
// Update the Gradient Layer with a given color
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
colorLayer.colors = [
UIColor.black.cgColor,
UIColor(hue: hue, saturation: saturation, brightness: 1, alpha: 1).cgColor
]
}
}
| mit | bf3d5ccf3cdb8c45597526321403eb3c | 34.656716 | 128 | 0.615739 | 4.503299 | false | false | false | false |
DianQK/Flix | Flix/Builder/AnimatableTableViewBuilder.swift | 1 | 4455 | //
// AnimatableTableViewBuilder.swift
// Flix
//
// Created by DianQK on 04/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
public class AnimatableTableViewBuilder: _TableViewBuilder, PerformGroupUpdatesable {
typealias AnimatableSectionModel = RxDataSources.AnimatableSectionModel<IdentifiableSectionNode, IdentifiableNode>
let disposeBag = DisposeBag()
let delegateProxy = TableViewDelegateProxy()
public let sectionProviders: BehaviorRelay<[AnimatableTableViewSectionProvider]>
var nodeProviders: [String: _TableViewMultiNodeProvider] = [:] {
didSet {
nodeProviders.forEach { (_, provider) in
provider._register(tableView)
}
}
}
var footerSectionProviders: [String: _SectionPartionTableViewProvider] = [:] {
didSet {
footerSectionProviders.forEach { (_, provider) in
provider.register(tableView)
}
}
}
var headerSectionProviders: [String: _SectionPartionTableViewProvider] = [:] {
didSet {
headerSectionProviders.forEach { (_, provider) in
provider.register(tableView)
}
}
}
weak var _tableView: UITableView?
var tableView: UITableView {
return _tableView!
}
public var decideViewTransition: (([ChangesetInfo]) -> ViewTransition)?
public init(tableView: UITableView, sectionProviders: [AnimatableTableViewSectionProvider]) {
self._tableView = tableView
self.sectionProviders = BehaviorRelay(value: sectionProviders)
let dataSource = RxTableViewSectionedAnimatedDataSource<AnimatableSectionModel>(configureCell: { [weak self] dataSource, tableView, indexPath, node in
guard let provider = self?.nodeProviders[node.providerIdentity] else { return UITableViewCell() }
return provider._configureCell(tableView, indexPath: indexPath, node: node)
})
dataSource.decideViewTransition = { [weak self] (_, _, changesets) -> ViewTransition in
return self?.decideViewTransition?(changesets) ?? ViewTransition.animated
}
dataSource.animationConfiguration = AnimationConfiguration(
insertAnimation: .fade,
reloadAnimation: .none,
deleteAnimation: .fade
)
self.build(dataSource: dataSource)
self.sectionProviders.asObservable()
.do(onNext: { [weak self] (sectionProviders) in
self?.nodeProviders = Dictionary(
uniqueKeysWithValues: sectionProviders
.flatMap { $0.animatableProviders.flatMap { $0.__providers.map { (key: $0._flix_identity, value: $0) } }
})
self?.footerSectionProviders = Dictionary(
uniqueKeysWithValues: sectionProviders.lazy.compactMap { $0.animatableFooterProvider.map { (key: $0._flix_identity, value: $0) } })
self?.headerSectionProviders = Dictionary(
uniqueKeysWithValues: sectionProviders.lazy.compactMap { $0.animatableHeaderProvider.map { (key: $0._flix_identity, value: $0) } })
})
.flatMapLatest { (providers) -> Observable<[AnimatableSectionModel]> in
let sections: [Observable<(section: IdentifiableSectionNode, nodes: [IdentifiableNode])?>] = providers.map { $0.createSectionModel() }
return Observable.combineLatest(sections)
.ifEmpty(default: [])
.map { value -> [AnimatableSectionModel] in
return BuilderTool.combineSections(value)
}
}
.sendLatest(when: performGroupUpdatesBehaviorRelay)
.debounce(.seconds(0), scheduler: MainScheduler.instance)
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
public convenience init(tableView: UITableView, providers: [_AnimatableTableViewMultiNodeProvider]) {
let sectionProviderTableViewBuilder = AnimatableTableViewSectionProvider(
providers: providers,
headerProvider: nil,
footerProvider: nil
)
self.init(tableView: tableView, sectionProviders: [sectionProviderTableViewBuilder])
}
}
| mit | d5fcb0cd29402e296b9729708ff7a50e | 39.490909 | 158 | 0.635833 | 5.296076 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Regex/CustomComponents.swift | 1 | 1656 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
@available(SwiftStdlib 5.7, *)
/// A protocol allowing custom types to function as regex components by
/// providing the raw functionality backing `prefixMatch`.
public protocol CustomConsumingRegexComponent: RegexComponent {
/// Process the input string within the specified bounds, beginning at the given index, and return
/// the end position (upper bound) of the match and the produced output.
/// - Parameters:
/// - input: The string in which the match is performed.
/// - index: An index of `input` at which to begin matching.
/// - bounds: The bounds in `input` in which the match is performed.
/// - Returns: The upper bound where the match terminates and a matched instance, or `nil` if
/// there isn't a match.
func consuming(
_ input: String,
startingAt index: String.Index,
in bounds: Range<String.Index>
) throws -> (upperBound: String.Index, output: RegexOutput)?
}
@available(SwiftStdlib 5.7, *)
extension CustomConsumingRegexComponent {
public var regex: Regex<RegexOutput> {
let node: DSLTree.Node = .matcher(RegexOutput.self, { input, index, bounds in
try consuming(input, startingAt: index, in: bounds)
})
return Regex(node: node)
}
}
| apache-2.0 | ae3bee4998c72929654698ca61ff72fe | 41.461538 | 100 | 0.64372 | 4.475676 | false | false | false | false |
bmichotte/HSTracker | HSTracker/UIs/StatsManager/LadderTab.swift | 1 | 6763 | //
// LadderTab.swift
// HSTracker
//
// Created by Matthew Welborn on 6/25/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Cocoa
// TODO: Localization
class LadderTab: NSViewController {
@IBOutlet weak var gamesTable: NSTableView!
@IBOutlet weak var timeTable: NSTableView!
@IBOutlet weak var rankPicker: NSPopUpButton!
@IBOutlet weak var starsPicker: NSPopUpButton!
@IBOutlet weak var streakButton: NSButton!
var ladderTableItems = [LadderTableRow]()
// TODO: latest data point
var deck: Deck?
override func viewDidLoad() {
super.viewDidLoad()
// swiftlint:disable line_length
gamesTable.tableColumns[2].headerToolTip = NSLocalizedString("It is 90% certain that the true winrate falls between these values.", comment: "")
timeTable.tableColumns[2].headerToolTip = NSLocalizedString("It is 90% certain that the true winrate falls between these values.", comment: "")
// swiftlint:enable line_length
for rank in (0...25).reversed() {
var title: String
if rank == 0 {
title = "Legend"
} else {
title = String(rank)
}
rankPicker.addItem(withTitle: title)
}
for stars in 0...5 {
starsPicker.addItem(withTitle: String(stars))
}
starsPicker.selectItem(at: 1)
starsPicker.autoenablesItems = false
guessRankAndUpdate()
gamesTable.delegate = self
timeTable.delegate = self
gamesTable.dataSource = self
timeTable.dataSource = self
DispatchQueue.main.async {
self.gamesTable.reloadData()
self.timeTable.reloadData()
}
NotificationCenter.default
.addObserver(self,
selector: #selector(guessRankAndUpdate),
name: NSNotification.Name(rawValue: "reload_decks"),
object: nil)
}
func guessRankAndUpdate() {
if !self.isViewLoaded {
return
}
if let deck = self.deck {
let rank = StatsHelper.guessRank(deck: deck)
rankPicker.selectItem(at: 25 - rank)
}
update()
}
@IBAction func rankChanged(_ sender: AnyObject) {
update()
}
@IBAction func starsChanged(_ sender: AnyObject) {
update()
}
@IBAction func streakChanged(_ sender: AnyObject) {
update()
}
func enableStars(rank: Int) {
for i in 0...5 {
starsPicker.item(at: i)!.isEnabled = false
}
for i in 0...Ranks.starsPerRank[rank]! {
starsPicker.item(at: i)!.isEnabled = true
}
if starsPicker.selectedItem?.isEnabled == false {
starsPicker.selectItem(at: Ranks.starsPerRank[rank]!)
}
streakButton.isEnabled = true
if rank <= 5 {
streakButton.isEnabled = false
streakButton.state = NSOffState
}
}
func update() {
if let selectedRank = rankPicker.selectedItem,
let selectedStars = starsPicker.selectedItem {
var rank: Int
if selectedRank.title == "Legend" {
rank = 0
} else {
rank = Int(selectedRank.title)!
}
enableStars(rank: rank)
let stars = Int(selectedStars.title)!
if let deck = self.deck {
let streak = (streakButton.state == NSOnState)
DispatchQueue.main.async {
self.ladderTableItems = StatsHelper.getLadderTableData(deck: deck,
rank: rank,
stars: stars,
streak: streak)
self.gamesTable.reloadData()
self.timeTable.reloadData()
}
} else {
DispatchQueue.main.async {
self.ladderTableItems = []
self.gamesTable.reloadData()
self.timeTable.reloadData()
}
}
}
}
}
extension LadderTab : NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
if [gamesTable, timeTable].contains(tableView) {
return ladderTableItems.count
} else {
return 0
}
}
}
extension LadderTab : NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?,
row: Int) -> NSView? {
var text: String = ""
var cellIdentifier: String = ""
var alignment: NSTextAlignment = NSTextAlignment.left
let item = ladderTableItems[row]
if tableView == gamesTable {
if tableColumn == gamesTable.tableColumns[0] {
text = item.rank
alignment = NSTextAlignment.left
cellIdentifier = "LadderGRankCellID"
} else if tableColumn == gamesTable.tableColumns[1] {
text = item.games
alignment = NSTextAlignment.right
cellIdentifier = "LadderGToRankCellID"
} else if tableColumn == gamesTable.tableColumns[2] {
text = item.gamesCI
alignment = NSTextAlignment.right
cellIdentifier = "LadderG90CICellID"
}
} else if tableView == timeTable {
if tableColumn == timeTable.tableColumns[0] {
text = item.rank
alignment = NSTextAlignment.left
cellIdentifier = "LadderTRankCellID"
} else if tableColumn == timeTable.tableColumns[1] {
text = item.time
alignment = NSTextAlignment.right
cellIdentifier = "LadderTToRankCellID"
} else if tableColumn == timeTable.tableColumns[2] {
text = item.timeCI
alignment = NSTextAlignment.right
cellIdentifier = "LadderT90CICellID"
}
} else {
return nil
}
if let cell = tableView.make(withIdentifier: cellIdentifier, owner: nil)
as? NSTableCellView {
cell.textField?.stringValue = text
cell.textField?.alignment = alignment
return cell
}
return nil
}
}
| mit | 25af7c1e232da3d0eea1c2dc4be12d56 | 31.509615 | 152 | 0.524401 | 5.316038 | false | false | false | false |
Sadmansamee/quran-ios | Quran/Crash.swift | 1 | 2582 | //
// Crash.swift
// Quran
//
// Created by Mohamed Afifi on 6/10/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
import Crashlytics
class CrashlyticsKeyBase {
static let QariId = CrashlyticsKey<Int>(key: "QariId")
static let QuranPage = CrashlyticsKey<Int>(key: "QuranPage")
static let PlayingAyah = CrashlyticsKey<AyahNumber>(key: "PlayingAyah")
static let DownloadingQuran = CrashlyticsKey<Bool>(key: "DownloadingQuran")
}
final class CrashlyticsKey<Type>: CrashlyticsKeyBase {
let key: String
fileprivate init(key: String) {
self.key = key
}
}
struct Crash {
static func setValue<T>(_ value: T?, forKey key: CrashlyticsKey<T>) {
let instance = Crashlytics.sharedInstance()
guard let value = value else {
instance.setObjectValue(nil, forKey: key.key)
return
}
if let value = value as? Int32 {
instance.setIntValue(value, forKey: key.key)
} else if let value = value as? Int {
instance.setIntValue(Int32(value), forKey: key.key)
} else if let value = value as? Float {
instance.setFloatValue(value, forKey: key.key)
} else if let value = value as? Bool {
instance.setBoolValue(value, forKey: key.key)
} else if let value = value as? CustomStringConvertible {
instance.setObjectValue(value.description, forKey: key.key)
} else {
fatalError("Unsupported value type: \(value)")
}
}
static func recordError(_ error: Error, reason: String, fatalErrorOnDebug: Bool = true) {
Crashlytics.sharedInstance().recordError(error as NSError, withAdditionalUserInfo: ["quran.reason": reason])
#if DEBUG
if fatalErrorOnDebug {
fatalError("\(reason). Error: \(error)")
}
#endif
}
}
func CLog(_ string: String) {
NSLog(string)
CLSLogv("%@", getVaList([string]))
}
public func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Never {
CLog("message: \(message()), file:\(file.description), line:\(line)")
Swift.fatalError(message, file: file, line: line)
}
public func fatalError(_ message: @autoclosure () -> String = "", _ error: Error, file: StaticString = #file, line: UInt = #line) -> Never {
let fullMessage = "\(message()), error: \(error)"
CLog("message: \(fullMessage), file:\(file.description), line:\(line)")
Swift.fatalError(fullMessage, file: file, line: line)
}
| mit | 54825361d2d1dab84b7bd6dd6d8cd219 | 32.089744 | 140 | 0.629213 | 4.090333 | false | false | false | false |
globelabs/globe-connect-swift | Sources/Subscriber.swift | 1 | 2453 | import Foundation
public struct Subscriber {
let accessToken: String
public typealias SuccessHandler = (JSON) -> Void
public typealias ErrorHandler = (_ error: Error) -> Void
public init(accessToken: String) {
self.accessToken = accessToken
}
public func getSubscriberBalance(
address: String,
success: SuccessHandler? = nil,
failure: ErrorHandler? = nil
) -> Void {
// set the url
let url = "https://devapi.globelabs.com.ph/location/v1/queries/balance?access_token=\(self.accessToken)&address=\(address)"
// set the header
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
// send the request
Request().get(
url: url,
headers: headers,
callback: { data, _, _ in
DispatchQueue.global(qos: .utility).async {
do {
let jsonResult = try JSON.parse(jsonData: data!)
DispatchQueue.main.async {
success?(jsonResult)
}
} catch {
DispatchQueue.main.async {
failure?(error)
}
}
}
}
)
}
public func getSubscriberReloadAmount(
address: String,
success: SuccessHandler? = nil,
failure: ErrorHandler? = nil
) -> Void {
// set the url
let url = "https://devapi.globelabs.com.ph/location/v1/queries/reload_amount?access_token=\(self.accessToken)&address=\(address)"
// set the header
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
// send the request
Request().get(
url: url,
headers: headers,
callback: { data, _, _ in
DispatchQueue.global(qos: .utility).async {
do {
let jsonResult = try JSON.parse(jsonData: data!)
DispatchQueue.main.async {
success?(jsonResult)
}
} catch {
DispatchQueue.main.async {
failure?(error)
}
}
}
}
)
}
}
| mit | 0f7a4b5b019e2763b03066af80a593b1 | 29.6625 | 137 | 0.460253 | 5.241453 | false | false | false | false |
arvedviehweger/swift | stdlib/public/core/LifetimeManager.swift | 1 | 6840 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended.
/// - Returns: The return value of `body`, if any.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended.
/// - Returns: The return value of `body`, if any.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// The `withCString(_:)` method ensures that the sequence's lifetime extends
/// through the execution of `body`. The pointer argument to `body` is only
/// valid for the lifetime of the closure. Do not escape it from the closure
/// for later use.
///
/// - Parameter body: A closure that takes a pointer to the string's UTF-8
/// code unit sequence as its sole argument. If the closure has a return
/// value, it is used as the return value of the `withCString(_:)` method.
/// The pointer argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value of the `body` closure, if any.
@_inlineable
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Invokes the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, it is used as the return
/// value of the `withUnsafeMutablePointer(to:_:)` function. The pointer
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
@_inlineable
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, it is used as the return value of the
/// `withUnsafePointer(to:_:)` function. The pointer argument is valid
/// only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
@_inlineable
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
| apache-2.0 | e83adf443f5148811ffb9fc5051a6af7 | 34.076923 | 88 | 0.677778 | 4.090909 | false | false | false | false |
AKIRA-MIYAKE/EasyBeacon | EasyBeacon/Entities/BeaconRegion.swift | 1 | 2236 | //
// BeaconRegion.swift
// EasyBeacon
//
// Created by MiyakeAkira on 2015/05/30.
// Copyright (c) 2015年 Miyake Akira. All rights reserved.
//
import Foundation
import CoreLocation
public struct BeaconRegion: Hashable {
// MARK: - let
public let identifier: String
public let proximityUUID: NSUUID
public let major: Int?
public let minor: Int?
public let region: CLBeaconRegion
// MARK: - Initialzie
public init(identifier: String, proximityUUID: NSUUID) {
self.identifier = identifier
self.proximityUUID = proximityUUID
major = nil
minor = nil
region = CLBeaconRegion(proximityUUID: proximityUUID, identifier: identifier)
}
public init(identifier: String, proximityUUID: NSUUID, major: Int) {
self.identifier = identifier
self.proximityUUID = proximityUUID
self.major = major
minor = nil
region = CLBeaconRegion(proximityUUID: proximityUUID, major: UInt16(major), identifier: identifier)
}
public init(identifier: String, proximityUUID: NSUUID, major: Int, minor: Int) {
self.identifier = identifier
self.proximityUUID = proximityUUID
self.major = major
self.minor = minor
region = CLBeaconRegion(
proximityUUID: proximityUUID,
major: UInt16(major),
minor: UInt16(minor),
identifier: identifier)
}
public init(region: CLBeaconRegion) {
self.region = region
identifier = region.identifier
proximityUUID = region.proximityUUID
if let majorValue = region.major {
major = majorValue.integerValue
} else {
major = nil
}
if let minorValue = region.minor {
minor = minorValue.integerValue
} else {
minor = nil
}
}
// MARK: - Hashable
public var hashValue: Int {
return identifier.hashValue - proximityUUID.hashValue
}
}
public func ==(lhs: BeaconRegion, rhs: BeaconRegion) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | baff78b8fb813f36fe146ba0ea04d76d | 24.101124 | 107 | 0.592659 | 5.171296 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardIssuing/Sources/FeatureCardIssuingUI/Manage/CardManagementView.swift | 1 | 11531 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import ComposableArchitecture
import FeatureCardIssuingDomain
import Localization
import MoneyKit
import SceneKit
import SwiftUI
import ToolKit
import WebKit
struct CardManagementView: View {
@State private var isHelperReady: Bool = false
private typealias L10n = LocalizationConstants.CardIssuing.Manage
private let store: Store<CardManagementState, CardManagementAction>
init(store: Store<CardManagementState, CardManagementAction>) {
self.store = store
}
var body: some View {
WithViewStore(store.scope(state: \.error)) { viewStore in
switch viewStore.state {
case .some(let error):
ErrorView(
error: error,
cancelAction: {
viewStore.send(.close)
}
)
default:
content
}
}
}
@ViewBuilder var content: some View {
// swiftlint:disable closure_body_length
WithViewStore(store) { viewStore in
ScrollView {
LazyVStack {
HStack {
Text(L10n.title)
.typography(.body2)
Spacer()
SmallMinimalButton(
title: L10n.Button.manage,
action: {
viewStore.send(.showManagementDetails)
}
)
}
.padding(Spacing.padding2)
card
VStack {
AccountRow(account: viewStore.state.linkedAccount) {
viewStore.send(.showSelectLinkedAccountFlow)
}
PrimaryDivider()
HStack {
PrimaryButton(
title: L10n.Button.addFunds,
action: {
viewStore.send(CardManagementAction.openBuyFlow)
}
)
MinimalButton(
title: L10n.Button.changeSource,
action: {
viewStore.send(.showSelectLinkedAccountFlow)
}
)
}
.padding(Spacing.padding2)
}
.overlay(
RoundedRectangle(cornerRadius: Spacing.padding1)
.stroke(Color.semantic.light, lineWidth: 1)
)
.padding(Spacing.padding2)
VStack {
HStack {
Text(L10n.RecentTransactions.title)
.typography(.body2)
Spacer()
SmallMinimalButton(title: L10n.Button.seeAll) {
viewStore.send(
.binding(
.set(
\.$isTransactionListPresented,
true
)
)
)
}
}
.padding(.horizontal, Spacing.padding2)
VStack(spacing: 0) {
PrimaryDivider()
ForEach(viewStore.state.recentTransactions.value?.prefix(3) ?? []) { transaction in
ActivityRow(transaction) {
viewStore.send(.showTransaction(transaction))
}
PrimaryDivider()
}
transactionPlaceholder
}
}
Text(L10n.disclaimer)
.typography(.caption1.regular())
.multilineTextAlignment(.center)
.padding(Spacing.padding4)
.foregroundColor(.semantic.muted)
}
.listStyle(PlainListStyle())
.background(Color.semantic.background.ignoresSafeArea())
}
.onAppear { viewStore.send(.onAppear) }
.onDisappear { viewStore.send(.onDisappear) }
.navigationTitle(
LocalizationConstants
.CardIssuing
.Navigation
.title
)
.bottomSheet(
isPresented: viewStore.binding(\.$isTopUpPresented),
content: { topUpSheet }
)
.sheet(
isPresented: viewStore.binding(\.$isDetailScreenVisible),
content: { CardManagementDetailsView(store: store) }
)
.bottomSheet(
isPresented: viewStore.binding(
get: {
$0.displayedTransaction != nil
},
send: CardManagementAction.setTransactionDetailsVisible
),
content: {
ActivityDetailsView(store: store.scope(state: \.displayedTransaction))
}
)
PrimaryNavigationLink(
destination: ActivityListView(store: store),
isActive: viewStore.binding(\.$isTransactionListPresented),
label: EmptyView.init
)
}
}
@ViewBuilder var card: some View {
ZStack(alignment: .center) {
if !isHelperReady {
ProgressView(value: 0.25)
.progressViewStyle(.indeterminate)
.frame(width: 52, height: 52)
}
IfLetStore(
store.scope(state: \.cardHelperUrl),
then: { store in
WithViewStore(store) { viewStore in
WebView(
url: viewStore.state,
loading: $isHelperReady
)
.frame(width: 300, height: 355)
}
},
else: {
EmptyView()
}
)
}
.frame(height: 355)
}
@ViewBuilder var transactionPlaceholder: some View {
WithViewStore(store) { viewStore in
if !viewStore.state.recentTransactions.isLoading,
viewStore.state.recentTransactions.value?.isEmpty ?? true
{
VStack(alignment: .center, spacing: Spacing.padding1) {
Image("empty-tx-graphic", bundle: .cardIssuing)
Text(L10n.RecentTransactions.Placeholder.title)
.typography(.title3)
.foregroundColor(.semantic.title)
Text(L10n.RecentTransactions.Placeholder.message)
.multilineTextAlignment(.center)
.typography(.body1)
.foregroundColor(.semantic.body)
}
.padding(Spacing.padding2)
} else {
EmptyView()
}
}
}
@ViewBuilder var topUpSheet: some View {
WithViewStore(store.stateless) { viewStore in
VStack {
PrimaryDivider().padding(.top, Spacing.padding2)
PrimaryRow(
title: L10n.TopUp.AddFunds.title,
subtitle: L10n.TopUp.AddFunds.caption,
leading: {
Icon.plus
.accentColor(.semantic.primary)
.frame(maxHeight: 24.pt)
},
action: {
viewStore.send(.openBuyFlow)
}
)
PrimaryDivider()
PrimaryRow(
title: L10n.TopUp.Swap.title,
subtitle: L10n.TopUp.Swap.caption,
leading: {
Icon.plus
.accentColor(.semantic.primary)
.frame(maxHeight: 24.pt)
},
action: {
viewStore.send(.openSwapFlow)
}
)
}
}
}
}
struct AccountRow: View {
let account: AccountSnapshot?
let action: () -> Void
private typealias L10n = LocalizationConstants.CardIssuing.Manage
init(account: AccountSnapshot?, action: @escaping () -> Void) {
self.account = account
self.action = action
}
var body: some View {
if let account = account {
BalanceRow(
leadingTitle: account.name,
leadingDescription: account.leadingDescription,
trailingTitle: account.fiat.displayString,
trailingDescription: account.trailingDescription,
trailingDescriptionColor: .semantic.muted,
action: action,
leading: {
ZStack {
RoundedRectangle(cornerRadius: account.cornerRadius)
.frame(width: 24, height: 24)
.foregroundColor(account.backgroundColor)
account.image
.resizable()
.frame(width: account.iconWidth, height: account.iconWidth)
}
}
)
} else {
PrimaryRow(
title: L10n.Button.ChoosePaymentMethod.title,
subtitle: L10n.Button.ChoosePaymentMethod.caption,
leading: {
Icon.questionCircle
.frame(width: 24)
.accentColor(
.semantic.muted
)
},
trailing: { chevronRight },
action: action
)
}
}
@ViewBuilder var chevronRight: some View {
Icon.chevronRight
.frame(width: 18, height: 18)
.accentColor(
.semantic.muted
)
.flipsForRightToLeftLayoutDirection(true)
}
}
#if DEBUG
struct CardManagement_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
CardManagementView(
store: Store(
initialState: .init(),
reducer: cardManagementReducer,
environment: .preview
)
)
}
}
}
#endif
extension AccountSnapshot {
fileprivate var leadingDescription: String {
cryptoCurrency?.name ?? LocalizationConstants.CardIssuing.Manage.SourceAccount.cashBalance
}
fileprivate var trailingDescription: String {
cryptoCurrency == nil ? crypto.displayCode : crypto.displayString
}
}
| lgpl-3.0 | 809deb44249513cbac22b0150b1ea20c | 34.807453 | 111 | 0.437554 | 6.239177 | false | false | false | false |
miDrive/MDAlert | Example/MDAlert/ViewController.swift | 1 | 1731 | //
// ViewController.swift
// MDAlert
//
// Created by Chris Byatt on 05/15/2017.
// Copyright (c) 2017 Chris Byatt. All rights reserved.
//
import UIKit
import MDAlert
class ViewController: UIViewController {
@IBAction func showAlert(_ sender: UIButton) {
// Alert with buttons
let alert = MDAlertController(title: "Wow", message: "It's an alert!", showsCancel: true)
alert.addAction(MDAlertAction(title: "OK", style: .default, action: nil))
alert.addAction(MDAlertAction(title: "OK", style: .destructive, action: nil))
alert.addAction(MDAlertAction(title: "OK", style: .cancel, action: nil))
alert.show()
// Alert no buttons
// let alert = MDAlertController(title: "Password reset Password reset Password reset Password reset Password reset Password reset Password reset Password reset ", message: "Your request has been recieved, please check your email for instructions on resetting your password.")
//
// alert.show()
// Alert custom view no buttons
// let view = UIView(frame: CGRect(x: 50, y: 50, width: 50, height: 130))
// view.backgroundColor = .black
//
// let alert = MDAlertController(title: "Wow", message: "This is an alert", customView: view, showsCancel: true)
//
// alert.show()
// Alert custom view with Buttons
// let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 130))
// view.backgroundColor = .black
//
// let alert = MDAlertController(title: "Wow", message: "This is an alert", customView: view, showsCancel: true)
// alert.addAction(MDAlertAction(title: "OK", style: .default, action: nil))
//
// alert.show()
}
}
| mit | d6ad335f88b9a85c4e7338af94387281 | 35.0625 | 283 | 0.647603 | 3.92517 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/ExplainedActionView/ExplainedActionView.swift | 1 | 4300 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxSwift
public final class ExplainedActionView: UIView {
// MARK: - Injected
public var viewModel: ExplainedActionViewModel! {
didSet {
guard let viewModel = viewModel else { return }
thumbBadgeImageView.viewModel = viewModel.thumbBadgeImageViewModel
titleLabel.content = viewModel.titleLabelContent
contentStackView.removeSubviews()
button.rx.tap
.bindAndCatch(to: viewModel.tapRelay)
.disposed(by: disposeBag)
let descriptionLabels: [UILabel] = viewModel.descriptionLabelContents
.map { content in
let label = UILabel()
label.verticalContentHuggingPriority = .required
label.verticalContentCompressionResistancePriority = .required
label.numberOfLines = 0
label.content = content
return label
}
for label in descriptionLabels {
contentStackView.addArrangedSubview(label)
}
if let badgeViewModel = viewModel.badgeViewModel {
badgeView = BadgeView()
badgeView.viewModel = badgeViewModel
contentStackView.addArrangedSubview(badgeView)
} else if let badgeView = badgeView {
contentStackView.removeArrangedSubview(badgeView)
self.badgeView = nil
}
}
}
// MARK: - UI Properties
private let thumbBadgeImageView = BadgeImageView()
private let titleLabel = UILabel()
private let contentStackView = UIStackView()
private var badgeView: BadgeView!
private let disclosureImageView = UIImageView()
private let button = UIButton()
private var extendedLayoutConstraints: [NSLayoutConstraint] = []
private var narrowedLayoutConstraints: [NSLayoutConstraint] = []
private let disposeBag = DisposeBag()
// MARK: - Setup
override public init(frame: CGRect) {
super.init(frame: frame)
// Add subviews
addSubview(thumbBadgeImageView)
addSubview(titleLabel)
addSubview(contentStackView)
addSubview(disclosureImageView)
addSubview(button)
// Add constraints
button.fillSuperview()
button.addTargetForTouchDown(self, selector: #selector(touchDown))
button.addTargetForTouchUp(self, selector: #selector(touchUp))
disclosureImageView.layoutToSuperview(.trailing, offset: -24)
disclosureImageView.layout(to: .centerY, of: thumbBadgeImageView)
disclosureImageView.layout(size: .init(edge: 12))
thumbBadgeImageView.layoutToSuperview(.leading, offset: 24)
thumbBadgeImageView.layoutToSuperview(.top, offset: 24)
thumbBadgeImageView.layout(size: .init(edge: 32))
titleLabel.layout(to: .top, of: thumbBadgeImageView)
titleLabel.layout(edge: .leading, to: .trailing, of: thumbBadgeImageView, offset: 16)
titleLabel.layout(edge: .trailing, to: .leading, of: disclosureImageView, offset: -16)
titleLabel.verticalContentHuggingPriority = .penultimateHigh
contentStackView.layout(edge: .top, to: .bottom, of: titleLabel, offset: 8)
contentStackView.layout(to: .leading, of: titleLabel)
contentStackView.layout(to: .trailing, of: titleLabel)
contentStackView.layoutToSuperview(.bottom, offset: -24, priority: .penultimateHigh)
// Configure subviews
contentStackView.alignment = .leading
contentStackView.distribution = .fillProportionally
contentStackView.axis = .vertical
contentStackView.spacing = 8
disclosureImageView.contentMode = .scaleAspectFit
disclosureImageView.image = UIImage(named: "icon-disclosure-small", in: .module, compatibleWith: .none)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
private func touchDown() {
backgroundColor = .hightlightedBackground
}
@objc
private func touchUp() {
backgroundColor = .white
}
}
| lgpl-3.0 | 4bb67b23191bed59d3a818ab9ca51ee0 | 34.825 | 111 | 0.652012 | 5.407547 | false | false | false | false |
lockersoft/Winter2016-iOS | BMICalcLecture/ChartViewController.swift | 1 | 3234 | //
// ChartViewController.swift
// BMICalcLecture
//
// Created by Jones, Dave on 2/9/16.
// Copyright © 2016 Jones, Dave. All rights reserved.
//
import UIKit
import Charts
class ChartViewController: UIViewController {
@IBOutlet var barChartView: BarChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Read data from logfile
var xaxis : [String] = []
var yaxis : [Double] = []
let logFile = FileUtils(fileName: "bmilog.csv")
if( logFile.fileExists()){
let rawLogData = logFile.readFile()
let logEntries : Array = rawLogData.componentsSeparatedByString("\n")
// Convert the record into a date/time object
// compare with the startdate and enddate time object
// if between - use that record's string
// otherwise skip
for record : String in logEntries {
// record is a comma delimited string
if( record != "" ){
let entry : Array = record.componentsSeparatedByString(",")
xaxis.append( entry[2] )
var yvalue = 0.0
if let y = Double(entry[1]){
yvalue = y
}
yaxis.append( yvalue )
}
}
setChart( xaxis, values: yaxis )
}
/* X-AXIS
let months = [
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
]
Y-AXIS
let weightPoints = [
190.0, 188.0, 187.0, 185.0,
180.0, 179.0, 178.0, 175.0,
160.0, 170.0, 175.0, 200.0
]
*/
// setChart( months, values: weightPoints )
}
@IBAction func switchToLogger(sender: UIButton) {
self.performSegueWithIdentifier("fromChartToLogger", sender: self)
}
func setChart( xAxisLabels : [String], values: [Double] ){
barChartView.noDataText = "You must supply some weight data for the bar chart"
barChartView.noDataTextDescription = "Log some data in the weight logger"
var dataEntries : [BarChartDataEntry] = []
for i in 0..<xAxisLabels.count {
dataEntries.append( BarChartDataEntry( value: values[i], xIndex: i ) )
}
let chartDataSet = BarChartDataSet( yVals: dataEntries, label: "Weight" )
let chartData = BarChartData( xVals: xAxisLabels, dataSet: chartDataSet )
barChartView.data = chartData
}
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.
}
*/
}
| unlicense | a8399168ae30ac413f71fec74a2a34e2 | 30.696078 | 106 | 0.560161 | 4.712828 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/CompoundBezierPath.swift | 1 | 4444 | //
// CompoundBezierPath.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import Foundation
import CoreGraphics
/**
A collection of BezierPath objects that can be trimmed and added.
*/
struct CompoundBezierPath {
let paths: [BezierPath]
let length: CGFloat
init() {
paths = []
length = 0
}
init(path: BezierPath) {
self.paths = [path]
self.length = path.length
}
init(paths: [BezierPath], length: CGFloat) {
self.paths = paths
self.length = length
}
init(paths: [BezierPath]) {
self.paths = paths
var l: CGFloat = 0
for path in paths {
l = l + path.length
}
self.length = l
}
func addPath(path: BezierPath) -> CompoundBezierPath {
var newPaths = paths
newPaths.append(path)
return CompoundBezierPath(paths: newPaths, length: length + path.length)
}
func combine(_ compoundBezier: CompoundBezierPath) -> CompoundBezierPath {
var newPaths = paths
newPaths.append(contentsOf: compoundBezier.paths)
return CompoundBezierPath(paths: newPaths, length: length + compoundBezier.length)
}
func trim(fromPosition: CGFloat, toPosition: CGFloat, offset: CGFloat, trimSimultaneously: Bool) -> CompoundBezierPath {
if fromPosition == toPosition {
return CompoundBezierPath()
}
if trimSimultaneously {
/// Trim each path individually.
var newPaths = [BezierPath]()
for path in paths {
newPaths.append(contentsOf: path.trim(fromLength: fromPosition * path.length,
toLength: toPosition * path.length,
offsetLength: offset * path.length))
}
return CompoundBezierPath(paths: newPaths)
}
/// Normalize lengths to the curve length.
var startPosition = (fromPosition+offset).truncatingRemainder(dividingBy: 1)
var endPosition = (toPosition+offset).truncatingRemainder(dividingBy: 1)
if startPosition < 0 {
startPosition = 1 + startPosition
}
if endPosition < 0 {
endPosition = 1 + endPosition
}
if startPosition == 1 {
startPosition = 0
}
if endPosition == 0 {
endPosition = 1
}
if startPosition == 0 && endPosition == 1 ||
startPosition == endPosition ||
startPosition == 1 && endPosition == 0 {
/// The trim encompasses the entire path. Return.
return self
}
var positions: [(start: CGFloat, end: CGFloat)]
if endPosition < startPosition {
positions = [(start: 0, end: endPosition * length),
(start: startPosition * length, end: length)]
} else {
positions = [(start: startPosition * length, end: endPosition * length)]
}
var compoundPath = CompoundBezierPath()
var trim = positions.remove(at: 0)
var pathStartPosition: CGFloat = 0
var finishedTrimming: Bool = false
var i: Int = 0
while !finishedTrimming {
if paths.count <= i {
/// Rounding errors
finishedTrimming = true
continue
}
let path = paths[i]
let pathEndPosition = pathStartPosition + path.length
if pathEndPosition < trim.start {
/// Path is not included in the trim, continue.
pathStartPosition = pathEndPosition
i = i + 1
continue
} else if trim.start <= pathStartPosition, pathEndPosition <= trim.end {
/// Full Path is inside of trim. Add full path.
compoundPath = compoundPath.addPath(path: path)
} else {
if let trimPath = path.trim(fromLength: trim.start > pathStartPosition ? (trim.start - pathStartPosition) : 0,
toLength: trim.end < pathEndPosition ? (trim.end - pathStartPosition) : path.length,
offsetLength: 0).first {
compoundPath = compoundPath.addPath(path: trimPath)
}
}
if trim.end <= pathEndPosition {
/// We are done with the current trim.
/// Advance trim but remain on the same path in case the next trim overlaps it.
if positions.count > 0 {
trim = positions.remove(at: 0)
} else {
finishedTrimming = true
}
} else {
pathStartPosition = pathEndPosition
i = i + 1
}
}
return compoundPath
}
}
| mit | ad695d513d9f409221ea58bed442cadb | 27.126582 | 122 | 0.59811 | 4.677895 | false | false | false | false |
maximkhatskevich/MKHCocoaFontMaster | Src/iOS/CFMSegmentedControl.swift | 1 | 1442 | //
// CFMSegmentedControl.swift
// CocoaFontMaster-iOS
//
// Created by Maxim Khatskevich on 21/01/16.
// Copyright © 2016 Maxim Khatskevich. All rights reserved.
//
import UIKit
//===
extension UISegmentedControl: CFMUIControlBasic
{
// MARK: Public properties
public var cfm_actualFont: UIFont!
{
get
{
var result: UIFont
//===
if
let textAttributes = self.titleTextAttributesForState(.Normal),
let font = textAttributes[NSFontAttributeName] as? UIFont
{
result = font
}
else
{
result = cfm_defaultFont
}
//===
return result
}
set
{
var textAttributes = self.titleTextAttributesForState(.Normal)
if textAttributes == nil
{
textAttributes = [:]
}
textAttributes![NSFontAttributeName] = newValue
//===
setTitleTextAttributes(textAttributes, forState: .Normal)
}
}
}
//===
public class CFMMetaFontSegmentedControl: UISegmentedControl
{
@IBInspectable var metaFontId: String? = nil
{
didSet
{
cfm_updateFont(metaFontId)
}
}
} | mit | cffb380fa9054c90cd48e4b903e6bded | 19.898551 | 79 | 0.480916 | 5.718254 | false | false | false | false |
nohirap/ANActionSheet | ANActionSheet/Classes/ANActionSheet.swift | 1 | 6632 | //
// ANActionSheet.swift
// Pods
//
// Created by nohirap on 2016/06/05.
// Copyright © 2016 nohirap. All rights reserved.
//
import UIKit
final public class ANActionSheet: UIView {
private let sheetView = UIView()
private let borderLine: CGFloat = 1.0
private let cornerRadius: CGFloat = 6.0
private let animateDuration = 0.5
private var actions = [ANAction]()
private var sheetViewMoveY: CGFloat = 0.0
private var titleText = ""
private var messageText = ""
public var headerBackgroundColor = UIColor.defaultBackgroundColor()
public var titleColor = UIColor.defaultTextColor()
public var messageColor = UIColor.defaultTextColor()
public var buttonsBorderColor = UIColor.defaultButtonsBorderColor()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(title: String = "", message: String = "") {
super.init(frame: CGRectZero)
titleText = title
messageText = message
self.frame = UIScreen.mainScreen().bounds
self.backgroundColor = UIColor(white: 0, alpha: 0.25)
}
public func addAction(action: ANAction) {
action.output = self
actions.append(action)
}
public func show() {
if notExistDefaultButton() {
return
}
let viewTag = 1000
for subview in self.subviews {
subview.removeFromSuperview()
}
if let keyWindow = UIApplication.sharedApplication().keyWindow {
if keyWindow.viewWithTag(viewTag) == nil {
self.tag = viewTag
keyWindow.addSubview(self)
}
} else {
return
}
let headerView = ANHeaderView(model: setupHeaderViewModel())
if headerView.height > 0 {
sheetView.addSubview(headerView)
}
let frameHeight = createButtonsView(headerView.height)
sheetView.frame = CGRectMake(0, UIScreen.height(), UIScreen.buttonWidth(), headerView.height + frameHeight)
self.addSubview(sheetView)
UIView.animateWithDuration(animateDuration) {
self.sheetView.frame = CGRectOffset(self.sheetView.frame, 0, -self.sheetViewMoveY)
}
}
private func notExistDefaultButton() -> Bool {
return actions.filter{$0.style.isDefault}.count == 0
}
private func setupHeaderViewModel() -> ANHeaderViewModel {
var headerViewModel = ANHeaderViewModel()
headerViewModel.title = titleText
headerViewModel.message = messageText
headerViewModel.headerBackgroundColor = headerBackgroundColor
headerViewModel.titleColor = titleColor
headerViewModel.messageColor = messageColor
return headerViewModel
}
private func createButtonsView(headerHeight: CGFloat) -> CGFloat {
let defaultsView = UIView()
var cancelView: UIView?
var actionCount = 0
var firstAction: ANAction?
var lastAction: ANAction?
// Setting buttons
var buttonsY: CGFloat = 0.0
for action in actions {
if action.style == .Cancel {
if let _ = cancelView {
// Cancel button only one.
continue
}
action.setupFrame(0)
cancelView = UIView()
cancelView?.addSubview(action)
} else {
if actionCount > 6 {
// Default button rimit 7.
continue
}
if firstAction == nil {
firstAction = action
} else {
let border = UIView()
border.frame = CGRectMake(0, buttonsY, UIScreen.buttonWidth(), borderLine)
border.backgroundColor = buttonsBorderColor
defaultsView.addSubview(border)
buttonsY += borderLine
}
buttonsY += action.setupFrame(buttonsY)
defaultsView.addSubview(action)
lastAction = action
actionCount += 1
}
}
guard let openedFirstAction = firstAction, openedLastAction = lastAction else {
return 0
}
// Setting corners
if headerHeight == 0 {
if actionCount > 1 {
let maskPath = UIBezierPath(roundedRect: openedFirstAction.bounds, byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight], cornerRadii:CGSizeMake(cornerRadius, cornerRadius))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
openedFirstAction.layer.mask = maskLayer
} else {
openedLastAction.layer.cornerRadius = cornerRadius
openedLastAction.layer.masksToBounds = true
}
}
if headerHeight > 0 || actionCount > 1 {
let maskPath = UIBezierPath(roundedRect: openedLastAction.bounds, byRoundingCorners: [UIRectCorner.BottomLeft, UIRectCorner.BottomRight], cornerRadii:CGSizeMake(cornerRadius, cornerRadius))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
openedLastAction.layer.mask = maskLayer
}
// Setting views frame
var frameHeight = buttonsY
defaultsView.frame = CGRectMake(UIScreen.mergin(), headerHeight, UIScreen.buttonWidth(), frameHeight)
if let cancelView = cancelView {
cancelView.frame = CGRectMake(UIScreen.mergin(), headerHeight + frameHeight + UIScreen.mergin(), UIScreen.buttonWidth(), UIScreen.buttonHeight())
frameHeight += UIScreen.mergin() + UIScreen.buttonHeight()
}
sheetView.addSubview(defaultsView)
if let cancelView = cancelView {
sheetView.addSubview(cancelView)
}
sheetViewMoveY = headerHeight + frameHeight + UIScreen.mergin()
return frameHeight
}
}
// MARK: - ANActionSheetOutPut
extension ANActionSheet: ANActionSheetOutPut {
func dismiss() {
UIView.animateWithDuration(animateDuration, delay: 0.0, options: .CurveEaseOut, animations: {
self.sheetView.frame = CGRectOffset(self.sheetView.frame , 0, self.sheetViewMoveY)
}, completion: { (finished) in
self.removeFromSuperview()
})
}
}
| mit | b128255b546592c9ce8010efc5616f4e | 34.459893 | 201 | 0.591464 | 5.347581 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | ScrollableGraphView.swift | 1 | 77593 | import UIKit
// MARK: - ScrollableGraphView
@IBDesignable
@objc open class ScrollableGraphView: UIScrollView, UIScrollViewDelegate, ScrollableGraphViewDrawingDelegate {
// MARK: - Public Properties
// Use these to customise the graph.
// #################################
// Line Styles
// ###########
/// Specifies how thick the graph of the line is. In points.
@IBInspectable open var lineWidth: CGFloat = 2
/// The color of the graph line. UIColor.
// We must not use type inferring here or else the property won't show up in IB
@IBInspectable open var lineColor: UIColor = UIColor.black
@IBInspectable var lineStyle_: Int {
get { return lineStyle.rawValue }
set {
if let enumValue = ScrollableGraphViewLineStyle(rawValue: newValue) {
lineStyle = enumValue
}
}
}
/// Whether or not the line should be rendered using bezier curves are straight lines.
open var lineStyle = ScrollableGraphViewLineStyle.straight
/// How each segment in the line should connect. Takes any of the Core Animation LineJoin values.
@IBInspectable open var lineJoin: String = kCALineJoinRound
/// The line caps. Takes any of the Core Animation LineCap values.
@IBInspectable open var lineCap: String = kCALineCapRound
@IBInspectable open var lineCurviness: CGFloat = 0.5
// Bar styles
// ##########
/// Whether bars should be drawn or not. If you want a bar graph, this should be set to true.
@IBInspectable open var shouldDrawBarLayer: Bool = false
/// The width of an individual bar on the graph.
@IBInspectable open var barWidth: CGFloat = 25;
/// The actual colour of the bar.
@IBInspectable open var barColor: UIColor = UIColor.gray
/// The width of the outline of the bar
@IBInspectable open var barLineWidth: CGFloat = 1
/// The colour of the bar outline
@IBInspectable open var barLineColor: UIColor = UIColor.darkGray
// Fill Styles
// ###########
/// The background colour for the entire graph view, not just the plotted graph.
@IBInspectable open var backgroundFillColor: UIColor = UIColor.white
/// Specifies whether or not the plotted graph should be filled with a colour or gradient.
@IBInspectable open var shouldFill: Bool = false
@IBInspectable var fillType_: Int {
get { return fillType.rawValue }
set {
if let enumValue = ScrollableGraphViewFillType(rawValue: newValue) {
fillType = enumValue
}
}
}
/// Specifies whether to fill the graph with a solid colour or gradient.
open var fillType = ScrollableGraphViewFillType.solid
/// If fillType is set to .Solid then this colour will be used to fill the graph.
@IBInspectable open var fillColor: UIColor = UIColor.black
/// If fillType is set to .Gradient then this will be the starting colour for the gradient.
@IBInspectable open var fillGradientStartColor: UIColor = UIColor.white
/// If fillType is set to .Gradient, then this will be the ending colour for the gradient.
@IBInspectable open var fillGradientEndColor: UIColor = UIColor.black
@IBInspectable var fillGradientType_: Int {
get { return fillGradientType.rawValue }
set {
if let enumValue = ScrollableGraphViewGradientType(rawValue: newValue) {
fillGradientType = enumValue
}
}
}
/// If fillType is set to .Gradient, then this defines whether the gradient is rendered as a linear gradient or radial gradient.
open var fillGradientType = ScrollableGraphViewGradientType.linear
// Spacing
// #######
/// How far the "maximum" reference line is from the top of the view's frame. In points.
@IBInspectable open var topMargin: CGFloat = 10
/// How far the "minimum" reference line is from the bottom of the view's frame. In points.
@IBInspectable open var bottomMargin: CGFloat = 10
/// How far the first point on the graph should be placed from the left hand side of the view.
@IBInspectable open var leftmostPointPadding: CGFloat = 50
/// How far the final point on the graph should be placed from the right hand side of the view.
@IBInspectable open var rightmostPointPadding: CGFloat = 50
/// How much space should be between each data point.
@IBInspectable open var dataPointSpacing: CGFloat = 40
@IBInspectable var direction_: Int {
get { return direction.rawValue }
set {
if let enumValue = ScrollableGraphViewDirection(rawValue: newValue) {
direction = enumValue
}
}
}
/// Which side of the graph the user is expected to scroll from.
open var direction = ScrollableGraphViewDirection.leftToRight
// Graph Range
// ###########
/// If this is set to true, then the range will automatically be detected from the data the graph is given.
@IBInspectable open var shouldAutomaticallyDetectRange: Bool = false
/// Forces the graph's minimum to always be zero. Used in conjunction with shouldAutomaticallyDetectRange or shouldAdaptRange, if you want to force the minimum to stay at 0 rather than the detected minimum.
@IBInspectable open var shouldRangeAlwaysStartAtZero: Bool = false // Used in conjunction with shouldAutomaticallyDetectRange, if you want to force the min to stay at 0.
/// The minimum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMin: Double = 0
/// The maximum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMax: Double = 100
// Data Point Drawing
// ##################
/// Whether or not to draw a symbol for each data point.
@IBInspectable open var shouldDrawDataPoint: Bool = true
/// The shape to draw for each data point.
open var dataPointType = ScrollableGraphViewDataPointType.circle
/// The size of the shape to draw for each data point.
@IBInspectable open var dataPointSize: CGFloat = 5
/// The colour with which to fill the shape.
@IBInspectable open var dataPointFillColor: UIColor = UIColor.black
/// If dataPointType is set to .Custom then you,can provide a closure to create any kind of shape you would like to be displayed instead of just a circle or square. The closure takes a CGPoint which is the centre of the shape and it should return a complete UIBezierPath.
open var customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)?
// Adapting & Animations
// #####################
/// Whether or not the y-axis' range should adapt to the points that are visible on screen. This means if there are only 5 points visible on screen at any given time, the maximum on the y-axis will be the maximum of those 5 points. This is updated automatically as the user scrolls along the graph.
@IBInspectable open var shouldAdaptRange: Bool = false
/// If shouldAdaptRange is set to true then this specifies whether or not the points on the graph should animate to their new positions. Default is set to true.
@IBInspectable open var shouldAnimateOnAdapt: Bool = true
/// How long the animation should take. Affects both the startup animation and the animation when the range of the y-axis adapts to onscreen points.
@IBInspectable open var animationDuration: Double = 1
@IBInspectable var adaptAnimationType_: Int {
get { return adaptAnimationType.rawValue }
set {
if let enumValue = ScrollableGraphViewAnimationType(rawValue: newValue) {
adaptAnimationType = enumValue
}
}
}
/// The animation style.
open var adaptAnimationType = ScrollableGraphViewAnimationType.easeOut
/// If adaptAnimationType is set to .Custom, then this is the easing function you would like applied for the animation.
open var customAnimationEasingFunction: ((_ t: Double) -> Double)?
/// Whether or not the graph should animate to their positions when the graph is first displayed.
@IBInspectable open var shouldAnimateOnStartup: Bool = true
// Reference Lines
// ###############
/// Whether or not to show the y-axis reference lines and labels.
@IBInspectable open var shouldShowReferenceLines: Bool = true
/// The colour for the reference lines.
@IBInspectable open var referenceLineColor: UIColor = UIColor.black
/// The thickness of the reference lines.
@IBInspectable open var referenceLineThickness: CGFloat = 0.5
@IBInspectable var referenceLinePosition_: Int {
get { return referenceLinePosition.rawValue }
set {
if let enumValue = ScrollableGraphViewReferenceLinePosition(rawValue: newValue) {
referenceLinePosition = enumValue
}
}
}
/// Where the labels should be displayed on the reference lines.
open var referenceLinePosition = ScrollableGraphViewReferenceLinePosition.left
/// The type of reference lines. Currently only .Cover is available.
open var referenceLineType = ScrollableGraphViewReferenceLineType.cover
/// How many reference lines should be between the minimum and maximum reference lines. If you want a total of 4 reference lines, you would set this to 2. This can be set to 0 for no intermediate reference lines.This can be used to create reference lines at specific intervals. If the desired result is to have a reference line at every 10 units on the y-axis, you could, for example, set rangeMax to 100, rangeMin to 0 and numberOfIntermediateReferenceLines to 9.
@IBInspectable open var numberOfIntermediateReferenceLines: Int = 3
/// Whether or not to add labels to the intermediate reference lines.
@IBInspectable open var shouldAddLabelsToIntermediateReferenceLines: Bool = true
/// Whether or not to add units specified by the referenceLineUnits variable to the labels on the intermediate reference lines.
@IBInspectable open var shouldAddUnitsToIntermediateReferenceLineLabels: Bool = false
// Reference Line Labels
// #####################
/// The font to be used for the reference line labels.
open var referenceLineLabelFont = UIFont.systemFont(ofSize: 8)
/// The colour of the reference line labels.
@IBInspectable open var referenceLineLabelColor: UIColor = UIColor.black
/// Whether or not to show the units on the reference lines.
@IBInspectable open var shouldShowReferenceLineUnits: Bool = true
/// The units that the y-axis is in. This string is used for labels on the reference lines.
@IBInspectable open var referenceLineUnits: String?
/// The number of decimal places that should be shown on the reference line labels.
@IBInspectable open var referenceLineNumberOfDecimalPlaces: Int = 0
/// The NSNumberFormatterStyle that reference lines should use to display
@IBInspectable open var referenceLineNumberStyle: NumberFormatter.Style = .none
// Data Point Labels
// #################
/// Whether or not to show the labels on the x-axis for each point.
@IBInspectable open var shouldShowLabels: Bool = true
/// How far from the "minimum" reference line the data point labels should be rendered.
@IBInspectable open var dataPointLabelTopMargin: CGFloat = 10
/// How far from the bottom of the view the data point labels should be rendered.
@IBInspectable open var dataPointLabelBottomMargin: CGFloat = 0
/// The font for the data point labels.
@IBInspectable open var dataPointLabelColor: UIColor = UIColor.black
/// The colour for the data point labels.
open var dataPointLabelFont: UIFont? = UIFont.systemFont(ofSize: 10)
/// Used to force the graph to show every n-th dataPoint label
@IBInspectable open var dataPointLabelsSparsity: Int = 1
// MARK: - Private State
// #####################
// Graph Data for Display
fileprivate var data = [Double]()
fileprivate var labels = [String]()
fileprivate var isInitialSetup = true
fileprivate var dataNeedsReloading = true
fileprivate var isCurrentlySettingUp = false
fileprivate var viewportWidth: CGFloat = 0 {
didSet { if(oldValue != viewportWidth) { viewportDidChange() }}
}
fileprivate var viewportHeight: CGFloat = 0 {
didSet { if(oldValue != viewportHeight) { viewportDidChange() }}
}
fileprivate var totalGraphWidth: CGFloat = 0
fileprivate var offsetWidth: CGFloat = 0
// Graph Line
fileprivate var currentLinePath = UIBezierPath()
fileprivate var zeroYPosition: CGFloat = 0
// Labels
fileprivate var labelsView = UIView()
fileprivate var labelPool = LabelPool()
// Graph Drawing
fileprivate var graphPoints = [GraphPoint]()
fileprivate var drawingView = UIView()
fileprivate var barLayer: BarDrawingLayer?
fileprivate var lineLayer: LineDrawingLayer?
fileprivate var dataPointLayer: DataPointDrawingLayer?
fileprivate var fillLayer: FillDrawingLayer?
fileprivate var gradientLayer: GradientDrawingLayer?
// Reference Lines
fileprivate var referenceLineView: ReferenceLineDrawingView?
// Animation
fileprivate var displayLink: CADisplayLink!
fileprivate var previousTimestamp: CFTimeInterval = 0
fileprivate var currentTimestamp: CFTimeInterval = 0
fileprivate var currentAnimations = [GraphPointAnimation]()
// Active Points & Range Calculation
fileprivate var previousActivePointsInterval: CountableRange<Int> = -1 ..< -1
fileprivate var activePointsInterval: CountableRange<Int> = -1 ..< -1 {
didSet {
if(oldValue.lowerBound != activePointsInterval.lowerBound || oldValue.upperBound != activePointsInterval.upperBound) {
if !isCurrentlySettingUp { activePointsDidChange() }
}
}
}
fileprivate var range: (min: Double, max: Double) = (0, 100) {
didSet {
if(oldValue.min != range.min || oldValue.max != range.max) {
if !isCurrentlySettingUp { rangeDidChange() }
}
}
}
// MARK: - INIT, SETUP & VIEWPORT RESIZING
// #######################################
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
displayLink?.invalidate()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setData([10, 2, 34, 11, 22, 11, 44, 9, 12, 4], withLabels: ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"])
}
fileprivate func setup() {
isCurrentlySettingUp = true
// Make sure everything is in a clean state.
reset()
self.delegate = self
// Calculate the viewport and drawing frames.
self.viewportWidth = self.frame.width
self.viewportHeight = self.frame.height
totalGraphWidth = graphWidthForNumberOfDataPoints(data.count)
self.contentSize = CGSize(width: totalGraphWidth, height: viewportHeight)
// Scrolling direction.
#if TARGET_INTERFACE_BUILDER
self.offsetWidth = 0
#else
if (direction == .rightToLeft) {
self.offsetWidth = self.contentSize.width - viewportWidth
}
// Otherwise start of all the way to the left.
else {
self.offsetWidth = 0
}
#endif
// Set the scrollview offset.
self.contentOffset.x = self.offsetWidth
// Calculate the initial range depending on settings.
let initialActivePointsInterval = calculateActivePointsInterval()
let detectedRange = calculateRangeForEntireDataset(self.data)
if(shouldAutomaticallyDetectRange) {
self.range = detectedRange
}
else {
self.range = (min: rangeMin, max: rangeMax)
}
if (shouldAdaptRange) { // This supercedes the shouldAutomaticallyDetectRange option
let range = calculateRangeForActivePointsInterval(initialActivePointsInterval)
self.range = range
}
// If the graph was given all 0s as data, we can't use a range of 0->0, so make sure we have a sensible range at all times.
if (self.range.min == 0 && self.range.max == 0) {
self.range = (min: 0, max: rangeMax)
}
// DRAWING
let viewport = CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight)
// Create all the GraphPoints which which are used for drawing.
for i in 0 ..< data.count {
#if TARGET_INTERFACE_BUILDER
let value = data[i]
#else
let value = (shouldAnimateOnStartup) ? self.range.min : data[i]
#endif
let position = calculatePosition(i, value: value)
let point = GraphPoint(position: position)
graphPoints.append(point)
}
// Drawing Layers
drawingView = UIView(frame: viewport)
drawingView.backgroundColor = backgroundFillColor
self.addSubview(drawingView)
addDrawingLayers(inViewport: viewport)
// References Lines
if(shouldShowReferenceLines) {
addReferenceLines(inViewport: viewport)
}
// X-Axis Labels
self.insertSubview(labelsView, aboveSubview: drawingView)
updateOffsetWidths()
#if !TARGET_INTERFACE_BUILDER
// Animation loop for when the range adapts
displayLink = CADisplayLink(target: self, selector: #selector(animationUpdate))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
displayLink.isPaused = true
#endif
isCurrentlySettingUp = false
// Set the first active points interval. These are the points that are visible when the view loads.
self.activePointsInterval = initialActivePointsInterval
}
// Makes sure everything is in a clean state for when we want to reset the data for a graph.
fileprivate func reset() {
drawingView.removeFromSuperview()
referenceLineView?.removeFromSuperview()
labelPool = LabelPool()
for labelView in labelsView.subviews {
labelView.removeFromSuperview()
}
graphPoints.removeAll()
currentAnimations.removeAll()
displayLink?.invalidate()
previousTimestamp = 0
currentTimestamp = 0
previousActivePointsInterval = -1 ..< -1
activePointsInterval = -1 ..< -1
range = (0, 100)
}
fileprivate func addDrawingLayers(inViewport viewport: CGRect) {
// Line Layer
lineLayer = LineDrawingLayer(frame: viewport, lineWidth: lineWidth, lineColor: lineColor, lineStyle: lineStyle, lineJoin: lineJoin, lineCap: lineCap)
lineLayer?.graphViewDrawingDelegate = self
drawingView.layer.addSublayer(lineLayer!)
// Data Point layer
if(shouldDrawDataPoint) {
dataPointLayer = DataPointDrawingLayer(frame: viewport, fillColor: dataPointFillColor, dataPointType: dataPointType, dataPointSize: dataPointSize, customDataPointPath: customDataPointPath)
dataPointLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(dataPointLayer!, above: lineLayer)
}
// Gradient and Fills
switch (self.fillType) {
case .solid:
if(shouldFill) {
// Setup fill
fillLayer = FillDrawingLayer(frame: viewport, fillColor: fillColor)
fillLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(fillLayer!, below: lineLayer)
}
case .gradient:
if(shouldFill) {
gradientLayer = GradientDrawingLayer(frame: viewport, startColor: fillGradientStartColor, endColor: fillGradientEndColor, gradientType: fillGradientType)
gradientLayer!.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(gradientLayer!, below: lineLayer)
}
}
// The bar layer
if (shouldDrawBarLayer) {
// Bar Layer
barLayer = BarDrawingLayer(frame: viewport,
barWidth: barWidth,
barColor: barColor,
barLineWidth: barLineWidth,
barLineColor: barLineColor)
barLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer (barLayer!, below: lineLayer)
}
}
fileprivate func addReferenceLines(inViewport viewport: CGRect) {
var referenceLineBottomMargin = bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) {
referenceLineBottomMargin += (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin)
}
referenceLineView = ReferenceLineDrawingView(
frame: viewport,
topMargin: topMargin,
bottomMargin: referenceLineBottomMargin,
referenceLineColor: self.referenceLineColor,
referenceLineThickness: self.referenceLineThickness)
// Reference line settings.
referenceLineView?.referenceLinePosition = self.referenceLinePosition
referenceLineView?.referenceLineType = self.referenceLineType
referenceLineView?.numberOfIntermediateReferenceLines = self.numberOfIntermediateReferenceLines
// Reference line label settings.
referenceLineView?.shouldAddLabelsToIntermediateReferenceLines = self.shouldAddLabelsToIntermediateReferenceLines
referenceLineView?.shouldAddUnitsToIntermediateReferenceLineLabels = self.shouldAddUnitsToIntermediateReferenceLineLabels
referenceLineView?.labelUnits = referenceLineUnits
referenceLineView?.labelFont = self.referenceLineLabelFont
referenceLineView?.labelColor = self.referenceLineLabelColor
referenceLineView?.labelDecimalPlaces = self.referenceLineNumberOfDecimalPlaces
referenceLineView?.labelNumberStyle = self.referenceLineNumberStyle
referenceLineView?.setRange(self.range)
self.addSubview(referenceLineView!)
}
// If the view has changed we have to make sure we're still displaying the right data.
override open func layoutSubviews() {
super.layoutSubviews()
// while putting the view on the IB, we may get calls with frame too small
// if frame height is too small we won't be able to calculate zeroYPosition
// so make sure to proceed only if there is enough space
var availableGraphHeight = frame.height
availableGraphHeight = availableGraphHeight - topMargin - bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) { availableGraphHeight -= (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) }
if availableGraphHeight > 0 {
updateUI()
}
}
fileprivate func updateUI() {
// Make sure we have data, if don't, just get out. We can't do anything without any data.
guard data.count > 0 else {
return
}
// If the data has been updated, we need to re-init everything
if (dataNeedsReloading) {
setup()
if(shouldAnimateOnStartup) {
startAnimations(withStaggerValue: 0.15)
}
// We're done setting up.
dataNeedsReloading = false
isInitialSetup = false
}
// Otherwise, the user is just scrolling and we just need to update everything.
else {
// Needs to update the viewportWidth and viewportHeight which is used to calculate which
// points we can actually see.
viewportWidth = self.frame.width
viewportHeight = self.frame.height
// If the scrollview has scrolled anywhere, we need to update the offset
// and move around our drawing views.
offsetWidth = self.contentOffset.x
updateOffsetWidths()
// Recalculate active points for this size.
// Recalculate range for active points.
let newActivePointsInterval = calculateActivePointsInterval()
self.previousActivePointsInterval = self.activePointsInterval
self.activePointsInterval = newActivePointsInterval
// If adaption is enabled we want to
if(shouldAdaptRange) {
let newRange = calculateRangeForActivePointsInterval(newActivePointsInterval)
self.range = newRange
}
}
}
fileprivate func updateOffsetWidths() {
drawingView.frame.origin.x = offsetWidth
drawingView.bounds.origin.x = offsetWidth
gradientLayer?.offset = offsetWidth
referenceLineView?.frame.origin.x = offsetWidth
}
fileprivate func updateFrames() {
// Drawing view needs to always be the same size as the scrollview.
drawingView.frame.size.width = viewportWidth
drawingView.frame.size.height = viewportHeight
// Gradient should extend over the entire viewport
gradientLayer?.frame.size.width = viewportWidth
gradientLayer?.frame.size.height = viewportHeight
// Reference lines should extend over the entire viewport
referenceLineView?.setViewport(viewportWidth, viewportHeight: viewportHeight)
self.contentSize.height = viewportHeight
}
// MARK: - Public Methods
// ######################
open func setData(_ data: [Double], withLabels labels: [String]) {
// If we are setting exactly the same data and labels, there's no need to re-init everything.
if(self.data == data && self.labels == labels) {
return
}
self.dataNeedsReloading = true
self.data = data
self.labels = labels
if(!isInitialSetup) {
updateUI()
}
}
// MARK: - Private Methods
// #######################
// MARK: Animation
// Animation update loop for co-domain changes.
@objc fileprivate func animationUpdate() {
let dt = timeSinceLastFrame()
for animation in currentAnimations {
animation.update(dt)
if animation.finished {
dequeueAnimation(animation)
}
}
updatePaths()
}
fileprivate func animatePoint(_ point: GraphPoint, toPosition position: CGPoint, withDelay delay: Double = 0) {
let currentPoint = CGPoint(x: point.x, y: point.y)
let animation = GraphPointAnimation(fromPoint: currentPoint, toPoint: position, forGraphPoint: point)
animation.animationEasing = getAnimationEasing()
animation.duration = animationDuration
animation.delay = delay
enqueueAnimation(animation)
}
fileprivate func getAnimationEasing() -> (Double) -> Double {
switch(self.adaptAnimationType) {
case .elastic:
return Easings.EaseOutElastic
case .easeOut:
return Easings.EaseOutQuad
case .custom:
if let customEasing = customAnimationEasingFunction {
return customEasing
}
else {
fallthrough
}
default:
return Easings.EaseOutQuad
}
}
fileprivate func enqueueAnimation(_ animation: GraphPointAnimation) {
if (currentAnimations.count == 0) {
// Need to kick off the loop.
displayLink.isPaused = false
}
currentAnimations.append(animation)
}
fileprivate func dequeueAnimation(_ animation: GraphPointAnimation) {
if let index = currentAnimations.index(of: animation) {
currentAnimations.remove(at: index)
}
if(currentAnimations.count == 0) {
// Stop animation loop.
displayLink.isPaused = true
}
}
fileprivate func dequeueAllAnimations() {
for animation in currentAnimations {
animation.animationDidFinish()
}
currentAnimations.removeAll()
displayLink.isPaused = true
}
fileprivate func timeSinceLastFrame() -> Double {
if previousTimestamp == 0 {
previousTimestamp = displayLink.timestamp
} else {
previousTimestamp = currentTimestamp
}
currentTimestamp = displayLink.timestamp
var dt = currentTimestamp - previousTimestamp
if dt > 0.032 {
dt = 0.032
}
return dt
}
// MARK: Layout Calculations
fileprivate func calculateActivePointsInterval() -> CountableRange<Int> {
// Calculate the "active points"
let min = Int((offsetWidth) / dataPointSpacing)
let max = Int(((offsetWidth + viewportWidth)) / dataPointSpacing)
// Add and minus two so the path goes "off the screen" so we can't see where it ends.
let minPossible = 0
let maxPossible = data.count - 1
let numberOfPointsOffscreen = 2
let actualMin = clamp(min - numberOfPointsOffscreen, min: minPossible, max: maxPossible)
let actualMax = clamp(max + numberOfPointsOffscreen, min: minPossible, max: maxPossible)
return actualMin ... actualMax
}
fileprivate func calculateRangeForActivePointsInterval(_ interval: Range<Int>) -> (min: Double, max: Double) {
let dataForActivePoints = data[interval]
// We don't have any active points, return defaults.
if(dataForActivePoints.count == 0) {
return (min: self.rangeMin, max: self.rangeMax)
}
else {
let range = calculateRange(dataForActivePoints)
return cleanRange(range)
}
}
fileprivate func calculateRangeForEntireDataset(_ data: [Double]) -> (min: Double, max: Double) {
let range = calculateRange(self.data)
return cleanRange(range)
}
fileprivate func calculateRange<T: Collection>(_ data: T) -> (min: Double, max: Double) where T.Iterator.Element == Double {
var rangeMin: Double = Double(Int.max)
var rangeMax: Double = Double(Int.min)
for dataPoint in data {
if (dataPoint > rangeMax) {
rangeMax = dataPoint
}
if (dataPoint < rangeMin) {
rangeMin = dataPoint
}
}
return (min: rangeMin, max: rangeMax)
}
fileprivate func cleanRange(_ range: (min: Double, max: Double)) -> (min: Double, max: Double){
if(range.min == range.max) {
let min = shouldRangeAlwaysStartAtZero ? 0 : range.min
let max = range.max + 1
return (min: min, max: max)
}
else if (shouldRangeAlwaysStartAtZero) {
let min: Double = 0
var max: Double = range.max
// If we have all negative numbers and the max happens to be 0, there will cause a division by 0. Return the default height.
if(range.max == 0) {
max = rangeMax
}
return (min: min, max: max)
}
else {
return range
}
}
fileprivate func graphWidthForNumberOfDataPoints(_ numberOfPoints: Int) -> CGFloat {
let width: CGFloat = (CGFloat(numberOfPoints - 1) * dataPointSpacing) + (leftmostPointPadding + rightmostPointPadding)
return width
}
fileprivate func calculatePosition(_ index: Int, value: Double) -> CGPoint {
// Set range defaults based on settings:
// self.range.min/max is the current ranges min/max that has been detected
// self.rangeMin/Max is the min/max that should be used as specified by the user
let rangeMax = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.max : self.rangeMax
let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin
// y = the y co-ordinate in the view for the value in the graph
// ( ( value - max ) ) value = the value on the graph for which we want to know its corresponding location on the y axis in the view
// y = ( ( ----------- ) * graphHeight ) + topMargin t = the top margin
// ( ( min - max ) ) h = the height of the graph space without margins
// min = the range's current mininum
// max = the range's current maximum
// Calculate the position on in the view for the value specified.
var graphHeight = viewportHeight - topMargin - bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) { graphHeight -= (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) }
let x = (CGFloat(index) * dataPointSpacing) + leftmostPointPadding
let y = (CGFloat((value - rangeMax) / (rangeMin - rangeMax)) * graphHeight) + topMargin
return CGPoint(x: x, y: y)
}
fileprivate func clamp<T: Comparable>(_ value:T, min:T, max:T) -> T {
if (value < min) {
return min
}
else if (value > max) {
return max
}
else {
return value
}
}
// MARK: Line Path Creation
fileprivate func createLinePath() -> UIBezierPath {
currentLinePath.removeAllPoints()
let pathSegmentAdder = lineStyle == .straight ? addStraightLineSegment : addCurvedLineSegment
zeroYPosition = calculatePosition(0, value: self.range.min).y
// Connect the line to the starting edge if we are filling it.
if(shouldFill) {
// Add a line from the base of the graph to the first data point.
let firstDataPoint = graphPoints[activePointsInterval.lowerBound]
let viewportLeftZero = CGPoint(x: firstDataPoint.x - (leftmostPointPadding), y: zeroYPosition)
let leftFarEdgeTop = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: zeroYPosition)
let leftFarEdgeBottom = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: viewportHeight)
currentLinePath.move(to: leftFarEdgeBottom)
pathSegmentAdder(leftFarEdgeBottom, leftFarEdgeTop, currentLinePath)
pathSegmentAdder(leftFarEdgeTop, viewportLeftZero, currentLinePath)
pathSegmentAdder(viewportLeftZero, CGPoint(x: firstDataPoint.x, y: firstDataPoint.y), currentLinePath)
}
else {
let firstDataPoint = graphPoints[activePointsInterval.lowerBound]
currentLinePath.move(to: firstDataPoint.location)
}
// Connect each point on the graph with a segment.
for i in activePointsInterval.lowerBound ..< activePointsInterval.upperBound - 1 {
let startPoint = graphPoints[i].location
let endPoint = graphPoints[i+1].location
pathSegmentAdder(startPoint, endPoint, currentLinePath)
}
// Connect the line to the ending edge if we are filling it.
if(shouldFill) {
// Add a line from the last data point to the base of the graph.
let lastDataPoint = graphPoints[activePointsInterval.upperBound - 1]
let viewportRightZero = CGPoint(x: lastDataPoint.x + (rightmostPointPadding), y: zeroYPosition)
let rightFarEdgeTop = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: zeroYPosition)
let rightFarEdgeBottom = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: viewportHeight)
pathSegmentAdder(lastDataPoint.location, viewportRightZero, currentLinePath)
pathSegmentAdder(viewportRightZero, rightFarEdgeTop, currentLinePath)
pathSegmentAdder(rightFarEdgeTop, rightFarEdgeBottom, currentLinePath)
}
return currentLinePath
}
fileprivate func addStraightLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
path.addLine(to: endPoint)
}
fileprivate func addCurvedLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
// calculate control points
let difference = endPoint.x - startPoint.x
var x = startPoint.x + (difference * lineCurviness)
var y = startPoint.y
let controlPointOne = CGPoint(x: x, y: y)
x = endPoint.x - (difference * lineCurviness)
y = endPoint.y
let controlPointTwo = CGPoint(x: x, y: y)
// add curve from start to end
currentLinePath.addCurve(to: endPoint, controlPoint1: controlPointOne, controlPoint2: controlPointTwo)
}
// MARK: Events
// If the active points (the points we can actually see) change, then we need to update the path.
fileprivate func activePointsDidChange() {
let deactivatedPoints = determineDeactivatedPoints()
let activatedPoints = determineActivatedPoints()
updatePaths()
if(shouldShowLabels) {
let deactivatedLabelPoints = filterPointsForLabels(fromPoints: deactivatedPoints)
let activatedLabelPoints = filterPointsForLabels(fromPoints: activatedPoints)
updateLabels(deactivatedLabelPoints, activatedLabelPoints)
}
}
fileprivate func rangeDidChange() {
// If shouldAnimateOnAdapt is enabled it will kickoff any animations that need to occur.
startAnimations()
referenceLineView?.setRange(range)
}
fileprivate func viewportDidChange() {
// We need to make sure all the drawing views are the same size as the viewport.
updateFrames()
// Basically this recreates the paths with the new viewport size so things are in sync, but only
// if the viewport has changed after the initial setup. Because the initial setup will use the latest
// viewport anyway.
if(!isInitialSetup) {
updatePaths()
// Need to update the graph points so they are in their right positions for the new viewport.
// Animate them into position if animation is enabled, but make sure to stop any current animations first.
#if !TARGET_INTERFACE_BUILDER
dequeueAllAnimations()
#endif
startAnimations()
// The labels will also need to be repositioned if the viewport has changed.
repositionActiveLabels()
}
}
// Update any paths with the new path based on visible data points.
fileprivate func updatePaths() {
createLinePath()
if let drawingLayers = drawingView.layer.sublayers {
for layer in drawingLayers {
if let layer = layer as? ScrollableGraphViewDrawingLayer {
// The bar layer needs the zero Y position to set the bottom of the bar
layer.zeroYPosition = zeroYPosition
// Need to make sure this is set in createLinePath
assert (layer.zeroYPosition > 0);
layer.updatePath()
}
}
}
}
// Update any labels for any new points that have been activated and deactivated.
fileprivate func updateLabels(_ deactivatedPoints: [Int], _ activatedPoints: [Int]) {
// Disable any labels for the deactivated points.
for point in deactivatedPoints {
labelPool.deactivateLabelForPointIndex(point)
}
// Grab an unused label and update it to the right position for the newly activated poitns
for point in activatedPoints {
let label = labelPool.activateLabelForPointIndex(point)
label.text = (point < labels.count) ? labels[point] : ""
label.textColor = dataPointLabelColor
label.font = dataPointLabelFont
label.sizeToFit()
// self.range.min is the current ranges minimum that has been detected
// self.rangeMin is the minimum that should be used as specified by the user
let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin
let position = calculatePosition(point, value: rangeMin)
label.frame = CGRect(origin: CGPoint(x: position.x - label.frame.width / 2, y: position.y + dataPointLabelTopMargin), size: label.frame.size)
labelsView.addSubview(label)
}
}
fileprivate func repositionActiveLabels() {
for label in labelPool.activeLabels {
let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin
let position = calculatePosition(0, value: rangeMin)
label.frame.origin.y = position.y + dataPointLabelTopMargin
}
}
// Returns the indices of any points that became inactive (that is, "off screen"). (No order)
fileprivate func determineDeactivatedPoints() -> [Int] {
let prevSet = setFromClosedRange(previousActivePointsInterval)
let currSet = setFromClosedRange(activePointsInterval)
let deactivatedPoints = prevSet.subtracting(currSet)
return Array(deactivatedPoints)
}
// Returns the indices of any points that became active (on screen). (No order)
fileprivate func determineActivatedPoints() -> [Int] {
let prevSet = setFromClosedRange(previousActivePointsInterval)
let currSet = setFromClosedRange(activePointsInterval)
let activatedPoints = currSet.subtracting(prevSet)
return Array(activatedPoints)
}
fileprivate func setFromClosedRange(_ range: Range<Int>) -> Set<Int> {
var set = Set<Int>()
for index in range.lowerBound...range.upperBound {
set.insert(index)
}
return set
}
fileprivate func filterPointsForLabels(fromPoints points:[Int]) -> [Int] {
if(self.dataPointLabelsSparsity == 1) {
return points
}
return points.filter({ $0 % self.dataPointLabelsSparsity == 0 })
}
fileprivate func startAnimations(withStaggerValue stagger: Double = 0) {
var pointsToAnimate = 0 ..< 0
#if !TARGET_INTERFACE_BUILDER
if (shouldAnimateOnAdapt || (dataNeedsReloading && shouldAnimateOnStartup)) {
pointsToAnimate = activePointsInterval
}
#endif
// For any visible points, kickoff the animation to their new position after the axis' min/max has changed.
//let numberOfPointsToAnimate = pointsToAnimate.endIndex - pointsToAnimate.startIndex
var index = 0
for i in pointsToAnimate {
let newPosition = calculatePosition(i, value: data[i])
let point = graphPoints[i]
animatePoint(point, toPosition: newPosition, withDelay: Double(index) * stagger)
index += 1
}
// Update any non-visible & non-animating points so they come on to screen at the right scale.
for i in 0 ..< graphPoints.count {
if(i > pointsToAnimate.lowerBound && i < pointsToAnimate.upperBound || graphPoints[i].currentlyAnimatingToPosition) {
continue
}
let newPosition = calculatePosition(i, value: data[i])
graphPoints[i].x = newPosition.x
graphPoints[i].y = newPosition.y
}
}
// MARK: - Drawing Delegate
fileprivate func currentPath() -> UIBezierPath {
return currentLinePath
}
fileprivate func intervalForActivePoints() -> CountableRange<Int> {
return activePointsInterval
}
fileprivate func rangeForActivePoints() -> (min: Double, max: Double) {
return range
}
fileprivate func graphPointForIndex(_ index: Int) -> GraphPoint {
return graphPoints[index]
}
}
// MARK: - LabelPool
private class LabelPool {
var labels = [UILabel]()
var relations = [Int : Int]()
var unused = [Int]()
func deactivateLabelForPointIndex(_ pointIndex: Int){
if let unusedLabelIndex = relations[pointIndex] {
unused.append(unusedLabelIndex)
}
relations[pointIndex] = nil
}
func activateLabelForPointIndex(_ pointIndex: Int) -> UILabel {
var label: UILabel
if(unused.count >= 1) {
let unusedLabelIndex = unused.first!
unused.removeFirst()
label = labels[unusedLabelIndex]
relations[pointIndex] = unusedLabelIndex
}
else {
label = UILabel()
labels.append(label)
let newLabelIndex = labels.index(of: label)!
relations[pointIndex] = newLabelIndex
}
return label
}
var activeLabels: [UILabel] {
get {
var currentlyActive = [UILabel]()
let numberOfLabels = labels.count
for i in 0 ..< numberOfLabels {
if(!unused.contains(i)) {
currentlyActive.append(labels[i])
}
}
return currentlyActive
}
}
}
// MARK: - GraphPoints and Animation Classes
private class GraphPoint {
var location = CGPoint(x: 0, y: 0)
var currentlyAnimatingToPosition = false
fileprivate var x: CGFloat {
get {
return location.x
}
set {
location.x = newValue
}
}
fileprivate var y: CGFloat {
get {
return location.y
}
set {
location.y = newValue
}
}
init(position: CGPoint = CGPoint.zero) {
x = position.x
y = position.y
}
}
private class GraphPointAnimation : Equatable {
// Public Properties
var animationEasing = Easings.EaseOutQuad
var duration: Double = 1
var delay: Double = 0
fileprivate(set) var finished = false
fileprivate(set) var animationKey: String
// Private State
fileprivate var startingPoint: CGPoint
fileprivate var endingPoint: CGPoint
fileprivate var elapsedTime: Double = 0
fileprivate var graphPoint: GraphPoint?
fileprivate var multiplier: Double = 1
static fileprivate var animationsCreated = 0
init(fromPoint: CGPoint, toPoint: CGPoint, forGraphPoint graphPoint: GraphPoint, forKey key: String = "animation\(animationsCreated)") {
self.startingPoint = fromPoint
self.endingPoint = toPoint
self.animationKey = key
self.graphPoint = graphPoint
self.graphPoint?.currentlyAnimatingToPosition = true
GraphPointAnimation.animationsCreated += 1
}
func update(_ dt: Double) {
if(!finished) {
if elapsedTime > delay {
let animationElapsedTime = elapsedTime - delay
let changeInX = endingPoint.x - startingPoint.x
let changeInY = endingPoint.y - startingPoint.y
// t is in the range of 0 to 1, indicates how far through the animation it is.
let t = animationElapsedTime / duration
let interpolation = animationEasing(t)
let x = startingPoint.x + changeInX * CGFloat(interpolation)
let y = startingPoint.y + changeInY * CGFloat(interpolation)
if(animationElapsedTime >= duration) {
animationDidFinish()
}
graphPoint?.x = CGFloat(x)
graphPoint?.y = CGFloat(y)
elapsedTime += dt * multiplier
}
// Keep going until we are passed the delay
else {
elapsedTime += dt * multiplier
}
}
}
func animationDidFinish() {
self.graphPoint?.currentlyAnimatingToPosition = false
self.finished = true
}
}
private func ==(lhs: GraphPointAnimation, rhs: GraphPointAnimation) -> Bool {
return lhs.animationKey == rhs.animationKey
}
// MARK: - Drawing Layers
// MARK: Delegate definition that provides the data required by the drawing layers.
private protocol ScrollableGraphViewDrawingDelegate {
func intervalForActivePoints() -> CountableRange<Int>
func rangeForActivePoints() -> (min: Double, max: Double)
func graphPointForIndex(_ index: Int) -> GraphPoint
func currentPath() -> UIBezierPath
}
// MARK: Drawing Layer Classes
// MARK: Base Class
private class ScrollableGraphViewDrawingLayer : CAShapeLayer {
var offset: CGFloat = 0 {
didSet {
offsetDidChange()
}
}
var viewportWidth: CGFloat = 0
var viewportHeight: CGFloat = 0
var zeroYPosition: CGFloat = 0
var graphViewDrawingDelegate: ScrollableGraphViewDrawingDelegate? = nil
var active = true
init(viewportWidth: CGFloat, viewportHeight: CGFloat, offset: CGFloat = 0) {
super.init()
self.viewportWidth = viewportWidth
self.viewportHeight = viewportHeight
self.frame = CGRect(origin: CGPoint(x: offset, y: 0), size: CGSize(width: self.viewportWidth, height: self.viewportHeight))
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setup() {
// Get rid of any animations.
self.actions = ["position" : NSNull(), "bounds" : NSNull()]
}
fileprivate func offsetDidChange() {
self.frame.origin.x = offset
self.bounds.origin.x = offset
}
func updatePath() {
fatalError("updatePath needs to be implemented by the subclass")
}
}
// MARK: Drawing the bars
private class BarDrawingLayer: ScrollableGraphViewDrawingLayer {
fileprivate var barPath = UIBezierPath()
fileprivate var barWidth: CGFloat = 4
init(frame: CGRect, barWidth: CGFloat, barColor: UIColor, barLineWidth: CGFloat, barLineColor: UIColor) {
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.barWidth = barWidth
self.lineWidth = barLineWidth
self.strokeColor = barLineColor.cgColor
self.fillColor = barColor.cgColor
self.lineJoin = lineJoin
self.lineCap = lineCap
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createBarPath(_ centre: CGPoint) -> UIBezierPath {
let squarePath = UIBezierPath()
squarePath.move(to: centre)
let barWidthOffset: CGFloat = self.barWidth / 2
let topLeft = CGPoint(x: centre.x - barWidthOffset, y: centre.y)
let topRight = CGPoint(x: centre.x + barWidthOffset, y: centre.y)
let bottomLeft = CGPoint(x: centre.x - barWidthOffset, y: zeroYPosition)
let bottomRight = CGPoint(x: centre.x + barWidthOffset, y: zeroYPosition)
squarePath.move(to: topLeft)
squarePath.addLine(to: topRight)
squarePath.addLine(to: bottomRight)
squarePath.addLine(to: bottomLeft)
squarePath.addLine(to: topLeft)
return squarePath
}
fileprivate func createPath () -> UIBezierPath {
barPath.removeAllPoints()
// We can only move forward if we can get the data we need from the delegate.
guard let
activePointsInterval = self.graphViewDrawingDelegate?.intervalForActivePoints()
else {
return barPath
}
for i in activePointsInterval {
var location = CGPoint.zero
if let pointLocation = self.graphViewDrawingDelegate?.graphPointForIndex(i).location {
location = pointLocation
}
let pointPath = createBarPath(location)
barPath.append(pointPath)
}
return barPath
}
override func updatePath() {
self.path = createPath ().cgPath
}
}
// MARK: Drawing the Graph Line
private class LineDrawingLayer : ScrollableGraphViewDrawingLayer {
init(frame: CGRect, lineWidth: CGFloat, lineColor: UIColor, lineStyle: ScrollableGraphViewLineStyle, lineJoin: String, lineCap: String) {
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.lineWidth = lineWidth
self.strokeColor = lineColor.cgColor
self.lineJoin = lineJoin
self.lineCap = lineCap
// Setup
self.fillColor = UIColor.clear.cgColor // This is handled by the fill drawing layer.
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updatePath() {
self.path = graphViewDrawingDelegate?.currentPath().cgPath
}
}
// MARK: Drawing the Individual Data Points
private class DataPointDrawingLayer: ScrollableGraphViewDrawingLayer {
fileprivate var dataPointPath = UIBezierPath()
fileprivate var dataPointSize: CGFloat = 5
fileprivate var dataPointType: ScrollableGraphViewDataPointType = .circle
fileprivate var customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)?
init(frame: CGRect, fillColor: UIColor, dataPointType: ScrollableGraphViewDataPointType, dataPointSize: CGFloat, customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)? = nil) {
self.dataPointType = dataPointType
self.dataPointSize = dataPointSize
self.customDataPointPath = customDataPointPath
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.fillColor = fillColor.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createDataPointPath() -> UIBezierPath {
dataPointPath.removeAllPoints()
// We can only move forward if we can get the data we need from the delegate.
guard let
activePointsInterval = self.graphViewDrawingDelegate?.intervalForActivePoints()
else {
return dataPointPath
}
let pointPathCreator = getPointPathCreator()
for i in activePointsInterval {
var location = CGPoint.zero
if let pointLocation = self.graphViewDrawingDelegate?.graphPointForIndex(i).location {
location = pointLocation
}
let pointPath = pointPathCreator(location)
dataPointPath.append(pointPath)
}
return dataPointPath
}
fileprivate func createCircleDataPoint(_ centre: CGPoint) -> UIBezierPath {
return UIBezierPath(arcCenter: centre, radius: dataPointSize, startAngle: 0, endAngle: CGFloat(2.0 * M_PI), clockwise: true)
}
fileprivate func createSquareDataPoint(_ centre: CGPoint) -> UIBezierPath {
let squarePath = UIBezierPath()
squarePath.move(to: centre)
let topLeft = CGPoint(x: centre.x - dataPointSize, y: centre.y - dataPointSize)
let topRight = CGPoint(x: centre.x + dataPointSize, y: centre.y - dataPointSize)
let bottomLeft = CGPoint(x: centre.x - dataPointSize, y: centre.y + dataPointSize)
let bottomRight = CGPoint(x: centre.x + dataPointSize, y: centre.y + dataPointSize)
squarePath.move(to: topLeft)
squarePath.addLine(to: topRight)
squarePath.addLine(to: bottomRight)
squarePath.addLine(to: bottomLeft)
squarePath.addLine(to: topLeft)
return squarePath
}
fileprivate func getPointPathCreator() -> (_ centre: CGPoint) -> UIBezierPath {
switch(self.dataPointType) {
case .circle:
return createCircleDataPoint
case .square:
return createSquareDataPoint
case .custom:
if let customCreator = self.customDataPointPath {
return customCreator
}
else {
// We don't have a custom path, so just return the default.
fallthrough
}
default:
return createCircleDataPoint
}
}
override func updatePath() {
self.path = createDataPointPath().cgPath
}
}
// MARK: Drawing the Graph Gradient Fill
private class GradientDrawingLayer : ScrollableGraphViewDrawingLayer {
fileprivate var startColor: UIColor
fileprivate var endColor: UIColor
fileprivate var gradientType: ScrollableGraphViewGradientType
lazy fileprivate var gradientMask: CAShapeLayer = ({
let mask = CAShapeLayer()
mask.frame = CGRect(x: 0, y: 0, width: self.viewportWidth, height: self.viewportHeight)
mask.fillRule = kCAFillRuleEvenOdd
mask.path = self.graphViewDrawingDelegate?.currentPath().cgPath
mask.lineJoin = self.lineJoin
return mask
})()
init(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientType: ScrollableGraphViewGradientType, lineJoin: String = kCALineJoinRound) {
self.startColor = startColor
self.endColor = endColor
self.gradientType = gradientType
//self.lineJoin = lineJoin
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
addMaskLayer()
self.setNeedsDisplay()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func addMaskLayer() {
self.mask = gradientMask
}
override func updatePath() {
gradientMask.path = graphViewDrawingDelegate?.currentPath().cgPath
}
override func draw(in ctx: CGContext) {
let colors = [startColor.cgColor, endColor.cgColor]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let locations: [CGFloat] = [0.0, 1.0]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)
let displacement = ((viewportWidth / viewportHeight) / 2.5) * self.bounds.height
let topCentre = CGPoint(x: offset + self.bounds.width / 2, y: -displacement)
let bottomCentre = CGPoint(x: offset + self.bounds.width / 2, y: self.bounds.height)
let startRadius: CGFloat = 0
let endRadius: CGFloat = self.bounds.width
switch(gradientType) {
case .linear:
ctx.drawLinearGradient(gradient!, start: topCentre, end: bottomCentre, options: .drawsAfterEndLocation)
case .radial:
ctx.drawRadialGradient(gradient!, startCenter: topCentre, startRadius: startRadius, endCenter: topCentre, endRadius: endRadius, options: .drawsAfterEndLocation)
}
}
}
// MARK: Drawing the Graph Fill
private class FillDrawingLayer : ScrollableGraphViewDrawingLayer {
init(frame: CGRect, fillColor: UIColor) {
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.fillColor = fillColor.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updatePath() {
self.path = graphViewDrawingDelegate?.currentPath().cgPath
}
}
// MARK: - Reference Lines
private class ReferenceLineDrawingView : UIView {
// PUBLIC PROPERTIES
// Reference line settings.
var referenceLineColor: UIColor = UIColor.black
var referenceLineThickness: CGFloat = 0.5
var referenceLinePosition = ScrollableGraphViewReferenceLinePosition.left
var referenceLineType = ScrollableGraphViewReferenceLineType.cover
var numberOfIntermediateReferenceLines = 3 // Number of reference lines between the min and max line.
// Reference line label settings.
var shouldAddLabelsToIntermediateReferenceLines: Bool = true
var shouldAddUnitsToIntermediateReferenceLineLabels: Bool = false
var labelUnits: String?
var labelFont: UIFont = UIFont.systemFont(ofSize: 8)
var labelColor: UIColor = UIColor.black
var labelDecimalPlaces: Int = 2
var labelNumberStyle: NumberFormatter.Style = .none
// PRIVATE PROPERTIES
fileprivate var intermediateLineWidthMultiplier: CGFloat = 1 //FUTURE: Can make the intermediate lines shorter using this.
fileprivate var referenceLineWidth: CGFloat = 100 // FUTURE: Used when referenceLineType == .Edge
fileprivate var labelMargin: CGFloat = 4
fileprivate var leftLabelInset: CGFloat = 10
fileprivate var rightLabelInset: CGFloat = 10
// Store information about the ScrollableGraphView
fileprivate var currentRange: (min: Double, max: Double) = (0,100)
fileprivate var topMargin: CGFloat = 10
fileprivate var bottomMargin: CGFloat = 10
// Partition recursion depth // FUTURE: For .Edge
// private var referenceLinePartitions: Int = 3
fileprivate var lineWidth: CGFloat {
get {
if(self.referenceLineType == ScrollableGraphViewReferenceLineType.cover) {
return self.bounds.width
}
else {
return referenceLineWidth
}
}
}
fileprivate var units: String {
get {
if let units = self.labelUnits {
return " \(units)"
} else {
return ""
}
}
}
// Layers
fileprivate var labels = [UILabel]()
fileprivate let referenceLineLayer = CAShapeLayer()
fileprivate let referenceLinePath = UIBezierPath()
init(frame: CGRect, topMargin: CGFloat, bottomMargin: CGFloat, referenceLineColor: UIColor, referenceLineThickness: CGFloat) {
super.init(frame: frame)
self.topMargin = topMargin
self.bottomMargin = bottomMargin
// The reference line layer draws the reference lines and we handle the labels elsewhere.
self.referenceLineLayer.frame = self.frame
self.referenceLineLayer.strokeColor = referenceLineColor.cgColor
self.referenceLineLayer.lineWidth = referenceLineThickness
self.layer.addSublayer(referenceLineLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createLabelAtPosition(_ position: CGPoint, withText text: String) -> UILabel {
let frame = CGRect(x: position.x, y: position.y, width: 0, height: 0)
let label = UILabel(frame: frame)
return label
}
fileprivate func createReferenceLinesPath() -> UIBezierPath {
referenceLinePath.removeAllPoints()
for label in labels {
label.removeFromSuperview()
}
labels.removeAll()
let maxLineStart = CGPoint(x: 0, y: topMargin)
let maxLineEnd = CGPoint(x: lineWidth, y: topMargin)
let minLineStart = CGPoint(x: 0, y: self.bounds.height - bottomMargin)
let minLineEnd = CGPoint(x: lineWidth, y: self.bounds.height - bottomMargin)
let numberFormatter = referenceNumberFormatter()
let maxString = numberFormatter.string(from: NSNumber(self.currentRange.max))! + units
let minString = numberFormatter.string(from: NSNumber(self.currentRange.min))! + units
addLineWithTag(maxString, from: maxLineStart, to: maxLineEnd, inPath: referenceLinePath)
addLineWithTag(minString, from: minLineStart, to: minLineEnd, inPath: referenceLinePath)
let initialRect = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y + topMargin, width: self.bounds.size.width, height: self.bounds.size.height - (topMargin + bottomMargin))
createIntermediateReferenceLines(initialRect, numberOfIntermediateReferenceLines: self.numberOfIntermediateReferenceLines, forPath: referenceLinePath)
return referenceLinePath
}
fileprivate func referenceNumberFormatter() -> NumberFormatter {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = labelNumberStyle
numberFormatter.minimumFractionDigits = labelDecimalPlaces
numberFormatter.maximumFractionDigits = labelDecimalPlaces
return numberFormatter
}
fileprivate func createIntermediateReferenceLines(_ rect: CGRect, numberOfIntermediateReferenceLines: Int, forPath path: UIBezierPath) {
let height = rect.size.height
let spacePerPartition = height / CGFloat(numberOfIntermediateReferenceLines + 1)
for i in 0 ..< numberOfIntermediateReferenceLines {
let lineStart = CGPoint(x: 0, y: rect.origin.y + (spacePerPartition * CGFloat(i + 1)))
let lineEnd = CGPoint(x: lineStart.x + lineWidth * intermediateLineWidthMultiplier, y: lineStart.y)
createReferenceLineFrom(from: lineStart, to: lineEnd, inPath: path)
}
}
// FUTURE: Can use the recursive version to create a ruler like look on the edge.
fileprivate func recursiveCreateIntermediateReferenceLines(_ rect: CGRect, width: CGFloat, forPath path: UIBezierPath, remainingPartitions: Int) -> UIBezierPath {
if(remainingPartitions <= 0) {
return path
}
let lineStart = CGPoint(x: 0, y: rect.origin.y + (rect.size.height / 2))
let lineEnd = CGPoint(x: lineStart.x + width, y: lineStart.y)
createReferenceLineFrom(from: lineStart, to: lineEnd, inPath: path)
let topRect = CGRect(
x: rect.origin.x,
y: rect.origin.y,
width: rect.size.width,
height: rect.size.height / 2)
let bottomRect = CGRect(
x: rect.origin.x,
y: rect.origin.y + (rect.size.height / 2),
width: rect.size.width,
height: rect.size.height / 2)
recursiveCreateIntermediateReferenceLines(topRect, width: width * intermediateLineWidthMultiplier, forPath: path, remainingPartitions: remainingPartitions - 1)
recursiveCreateIntermediateReferenceLines(bottomRect, width: width * intermediateLineWidthMultiplier, forPath: path, remainingPartitions: remainingPartitions - 1)
return path
}
fileprivate func createReferenceLineFrom(from lineStart: CGPoint, to lineEnd: CGPoint, inPath path: UIBezierPath) {
if(shouldAddLabelsToIntermediateReferenceLines) {
let value = calculateYAxisValueForPoint(lineStart)
let numberFormatter = referenceNumberFormatter()
var valueString = numberFormatter.string(from: NSNumber(value))!
if(shouldAddUnitsToIntermediateReferenceLineLabels) {
valueString += " \(units)"
}
addLineWithTag(valueString, from: lineStart, to: lineEnd, inPath: path)
} else {
addLineFrom(lineStart, to: lineEnd, inPath: path)
}
}
fileprivate func addLineWithTag(_ tag: String, from: CGPoint, to: CGPoint, inPath path: UIBezierPath) {
let boundingSize = boundingSizeForText(tag)
let leftLabel = createLabelWithText(tag)
let rightLabel = createLabelWithText(tag)
// Left label gap.
leftLabel.frame = CGRect(
origin: CGPoint(x: from.x + leftLabelInset, y: from.y - (boundingSize.height / 2)),
size: boundingSize)
let leftLabelStart = CGPoint(x: leftLabel.frame.origin.x - labelMargin, y: to.y)
let leftLabelEnd = CGPoint(x: (leftLabel.frame.origin.x + leftLabel.frame.size.width) + labelMargin, y: to.y)
// Right label gap.
rightLabel.frame = CGRect(
origin: CGPoint(x: (from.x + self.frame.width) - rightLabelInset - boundingSize.width, y: from.y - (boundingSize.height / 2)),
size: boundingSize)
let rightLabelStart = CGPoint(x: rightLabel.frame.origin.x - labelMargin, y: to.y)
let rightLabelEnd = CGPoint(x: (rightLabel.frame.origin.x + rightLabel.frame.size.width) + labelMargin, y: to.y)
// Add the lines and tags depending on the settings for where we want them.
var gaps = [(start: CGFloat, end: CGFloat)]()
switch(self.referenceLinePosition) {
case .left:
gaps.append((start: leftLabelStart.x, end: leftLabelEnd.x))
self.addSubview(leftLabel)
self.labels.append(leftLabel)
case .right:
gaps.append((start: rightLabelStart.x, end: rightLabelEnd.x))
self.addSubview(rightLabel)
self.labels.append(rightLabel)
case .both:
gaps.append((start: leftLabelStart.x, end: leftLabelEnd.x))
gaps.append((start: rightLabelStart.x, end: rightLabelEnd.x))
self.addSubview(leftLabel)
self.addSubview(rightLabel)
self.labels.append(leftLabel)
self.labels.append(rightLabel)
}
addLineWithGaps(from, to: to, withGaps: gaps, inPath: path)
}
fileprivate func addLineWithGaps(_ from: CGPoint, to: CGPoint, withGaps gaps: [(start: CGFloat, end: CGFloat)], inPath path: UIBezierPath) {
// If there are no gaps, just add a single line.
if(gaps.count <= 0) {
addLineFrom(from, to: to, inPath: path)
}
// If there is only 1 gap, it's just two lines.
else if (gaps.count == 1) {
let gapLeft = CGPoint(x: gaps.first!.start, y: from.y)
let gapRight = CGPoint(x: gaps.first!.end, y: from.y)
addLineFrom(from, to: gapLeft, inPath: path)
addLineFrom(gapRight, to: to, inPath: path)
}
// If there are many gaps, we have a series of intermediate lines.
else {
let firstGap = gaps.first!
let lastGap = gaps.last!
let firstGapLeft = CGPoint(x: firstGap.start, y: from.y)
let lastGapRight = CGPoint(x: lastGap.end, y: to.y)
// Add the first line to the start of the first gap
addLineFrom(from, to: firstGapLeft, inPath: path)
// Add lines between all intermediate gaps
for i in 0 ..< gaps.count - 1 {
let startGapEnd = gaps[i].end
let endGapStart = gaps[i + 1].start
let lineStart = CGPoint(x: startGapEnd, y: from.y)
let lineEnd = CGPoint(x: endGapStart, y: from.y)
addLineFrom(lineStart, to: lineEnd, inPath: path)
}
// Add the final line to the end
addLineFrom(lastGapRight, to: to, inPath: path)
}
}
fileprivate func addLineFrom(_ from: CGPoint, to: CGPoint, inPath path: UIBezierPath) {
path.move(to: from)
path.addLine(to: to)
}
fileprivate func boundingSizeForText(_ text: String) -> CGSize {
return (text as NSString).size(attributes: [NSFontAttributeName:labelFont])
}
fileprivate func calculateYAxisValueForPoint(_ point: CGPoint) -> Double {
let graphHeight = self.frame.size.height - (topMargin + bottomMargin)
// value = the corresponding value on the graph for any y co-ordinate in the view
// y - t y = the y co-ordinate in the view for which we want to know the corresponding value on the graph
// value = --------- * (min - max) + max t = the top margin
// h h = the height of the graph space without margins
// min = the range's current mininum
// max = the range's current maximum
var value = (((point.y - topMargin) / (graphHeight)) * CGFloat((self.currentRange.min - self.currentRange.max))) + CGFloat(self.currentRange.max)
// Sometimes results in "negative zero"
if(value == 0) {
value = 0
}
return Double(value)
}
fileprivate func createLabelWithText(_ text: String) -> UILabel {
let label = UILabel()
label.text = text
label.textColor = labelColor
label.font = labelFont
return label
}
// Public functions to update the reference lines with any changes to the range and viewport (phone rotation, etc).
// When the range changes, need to update the max for the new range, then update all the labels that are showing for the axis and redraw the reference lines.
func setRange(_ range: (min: Double, max: Double)) {
self.currentRange = range
self.referenceLineLayer.path = createReferenceLinesPath().cgPath
}
func setViewport(_ viewportWidth: CGFloat, viewportHeight: CGFloat) {
self.frame.size.width = viewportWidth
self.frame.size.height = viewportHeight
self.referenceLineLayer.path = createReferenceLinesPath().cgPath
}
}
// MARK: - ScrollableGraphView Settings Enums
@objc public enum ScrollableGraphViewLineStyle : Int {
case straight
case smooth
}
@objc public enum ScrollableGraphViewFillType : Int {
case solid
case gradient
}
@objc public enum ScrollableGraphViewGradientType : Int {
case linear
case radial
}
@objc public enum ScrollableGraphViewDataPointType : Int {
case circle
case square
case custom
}
@objc public enum ScrollableGraphViewReferenceLinePosition : Int {
case left
case right
case both
}
@objc public enum ScrollableGraphViewReferenceLineType : Int {
case cover
//case Edge // FUTURE: Implement
}
@objc public enum ScrollableGraphViewAnimationType : Int {
case easeOut
case elastic
case custom
}
@objc public enum ScrollableGraphViewDirection : Int {
case leftToRight
case rightToLeft
}
// Simplified easing functions from: http://www.joshondesign.com/2013/03/01/improvedEasingEquations
private struct Easings {
static let EaseInQuad = { (t:Double) -> Double in return t*t; }
static let EaseOutQuad = { (t:Double) -> Double in return 1 - Easings.EaseInQuad(1-t); }
static let EaseOutElastic = { (t: Double) -> Double in
var p = 0.3;
return pow(2,-10*t) * sin((t-p/4)*(2*M_PI)/p) + 1;
}
}
| mit | b7efcf1b911eabc542916247d4e81c12 | 37.7965 | 468 | 0.624476 | 5.156024 | false | false | false | false |
BeanstalkData/beanstalk-ios-sdk | Example/BeanstalkEngageiOSSDK/RegisterViewController.swift | 1 | 4545 | //
// RegisterViewController.swift
// BeanstalkEngageiOSSDK
//
// 2016 Heartland Commerce, Inc. All rights reserved.
//
import UIKit
import BeanstalkEngageiOSSDK
class RegisterViewController: BaseViewController, RegistrationProtocol, UITextFieldDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var firstNameTextField: UITextField!
@IBOutlet var lastNameTextField: UITextField!
@IBOutlet var phoneTextField: UITextField!
@IBOutlet var emailTextField: UITextField!
@IBOutlet var confirmEmailTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var confirmPasswordTextField: UITextField!
@IBOutlet var zipCodeTextField: UITextField!
@IBOutlet var optEmailCheckBox: UISwitch!
@IBOutlet var genderSegmentView: UISegmentedControl!
var selectedDate = NSDate()
override func viewDidLoad() {
super.viewDidLoad()
self.firstNameTextField.text = "John"
self.lastNameTextField.text = "Appleseed"
self.phoneTextField.text = "+1234567890"
self.emailTextField.text = ""
self.confirmEmailTextField.text = ""
self.passwordTextField.text = ""
self.confirmPasswordTextField.text = ""
self.zipCodeTextField.text = ""
self.optEmailCheckBox.on = false
self.genderSegmentView.selectedSegmentIndex = 0
self.selectedDate = self.dateInPast(21)!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Register",
style: .Plain,
target: self,
action: #selector(register))
}
//MARK: - Actions
func register() {
self.scrollView.endEditing(true)
let request = CreateContactRequest()
request.firstName = self.firstNameTextField.text
request.lastName = self.lastNameTextField.text
request.phone = self.phoneTextField.text?.stringByReplacingOccurrencesOfString("-", withString: "")
request.email = self.emailTextField.text
request.emailConfirm = self.confirmEmailTextField.text
request.password = self.passwordTextField.text
request.passwordConfirm = self.confirmPasswordTextField.text
request.zipCode = self.zipCodeTextField.text
request.birthdate = self.getFormatedDate(self.selectedDate, dateFormat: "yyyy-MM-dd")
request.emailOptIn = self.optEmailCheckBox.on
request.preferredReward = ""
request.gender = self.genderSegmentView.selectedSegmentIndex == 0 ? "Male" : "Female"
self.coreService?.register(self, request: request, handler: { (success) in
self.completionBlock?(success: success)
})
// self.coreService?.registerLoyaltyAccount(self, request: request, handler: {
// success in
// self.completionBlock?(success: success)
// })
}
//MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
//MARK: - Private
private func getFormatedDate(date: NSDate, dateFormat: String) -> String {
var formatedString: String!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
formatedString = dateFormatter.stringFromDate(date)
return formatedString
}
override internal func keyboardWillChange(notification: NSNotification) {
var scrollInsets = UIEdgeInsetsZero
if let endFrameInfo = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let endFrame = endFrameInfo.CGRectValue()
let converted = self.view.convertRect(endFrame, fromView: UIApplication.sharedApplication().keyWindow!)
scrollInsets.bottom = converted.height
}
self.scrollView.contentInset = scrollInsets
self.scrollView.scrollIndicatorInsets = scrollInsets
}
override internal func keyboardWillHide(notification: NSNotification) {
self.scrollView.contentInset = UIEdgeInsetsZero
self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero
}
//MARK: - Private
private func dateInPast(yearsAgo: Int) -> NSDate? {
let currentDate = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
if let dateComponents = calendar?.components([.Year, .Month, .Day], fromDate: currentDate) {
dateComponents.year = dateComponents.year - yearsAgo
let date = calendar?.dateFromComponents(dateComponents)
return date
}
return nil
}
}
| mit | f448b2b9f1132ce965615970862c9920 | 30.783217 | 109 | 0.717052 | 5.055617 | false | false | false | false |
russellladd/MichiganPeople | MichiganPeople/SearchViewController.swift | 1 | 3522 | //
// MasterViewController.swift
// MichiganPeople
//
// Created by Russell Ladd on 8/14/14.
// Copyright (c) 2014 GRL5. All rights reserved.
//
import UIKit
import Wolverine
class SearchViewController: UITableViewController, ServiceManagerDelegate {
let serviceManager: ServiceManager
var personArrayResults: PersonArrayResult? {
didSet {
tableView.reloadData()
}
}
var personResults: [PersonResult]? {
get {
if let personArrayResults = personArrayResults {
switch personArrayResults {
case .Success(let personResults):
return personResults
default:
return nil
}
} else {
return nil
}
}
}
// MARK: - View
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.text = NSLocalizedString("Could not connect to database.", comment: "Service not connected")
//label.hidden =
}
// MARK: - Initialization
required init(coder aDecoder: NSCoder) {
serviceManager = ServiceManager(credential: Credential(key: "Wijw6wNYqffL0_ZnLOW9HemfEf8a", secret: "hjUuNq2CqsjchshuVsGnJs5Kenca"))
super.init(coder: aDecoder)
serviceManager.delegate = self
}
// MARK: - Service manager delegate
func serviceManager(serviceManager: ServiceManager, didChangeStatus status: ServiceManager.Status) {
switch status {
case .Connecting:
()
case .Connected(let service):
service.getPeopleForSearchString("Russell") { personArrayResults in
self.personArrayResults = personArrayResults
}
case .NotConnected(let error):
println(error)
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPerson" {
let indexPath = self.tableView.indexPathForSelectedRow()!
let personResult = personResults![indexPath.row]
let controller = (segue.destinationViewController as UINavigationController).topViewController as PersonViewController
controller.personResult = personResult
controller.navigationItem.leftBarButtonItem = self.splitViewController!.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
// MARK: - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personResults?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Person Cell", forIndexPath: indexPath) as UITableViewCell
let personResult = personResults![indexPath.row];
switch personResult {
case .Success(let person):
cell.textLabel!.text = person.displayName
case .Error(let error):
cell.textLabel!.text = error.description
}
return cell
}
}
| mit | 32b6f3842e059807a09d88581307314f | 29.362069 | 140 | 0.604486 | 5.49454 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/Views/CustomRoundedRectangle.swift | 1 | 2889 | //
// CustomRoundedRectangle.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-05.
//
// Original solution by @kontiki at:
// https://stackoverflow.com/questions/56760335/round-specific-corners-swiftui
//
import SwiftUI
/**
This shape is a rounded rectangle where every corner can be
given a custom corner radius.
The shape is internal, since it's just an internal tool. It
is not a public part of KeyboardKit.
*/
struct CustomRoundedRectangle: Shape {
init(
topLeft: CGFloat = 0.0,
topRight: CGFloat = 0.0,
bottomLeft: CGFloat = 0.0,
bottomRight: CGFloat = 0.0) {
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
}
private let topLeft: CGFloat
private let topRight: CGFloat
private let bottomLeft: CGFloat
private let bottomRight: CGFloat
func path(in rect: CGRect) -> Path {
var path = Path()
guard rect.isValidForPath else { return path }
let width = rect.size.width
let height = rect.size.height
let topLeft = min(min(self.topLeft, height/2), width/2)
let topRight = min(min(self.topRight, height/2), width/2)
let bottomLeft = min(min(self.bottomLeft, height/2), width/2)
let bottomRight = min(min(self.bottomRight, height/2), width/2)
path.move(to: CGPoint(x: width / 2.0, y: 0))
path.addLine(to: CGPoint(x: width - topRight, y: 0))
path.addArc(center: CGPoint(x: width - topRight, y: topRight), radius: topRight,
startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
path.addLine(to: CGPoint(x: width, y: height - bottomRight))
path.addArc(center: CGPoint(x: width - bottomRight, y: height - bottomRight), radius: bottomRight,
startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
path.addLine(to: CGPoint(x: bottomLeft, y: height))
path.addArc(center: CGPoint(x: bottomLeft, y: height - bottomLeft), radius: bottomLeft,
startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
path.addLine(to: CGPoint(x: 0, y: topLeft))
path.addArc(center: CGPoint(x: topLeft, y: topLeft), radius: topLeft,
startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
return path
}
}
struct CustomRoundedRectangle_Previews: PreviewProvider {
static var previews: some View {
CustomRoundedRectangle(topLeft: 10, topRight: 20, bottomLeft: 30, bottomRight: 40)
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
.padding()
.background(Color.red)
.frame(width: 200, height: 200)
}
}
| mit | 8a937a78db9eb3cf24c35b059120188b | 37.52 | 106 | 0.632745 | 4.092068 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDK/DataArchiving/SBADemographicDataConverter.swift | 1 | 7044 | //
// SBADemographicDataConverter.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. 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(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
// ===== WORK IN PROGRESS =====
// TODO: WIP syoung 12/06/2016 This is unfinished but b/c it is wrapped up with the profile
// and onboarding stuff, I don't want the branch lingering unmerged. This is ported from
// AppCore and is still untested and *not* intended for production use.
// ============================
/**
Data converter to use as a factory for converting objects to to an archivable object
for upload or saving to user defaults.
*/
public protocol SBADemographicDataConverter {
/**
Key/Value pair to insert into a dictionary for upload.
*/
func uploadObject(for identifier: SBADemographicDataIdentifier) -> SBAAnswerKeyAndValue?
}
/**
Demographics converter for shared key/value pairs included in the base implementation.
*/
public protocol SBABaseDemographicsUtility {
var birthdate: Date? { get }
var gender: HKBiologicalSex? { get }
var height: HKQuantity? { get }
var weight: HKQuantity? { get }
var wakeTime: DateComponents? { get }
var sleepTime: DateComponents? { get }
}
extension SBABaseDemographicsUtility {
public func demographicsValue(for identifier: SBADemographicDataIdentifier) -> NSSecureCoding? {
if identifier == SBADemographicDataIdentifier.currentAge,
let currentAge = self.birthdate?.currentAge() {
return NSNumber(value:currentAge)
}
else if identifier == SBADemographicDataIdentifier.biologicalSex {
return self.gender?.demographicDataValue
}
else if identifier == SBADemographicDataIdentifier.heightInches,
let quantity = quantityValue(for: self.height, with: HKUnit(from: .inch)) {
return quantity
}
else if identifier == SBADemographicDataIdentifier.weightPounds,
let quantity = quantityValue(for: self.weight, with: HKUnit(from: .pound)) {
return quantity
}
else if identifier == SBADemographicDataIdentifier.wakeUpTime {
return jsonTimeOfDay(for: self.wakeTime)
}
else if identifier == SBADemographicDataIdentifier.sleepTime {
return jsonTimeOfDay(for: self.sleepTime)
}
return nil
}
public func jsonTimeOfDay(for dateComponents: DateComponents?) -> NSSecureCoding? {
guard let dateComponents = dateComponents else { return nil }
var time = dateComponents
time.day = 0
time.month = 0
time.year = 0
return (time as NSDateComponents).jsonObject()
}
public func quantityValue(for quantity: HKQuantity?, with unit:HKUnit) -> NSNumber? {
guard let quantity = quantity, quantity.is(compatibleWith: unit)
else {
return nil
}
return NSNumber(value: quantity.doubleValue(for: unit))
}
}
/**
Demographic Data converter to use as a factory for converting from a task/result pairing to
to an archivable object for upload or saving to user defaults.
*/
@objc
open class SBADemographicDataTaskConverter: NSObject, SBADemographicDataConverter, SBAResearchKitResultConverter, SBABaseDemographicsUtility {
let results: [ORKStepResult]
public var answerFormatFinder: SBAAnswerFormatFinder? {
return _answerFormatFinder
}
let _answerFormatFinder: SBAAnswerFormatFinder
public init(answerFormatFinder: SBAAnswerFormatFinder, results: [ORKStepResult]) {
self.results = results
self._answerFormatFinder = answerFormatFinder
super.init()
}
public convenience init(answerFormatFinder: SBAAnswerFormatFinder, taskResult: ORKTaskResult) {
self.init(answerFormatFinder: answerFormatFinder, results: taskResult.consolidatedResults())
}
open func uploadObject(for identifier:SBADemographicDataIdentifier) -> SBAAnswerKeyAndValue? {
if let valueOnly = demographicsValue(for: identifier) {
return SBAAnswerKeyAndValue(key: identifier.rawValue, value: valueOnly, questionType: .none)
}
else if let profileResult = findResult(for: identifier.rawValue) as? ORKQuestionResult,
let answer = profileResult.jsonSerializedAnswer() {
let result = SBAAnswerKeyAndValue(key: identifier.rawValue, value: answer.value, questionType: answer.questionType)
result.unit = answer.unit
return result
}
return nil
}
/**
Return the result to be used for setting values in a profile. Allow override. Default implementation
iterates through the `ORKStepResult` objects until an `ORKResult` is found with a matching identifier.
@return Result for the given identifier
*/
open func findResult(for identifier:String) -> ORKResult? {
for stepResult in results {
if let profileResult = stepResult.result(forIdentifier: identifier) {
return profileResult
}
}
return nil
}
}
extension HKBiologicalSex {
public var demographicDataValue: NSString? {
switch (self) {
case .female:
return "Female"
case .male:
return "Male"
case .other:
return "Other"
default:
return nil
}
}
}
| bsd-3-clause | d196ff73e3ecb12f35f33197a6fb848d | 38.346369 | 142 | 0.694306 | 4.76845 | false | false | false | false |
wangzheng0822/algo | swift/12_sorts/QuickSort.swift | 1 | 1120 | //
// QuickSort.swift
// algo
//
// Created by Wenru Dong on 2018/10/17.
// Copyright © 2018年 Wenru Dong. All rights reserved.
//
import Foundation
public func quickSort<T: RandomAccessCollection & MutableCollection>(_ a: inout T) where T.Element: Comparable {
quickSort(&a, from: a.startIndex, to: a.index(before: a.endIndex))
}
fileprivate func quickSort<T: RandomAccessCollection & MutableCollection>(_ a: inout T, from low: T.Index, to high: T.Index) where T.Element: Comparable {
if low >= high { return }
let m = partition(&a, from: low, to: high)
quickSort(&a, from: low, to: a.index(before: m))
quickSort(&a, from: a.index(after: m), to: high)
}
fileprivate func partition<T: RandomAccessCollection & MutableCollection>(_ a: inout T, from low: T.Index, to high: T.Index) -> T.Index where T.Element: Comparable {
let pivot = a[low]
var j = low
var i = a.index(after: low)
while i <= high {
if a[i] < pivot {
a.formIndex(after: &j)
a.swapAt(i, j)
}
a.formIndex(after: &i)
}
a.swapAt(low, j)
return j
}
| apache-2.0 | f0647ac05894c45d03dae9140f836306 | 30.027778 | 165 | 0.63026 | 3.374622 | false | false | false | false |
kgellci/QuickTable | QuickTable/Classes/QuickRow.swift | 1 | 3166 | //
// QuickRow.swift
// Pods
//
// Created by Kris Gellci on 5/11/17.
//
//
import UIKit
/// Called passing in the UITableViewCell for setup of the cell.
public typealias QuickRowStyleBlock = (UITableViewCell) -> Void
/// Called when a UITableViewCell is tapped by the user. Returns if the cell should auto deselect
public typealias QuickRowSelectionBlock = (UITableViewCell) -> Bool
/// Called to allow for custom height compution before a UITableViewCell is displayed. Returns the computed height.
public typealias QuickRowComputeHeightBlock = (QuickRow) -> CGFloat
/// The data used by any subclass of QuickSectionBase to define the UITableViewCells which will be displayed
public class QuickRow {
/// Used in dequeueReusableCellWithIdentifier on UITableView
private var reuseIdentifier: String
/// executed when the UITableViewCell needs to be setup for display
public var styleBlock: QuickRowStyleBlock?
/// executed when the user taps a UITableViewCell
public var selectionBlock: QuickRowSelectionBlock?
/// The selection style for UITableViewCell
public var selectionStyle: UITableViewCellSelectionStyle = .default
/// The preComputed row height
public var computeRowHeightBlock: QuickRowComputeHeightBlock?
/// A convenient way to initialize a QuickRow with common params
/// - Parameter reuseIdentifier: The reuse identifier for the UITableViewCell, will later be used in dequeueReusableCellWithIdentifier on UITableView.
/// - Parameter styleBlock: The block used to setup the UITableViewCell before it is displayed
public init(reuseIdentifier: String, styleBlock: QuickRowStyleBlock?) {
self.reuseIdentifier = reuseIdentifier
self.styleBlock = styleBlock
}
/// A convenient way to initialize a QuickRow with common params
/// - Parameter reuseIdentifier: The reuse identifier for the UITableViewCell, will later be used in dequeueReusableCellWithIdentifier on UITableView.
/// - Parameter styleBlock: The block used to setup the UITableViewCell before it is displayed
/// - Parameter selectionBlock: The block which is executed when the user taps on a UITableViewCell
public init(reuseIdentifier: String, styleBlock: QuickRowStyleBlock?, selectionBlock: QuickRowSelectionBlock?) {
self.reuseIdentifier = reuseIdentifier
self.styleBlock = styleBlock
self.selectionBlock = selectionBlock
}
/// Used by the UITableView to retrieve the cell
/// - Parameter tableView: The UITableView which will display the cell
/// - Returns: The UITableViewCell for display
func cellForTableView(_ tableView: UITableView) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)!
}
/// The height of the UITableViewCell to be displayed
/// - Returns: the height of the UItableViewCell, default is UITableViewAutomaticDimension
func height() -> CGFloat {
if let computeRowHeightBlock = computeRowHeightBlock {
return computeRowHeightBlock(self)
}
return UITableViewAutomaticDimension
}
}
| mit | 04d93492777df5ba881dd85a7dcf42a2 | 44.228571 | 154 | 0.743525 | 5.59364 | false | false | false | false |
mcrollin/safecaster | safecaster/SCRImport.swift | 1 | 11882 | //
// SCRImport.swift
// safecaster
//
// Created by Marc Rollin on 3/25/15.
// Copyright (c) 2015 safecast. All rights reserved.
//
import UIKit
import Foundation
import CoreData
import Alamofire
import ObjectMapper
import ReactiveCocoa
enum SCRImportProgress {
case Uploaded
case Processed
case MetadataAdded
case Submitted
case Approved
case Rejected
case Live
}
@objc(SCRImport)
class SCRImport: NSManagedObject, Mappable {
@NSManaged var approved: Bool
@NSManaged var cities: String?
@NSManaged var createdAt: NSDate
@NSManaged var credits: String?
@NSManaged var details: String?
@NSManaged var height: String?
@NSManaged var id: NSNumber
@NSManaged var lineCount: NSNumber
@NSManaged var mapId: NSNumber
@NSManaged var md5sum: String?
@NSManaged var measurementCount: NSNumber
@NSManaged var name: String?
@NSManaged var orientation: String?
@NSManaged var source: String?
@NSManaged var status: String?
@NSManaged var statusComputeLocation: Bool
@NSManaged var statusCreateMap: Bool
@NSManaged var statusImportLogs: Bool
@NSManaged var statusMeasurementsAdded: Bool
@NSManaged var statusProcessFile: Bool
@NSManaged var updatedAt: NSDate
@NSManaged var userId: NSNumber
@NSManaged var deletedOnAPI: Bool
convenience required init?(_ map: Map) {
self.init(entity: SCRImport.entity(SCRImport.context()), insertIntoManagedObjectContext: nil)
mapping(map)
}
override var description: String {
return "\(id) - \(name): \(approved) (\(credits) in \(cities))"
}
var hasAction: Bool {
switch progress() {
case .Uploaded:
return true
case .Processed:
return true
case .MetadataAdded:
return true
default:
return false
}
}
var actionName: String {
switch progress() {
case .Uploaded:
return "Update status"
case .Processed:
return "Fill in metadata"
case .MetadataAdded:
return "Submit for approval"
case .Submitted:
return "Awaiting for approval"
case .Rejected:
return "Your import has been rejected"
default:
return "Thank you!"
}
}
var fullDetails: String {
if let cities = cities,
let credits = credits {
return (credits + " in " + cities
+ (details != nil ? "\n" + details! : ""))
}
return details ?? ""
}
static func newInstance(map: Map) -> Mappable? {
return SCRImport(entity: SCRImport.entity(SCRImport.context()), insertIntoManagedObjectContext: nil)
}
func mapping(map: Map) {
id <- map["id"]
userId <- map["user_id"]
name <- map["name"]
createdAt <- (map["created_at"], SCRUTCDateFormatTransform())
updatedAt <- (map["updated_at"], SCRUTCDateFormatTransform())
measurementCount <- map["measurements_count"]
lineCount <- map["lines_count"]
source <- map["source.url"]
status <- map["status"]
statusProcessFile <- map["status_details.process_file"]
statusImportLogs <- map["status_details.import_bgeigie_logs"]
statusComputeLocation <- map["status_details.compute_latlng"]
statusCreateMap <- map["status_details.create_map"]
statusMeasurementsAdded <- map["status_details.measurements_added"]
approved <- map["approved"]
mapId <- map["map_id"]
height <- map["height"]
orientation <- map["orientation"]
cities <- map["cities"]
credits <- map["credits"]
details <- map["description"]
md5sum <- map["md5sum"]
}
func progress() -> SCRImportProgress {
if (!self.statusProcessFile || !self.statusImportLogs) {
return .Uploaded
} else if (self.cities == nil || self.credits == nil) {
return .Processed
} else if (self.status == "processed") {
return .MetadataAdded
} else if (self.status == "submitted") {
return .Submitted
} else if (self.approved && !self.statusMeasurementsAdded) {
return .Approved
} else if (!self.approved) {
return .Rejected
}
return .Live
}
}
extension SCRImport {
func actionSignal() -> RACSignal! {
switch progress() {
case .Uploaded:
return SCRUserManager.sharedManager.updateImports()
case .Processed:
return editImportMetadataSignal()
case .MetadataAdded:
return submitImportSignal()
default:
log("Error: no action for progress \(progress())")
}
return RACSignal.empty()
}
private func sendRequest(request: URLRequestConvertible) -> RACSignal! {
return RACSignal.createSignal { subscriber in
let delegate = Alamofire.Manager.sharedInstance.delegate
// Disable HTTP Redirection
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
return SCRSafecastAPIRouter.Import(self.id.integerValue).URLRequest
}
Alamofire.request(request)
.responseJSON { _, _, result in
log("RESULT \(result)")
if result.isFailure {
subscriber.sendError(result.error as! NSError)
} else {
let logImport = Mapper<SCRImport>().map(result.value)
log("IMPORT \(logImport)")
subscriber.sendNext(logImport)
subscriber.sendCompleted()
}
}
return nil
}
}
private func editImportMetadataSignal() -> RACSignal! {
let user = SCRUserManager.sharedManager.user!
let key = user.token!
let request = SCRSafecastAPIRouter.EditImportMetadata(id.integerValue, key, user.name, "titi")
return self.sendRequest(request)
}
private func submitImportSignal() -> RACSignal! {
let key = SCRUserManager.sharedManager.user!.token!
let request = SCRSafecastAPIRouter.SubmitImport(id.integerValue, key)
return self.sendRequest(request)
}
}
// MARK: - Class Methods
extension SCRImport {
class func entityName () -> String {
return "SCRImport"
}
class func entity(managedObjectContext: NSManagedObjectContext!) -> NSEntityDescription! {
return NSEntityDescription.entityForName(entityName(), inManagedObjectContext: managedObjectContext)
}
private class func getByPage(userId: Int, page: Int = 1, collection: [[String : AnyObject]] = [],
success: (([[String : AnyObject]]) -> Void)?, failure: ((ErrorType) -> Void)?) {
SCRNetworkActivityManager.sharedManager.start()
Alamofire.request(SCRSafecastAPIRouter.Imports(userId, page))
.validate()
.responseJSON { _, _, result in
SCRNetworkActivityManager.sharedManager.stop()
if let newCollection = result.value as? [[String : AnyObject]] {
if newCollection.count > 0 {
return self.getByPage(userId, page: page + 1, collection: collection + newCollection, success: success, failure: failure)
} else {
success?(collection)
}
}
}
}
private class func getAll(userId: Int, success: (([[String : AnyObject]]) -> Void)?, failure: ((ErrorType) -> Void)?) {
SCRNetworkActivityManager.sharedManager.start()
getByPage(userId, success: { (collection: [[String : AnyObject]]) -> Void in
SCRNetworkActivityManager.sharedManager.stop()
success?(collection)
}, failure: { (error: ErrorType) -> Void in
SCRNetworkActivityManager.sharedManager.stop()
failure?(error)
})
}
private class func findById(id:NSNumber) -> SCRImport? {
let request = NSFetchRequest(entityName: entityName())
request.fetchLimit = 1
request.predicate = NSPredicate(format: "id = %@ AND deletedOnAPI = %@", id, false)
do {
let result = try context().executeFetchRequest(request) as? [SCRImport]
return result?.count > 0 ? result?.first : nil
} catch {
log(error)
}
return nil
}
private class func findOne(ascending:Bool = true) -> SCRImport? {
let request = NSFetchRequest(entityName: entityName())
request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: ascending)]
request.predicate = NSPredicate(format: "deletedOnAPI = %@", false)
request.fetchLimit = 1
do {
let result = try context().executeFetchRequest(request) as? [SCRImport]
return result?.count > 0 ? result?.first : nil
} catch {
log(error)
}
return nil
}
class func findLast() -> SCRImport? {
return findOne(false)
}
class func findAll(ascending:Bool = true) -> [SCRImport] {
let request = NSFetchRequest(entityName: entityName())
request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: ascending)]
request.predicate = NSPredicate(format: "deletedOnAPI = %@", false)
do {
let results = try context().executeFetchRequest(request) as! [SCRImport]
return results ?? []
} catch {
log(error)
}
return []
}
class func update(userId: Int, success: (([SCRImport]) -> Void)?, failure: ((ErrorType) -> Void)?) {
self.getAll(userId, success: { (logImports: [[String : AnyObject]]) in
// Flag all imports as deletedOnAPI
for logImport in self.findAll() {
logImport.deletedOnAPI = true
}
// Replacing them by the newly retrieved one
for map in logImports {
// Update and unflag
if let logImport = self.findById((map["id"] as? NSNumber)!) {
logImport.deletedOnAPI = false
Mapper<SCRImport>().map(map, toObject: logImport)
} else { // Add if does not exists
let logImport = Mapper<SCRImport>().map(map)
if let logImport = logImport {
self.context().insertObject(logImport)
}
}
}
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
success?(self.findAll())
}, failure: { (error: ErrorType) in
self.context().rollback()
failure?(error)
})
}
} | cc0-1.0 | 37909aa2f1a7728cd7538d659d3d84bd | 33.847507 | 149 | 0.54166 | 5.229754 | false | false | false | false |
shuuchen/SwiftTips | closure.swift | 1 | 3164 | // closures
// sort an array using sort()
let arr = ["a", "b", "c"]
(String, String) -> (Bool)
// using normal function
func backwards(str1: String, str2: String) -> Bool {
return str1 > str2
}
arr.sort(backwards)
// using closure expression syntax
+++++++++++++++++++++++++++++++++++++
general form
{ (parameters) -> return type in
statements
}
+++++++++++++++++++++++++++++++++++++
* parameters can be constants, variables, inout
arr.sort({ (str1: String, str2: String) -> Bool in
return str1 > str2
})
// written in one line is OK
arr.sort({ (str1: String, str2: String) -> Bool in return str1 > str2})
// the types of parameters & return values can be inferred
// thus needless to specify
arr.sort({str1, str2 in return str1 > str2})
// single expression closure can return implicitly
// thus return can be omitted
arr.sort({str1, str2 in str1 > str2})
// swift provides shorthand argument names: $0, $1, $2...
// argument list can be omitted
arr.sort({ $0 > $1 })
// using string-specific implementation of ">" operator
arr.sort(>)
// trailing closures
// if the closure is passed as final argument
arr.sort() { $0 > $1 }
var a = [1, 2, 3, 4, 5]
// sort
// trailing closure
a.sort() { $0 > $1 }
// "()" can be omitted if closure is the only argument
a.sort { $0 < $1 }
// map
let m = [0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]
let mm = a.map {
n -> String in
return m[n]! // may be nil, thus force-unwrap is necessary
}
let mmm = a.map { m[$0]! }
mmm
// capturing values
// ...
// closures are reference types
// escaping & nonescaping closure
// when a closure is passed to a function
// escaping closure is called after function returned
func someFunctionWithNoescapeClosure(@noescape closure: () -> Void) {
closure()
}
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: () -> Void) {
completionHandlers.append(completionHandler)
}
class SomeClass {
var x = 10
func doSomething() {
someFunctionWithEscapingClosure { self.x = 100 }
someFunctionWithNoescapeClosure { x = 200 }
}
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
completionHandlers.first?()
print(instance.x)
// auto closure
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
let customerProvider = { customersInLine.removeAtIndex(0) }
print(customersInLine.count)
print("Now serving \(customerProvider())!")
print(customersInLine.count)
// pass a closure to a fucntion
func serveCustomer(customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serveCustomer { customersInLine.removeAtIndex(0) } // the type of the closure is () -> String
// using @autoclosure
func serveCustomer(@autoclosure customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
// single expression
// no argument
serveCustomer(customersInLine.removeAtIndex(0))
| mit | 104864f221308d7e2ff36fda607bffa0 | 21.6 | 93 | 0.625158 | 3.784689 | false | false | false | false |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Segmented Control/BorderLessSegmentedControl.swift | 1 | 2978 | //
// BorderLessSegmentedControl.swift
// Pods
//
// Created by Incubasys on 09/08/2017.
//
//
import UIKit
public class BorderLessSegmentedControl: UISegmentedControl {
// @IBInspectable public var isLightBackground: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
override init(items: [Any]?) {
super.init(items: items)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override func awakeFromNib() {
setup()
}
//setup
func setup() {
var normalTextColor: UIColor!
// if isLightBackground{
normalTextColor = UIColor.appColor(color: .DarkText)
// }else{
// normalTextColor = UIColor.appColor(color: .LightText)
// }
sharpCornersStyle(normalBackgroudColor: UIColor.white, selectedBackggroundColor: UIColor.appColor(color: .Primary), tintColor: UIColor.appColor(color: .Primary), normalTextColor: normalTextColor, selectedTextColor: UIColor.appColor(color: .Light))
}
func sharpCornersStyle(normalBackgroudColor:UIColor,selectedBackggroundColor:UIColor,tintColor:UIColor,normalTextColor: UIColor, selectedTextColor:UIColor) {
let img = UIImage.getImageFromColor(color: normalBackgroudColor, size: CGSize(width: 200, height: 200))
self.setBackgroundImage(img, for: UIControlState.normal, barMetrics: .default)
let imgFocused = UIImage.getImageFromColor(color: selectedBackggroundColor.withAlphaComponent(0.2), size: CGSize(width: 200, height: 200))
// setBackgroundImage(imgFocused, for: .focused, barMetrics: .default)
setBackgroundImage(imgFocused, for: .highlighted, barMetrics: .default)
// setBackgroundImage(img, for: ., barMetrics: <#T##UIBarMetrics#>)
self.setBackgroundImage(UIImage.getImageFromColor(color: selectedBackggroundColor, size: CGSize(width: 200, height: 200)), for: UIControlState.selected, barMetrics: .default)
self.tintColor = tintColor
let img2 = UIImage.getImageFromColor(color: selectedBackggroundColor, size: CGSize(width: 1, height: self.frame.size.height))
self.setDividerImage(img2, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
let titleTextAttributes = [NSForegroundColorAttributeName: selectedTextColor]
let normalTitleTextAttributes = [NSForegroundColorAttributeName: normalTextColor]
self.setTitleTextAttributes(titleTextAttributes, for: .selected)
self.setTitleTextAttributes(normalTitleTextAttributes, for: .normal)
self.backgroundColor = normalBackgroudColor
self.layer.borderWidth = 0
self.layer.cornerRadius = 0
self.layer.borderColor = selectedBackggroundColor.cgColor
}
}
| mit | a933bbb84a4f8ec0b579ce65a1dec38f | 37.675325 | 255 | 0.682673 | 4.749601 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor TableView CellView Items/PayloadCellViewItemTextView.swift | 1 | 2603 | //
// PayloadCellViewItemTextView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class EditorTextView {
class func scrollView(string: String?,
visibleRows: Int,
constraints: inout [NSLayoutConstraint],
cellView: PayloadCellView & NSTextViewDelegate) -> OverlayScrollView {
let scrollView = OverlayScrollView(frame: NSRect.zero)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.hasVerticalScroller = true
scrollView.verticalScroller = OverlayScroller()
scrollView.borderType = .bezelBorder
let textView = PayloadTextView()
textView.minSize = NSSize(width: 0, height: 0)
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
textView.drawsBackground = false
textView.isEditable = true
textView.isSelectable = true
textView.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .regular))
textView.textColor = .labelColor
textView.delegate = cellView
textView.string = string ?? ""
// Use old resizing masks until I know how to replicate with AutoLayout.
textView.autoresizingMask = .width
textView.textContainer?.containerSize = NSSize(width: scrollView.contentSize.width, height: CGFloat.greatestFiniteMagnitude)
textView.textContainer?.heightTracksTextView = false
// Add TextView to ScrollView
scrollView.documentView = textView
cellView.addSubview(scrollView)
let heightMultiplier: Int
if visibleRows < 2 {
heightMultiplier = 2
} else {
heightMultiplier = visibleRows
}
let scrollViewHeight = CGFloat(20 + (17 * (heightMultiplier - 1)))
cellView.updateHeight(scrollViewHeight)
// Height
constraints.append(NSLayoutConstraint(item: scrollView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: scrollViewHeight))
return scrollView
}
}
| mit | 09c8e3a1a9a45baa6024203d4080871e | 36.710145 | 132 | 0.602229 | 6.180523 | false | false | false | false |
BetterWorks/Mention | Pod/Classes/AttributedTextContainingView.swift | 2 | 4438 | //
// AttributedTextContainingView.swift
// Pods
//
// Created by Connor Smith on 12/10/15.
// Copyright (c) 2015 BetterWorks. https://www.betterworks.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.
// MARK: AttributedTextContainingView
/**
* AttributedTextContainingView provides a single interface for text-containing views
*/
public protocol AttributedTextContainingView: CharacterFinder {
var m_text: String { get }
var m_attributedText: NSAttributedString? { get set }
var m_font: UIFont { get }
var m_textColor: UIColor { get }
}
// MARK: - ComposableAttributedTextContainingView
/**
* ComposableAttributedTextContainingView provides a single interface for composable text-containing views
*/
public protocol ComposableAttributedTextContainingView: AttributedTextContainingView, UITextInputTraits, UITextInput {
var m_typingAttributes: [String : AnyObject]? { get set }
}
// MARK: - AttributedTextContainingView Extension
extension AttributedTextContainingView {
mutating func configureDefaultAttributedText() {
m_attributedText = m_attributedText ?? defaultAttributedText
}
var defaultAttributedText: NSAttributedString {
return NSAttributedString(string: m_text, attributes: [NSFontAttributeName : m_font, NSForegroundColorAttributeName : m_textColor])
}
}
// MARK: - UILabel
extension UILabel: AttributedTextContainingView {
public var m_text: String {
get {
return text ?? ""
}
}
public var m_attributedText: NSAttributedString? {
set {
attributedText = newValue
}
get {
return attributedText
}
}
public var m_font: UIFont {
return font
}
public var m_textColor: UIColor {
return textColor
}
}
// MARK: - UITextField
extension UITextField: ComposableAttributedTextContainingView {
public var m_text: String {
get {
return self.text ?? ""
}
}
public var m_attributedText: NSAttributedString? {
set {
self.attributedText = newValue
}
get {
return self.attributedText
}
}
public var m_font: UIFont {
return font ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
}
public var m_textColor: UIColor {
return textColor ?? UIColor.darkTextColor()
}
public var m_typingAttributes: [String : AnyObject]? {
get {
return typingAttributes
}
set {
typingAttributes = newValue
}
}
}
// MARK: - UITextView
extension UITextView: ComposableAttributedTextContainingView {
public var m_text: String {
get {
return self.text ?? ""
}
}
public var m_attributedText: NSAttributedString? {
set {
self.attributedText = newValue
}
get {
return self.attributedText
}
}
public var m_font: UIFont {
return font ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
}
public var m_textColor: UIColor {
return textColor ?? UIColor.darkTextColor()
}
public var m_typingAttributes: [String : AnyObject]? {
get {
return typingAttributes
}
set {
typingAttributes = newValue ?? [String : AnyObject]()
}
}
}
| mit | 5d821e6754ecf8ea8895dd91eec0c4ea | 27.267516 | 139 | 0.661785 | 4.839695 | false | false | false | false |
jessesquires/swift-proposal-analyzer | page-generator/main.swift | 1 | 2498 | #!/usr/bin/swift
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// GitHub
// https://github.com/jessesquires/swift-proposal-analyzer
//
//
// License
// Copyright © 2016 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
print("Generating playground pages from proposals...")
func proposalFiles(inDirectory directory: URL) -> [URL : String] {
let fm = FileManager.default
let proposalNames = try! fm.contentsOfDirectory(atPath: directory.path)
var proposals = [URL : String]()
for eachName in proposalNames {
let url = directory.appendingPathComponent(eachName)
let fileContents = try! String(contentsOf: url, encoding: String.Encoding.utf8)
proposals[url] = fileContents
}
return proposals
}
if #available(OSX 10.11, *) {
let process = Process()
let currentDir = URL(fileURLWithPath: process.currentDirectoryPath)
let proposalDir = currentDir
.appendingPathComponent("swift-evolution", isDirectory: true)
.appendingPathComponent("proposals", isDirectory: true)
let basePlaygroundDir = currentDir
.appendingPathComponent("swift-proposal-analyzer.playground", isDirectory: true)
.appendingPathComponent("Pages", isDirectory: true)
let proposals = proposalFiles(inDirectory: proposalDir)
let fm = FileManager.default
for (url, contents) in proposals {
let path = url.lastPathComponent
let range = path.index(path.startIndex, offsetBy: 4)
let seNumber = "SE-" + path[..<range]
let pageDir = basePlaygroundDir
.appendingPathComponent(seNumber + ".xcplaygroundpage", isDirectory: true)
try! fm.createDirectory(at: pageDir, withIntermediateDirectories: true, attributes: nil)
let pageFile = pageDir
.appendingPathComponent("Contents", isDirectory: false)
.appendingPathExtension("swift")
let pageContents = "/*:\n"
+ contents
+ "\n\n----------\n\n"
+ "[Previous](@previous) | [Next](@next)\n"
+ "*/\n"
let pageData = pageContents.data(using: .utf8)
let success = fm.createFile(atPath: pageFile.path, contents: pageData, attributes: nil)
if !success {
print("** Error: failed to generate playground page for " + seNumber)
}
}
} else {
print("** Error: Must use OSX 10.11 or higher.")
}
print("Done! 🎉")
| mit | d7c109a538422fa89a69b8d125e5bcb5 | 30.175 | 96 | 0.653569 | 4.314879 | false | false | false | false |
Pargi/Pargi-iOS | Pargi/UI/RoundedButton.swift | 1 | 1167 | //
// RoundedButton.swift
// Pargi
//
// Created by Henri Normak on 29/04/2017.
// Copyright © 2017 Henri Normak. All rights reserved.
//
import UIKit
@IBDesignable class RoundedButton: UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
self.layer.borderWidth = newValue
}
get {
return self.layer.borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
set {
self.layer.borderColor = newValue?.cgColor
}
get {
if let color = self.layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
self.layer.cornerRadius = newValue
}
get {
return self.layer.cornerRadius
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.clipsToBounds = true
}
}
| mit | 2d9ed12abb30548be9967a7f6bbd810c | 20.2 | 55 | 0.524014 | 4.818182 | false | false | false | false |
Tyrant2013/LeetCodePractice | LeetCodePractice/Easy/83_Remove_Duplicates_From_Sorted_List.swift | 1 | 1304 | //
// Remove Duplicates From Sorted List.swift
// LeetCodePractice
//
// Created by 庄晓伟 on 2018/2/22.
// Copyright © 2018年 Zhuang Xiaowei. All rights reserved.
//
import UIKit
class Remove_Duplicates_From_Sorted_List: Solution {
override func ExampleTest() {
let first = ListNode(1)
first.next = ListNode(2)
first.next?.next = ListNode(4)
self.showList(first)
self.showList(self.deleteDuplicates(first))
let sec = ListNode(1)
sec.next = ListNode(1)
sec.next?.next = ListNode(1)
sec.next?.next?.next = ListNode(2)
sec.next?.next?.next?.next = ListNode(1)
self.showList(sec)
self.showList(self.deleteDuplicates(sec))
}
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
if head == nil {
return head
}
var eles = [Int : Int]()
eles[(head?.val)!] = 0
var index = head?.next
var pre = head
while index != nil {
if eles[(index?.val)!] != nil {
pre?.next = index?.next
}
else {
eles[(index?.val)!] = 0
pre = index
}
index = index?.next
}
return head
}
}
| mit | 94a777a090d47147ee4f4674c777549c | 24.392157 | 59 | 0.511197 | 4.009288 | false | false | false | false |
jemmons/Medea | Tests/MedeaTests/JSONArrayTests.swift | 1 | 3317 | import XCTest
import Medea
class JSONArrayTests: XCTestCase {
func testRawArray() {
let subject = try! JSONHelper.jsonArray(from: "[\"foo\", \"bar\"]")
XCTAssertEqual(subject as! [String], ["foo", "bar"])
}
func testRawJSONObject() {
let shouldThrow = expectation(description: "throws notJSONArray error")
do {
let _ = try JSONHelper.jsonArray(from: "{\"foo\": \"bar\"}")
} catch JSONError.unexpectedType {
shouldThrow.fulfill()
} catch {}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testInvalidRawJSON() {
let shouldThrow = expectation(description: "does not parse")
do {
let _ = try JSONHelper.jsonArray(from: "foobarbaz")
} catch JSONError.malformed {
shouldThrow.fulfill()
} catch {}
waitForExpectations(timeout: 0.1, handler: nil)
}
func testInvalidByOmission() {
let shouldThrow = expectation(description: "does not parse")
do {
let _ = try JSONHelper.jsonArray(from: "")
} catch JSONError.malformed {
shouldThrow.fulfill()
} catch {}
waitForExpectations(timeout: 0.1, handler: nil)
}
func testEmptyRawJSON() {
let subject = try! JSONHelper.jsonArray(from: "[]")
XCTAssert(subject.isEmpty)
}
func testJSONArray() {
let subject = try! JSONHelper.string(from: ["foo", "bar"])
XCTAssertEqual(subject, "[\"foo\",\"bar\"]")
}
func testValidJSONArray() {
let subject = try! ValidJSONArray(["foo", "bar"])
let array = JSONHelper.string(from: subject)
XCTAssertEqual(array, "[\"foo\",\"bar\"]")
}
func testInvaidJSONArray() {
let shouldThrow = expectation(description: "invalid json array")
do {
let _ = try JSONHelper.string(from: [Date(), Date()])
} catch JSONError.invalidType {
shouldThrow.fulfill()
} catch {}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testEmptyJSONArray() {
let subject = try! JSONHelper.string(from: [])
XCTAssertEqual(subject, "[]")
}
func testIsValid() {
XCTAssert(JSONHelper.isValid("[1,2]"))
XCTAssert(JSONHelper.isValid("[\"one\", \"two\"]"))
XCTAssert(JSONHelper.isValid(["foo", 42, false, NSNull()]))
XCTAssertFalse(JSONHelper.isValid(""))
XCTAssertFalse(JSONHelper.isValid("foobar"))
XCTAssertFalse(JSONHelper.isValid([Date()]))
}
func testValidate() {
_ = try! JSONHelper.validate("[1,2]")
_ = try! JSONHelper.validate("[\"one\", \"two\"]")
_ = try! JSONHelper.validate("[true, false]")
_ = try! JSONHelper.validate("[null]")
_ = try! JSONHelper.validate(["foo", 42, false, NSNull()])
let shouldRejectEmptyString = expectation(description: "empty string")
let shouldRejectString = expectation(description: "string")
let shouldRejectElement = expectation(description: "bad element")
do { try JSONHelper.validate("") } catch JSONError.malformed {
shouldRejectEmptyString.fulfill()
} catch { }
do { try JSONHelper.validate("foobar") } catch JSONError.malformed {
shouldRejectString.fulfill()
} catch { }
do { try JSONHelper.validate([Date()]) } catch JSONError.invalidType {
shouldRejectElement.fulfill()
} catch { }
waitForExpectations(timeout: 1.0, handler: nil)
}
}
| mit | 08e5385ae442ab7bb29d192637d3b44e | 28.096491 | 75 | 0.635213 | 4.252564 | false | true | false | false |
Spriter/SwiftyHue | Sources/Base/BridgeResourceModels/Sensors/DaylightSensor/DaylightSensor.swift | 1 | 1853 | //
// DaylightSensor.swift
// Pods
//
// Created by Jerome Schmitz on 01.05.16.
//
//
import Foundation
import Gloss
public class DaylightSensor: PartialSensor {
let config: DaylightSensorConfig
let state: DaylightSensorState
required public init?(sensor: Sensor) {
guard let sensorConfig = sensor.config else {
return nil
}
guard let sensorState = sensor.state else {
return nil
}
guard let config: DaylightSensorConfig = DaylightSensorConfig(sensorConfig: sensorConfig) else {
return nil
}
guard let state: DaylightSensorState = DaylightSensorState(state: sensorState) else {
return nil
}
self.config = config
self.state = state
super.init(identifier: sensor.identifier, uniqueId: sensor.uniqueId, name: sensor.name, type: sensor.type, modelId: sensor.modelId, manufacturerName: sensor.manufacturerName, swVersion: sensor.swVersion, recycle: sensor.recycle)
}
public required init?(json: JSON) {
guard let config: DaylightSensorConfig = "config" <~~ json else {
return nil
}
guard let state: DaylightSensorState = "state" <~~ json else {
return nil
}
self.config = config
self.state = state
super.init(json: json)
}
}
public func ==(lhs: DaylightSensor, rhs: DaylightSensor) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.name == rhs.name &&
lhs.state == rhs.state &&
lhs.config == rhs.config &&
lhs.type == rhs.type &&
lhs.modelId == rhs.modelId &&
lhs.manufacturerName == rhs.manufacturerName &&
lhs.swVersion == rhs.swVersion
} | mit | 7497d0026ff090ed06327b8712ff41da | 26.671642 | 236 | 0.587156 | 4.691139 | false | true | false | false |
Look-ARound/LookARound2 | Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARPresenter.swift | 1 | 18881 | //
// ARPresenter.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 16/12/2016.
// Copyright © 2016 Danijel Huis. All rights reserved.
//
import UIKit
import CoreLocation
/**
Handles visual presentation of annotations.
Adds ARAnnotationViews on the screen and calculates its screen positions. Before anything
is done, it first filters annotations by distance and count for improved performance. This
class is also responsible for vertical stacking of the annotation views.
It can be subclassed if custom positioning is needed, e.g. if you wan't to position
annotations relative to its altitudes you would subclass ARPresenter and override
xPositionForAnnotationView and yPositionForAnnotationView.
*/
open class ARPresenter: UIView
{
/**
Stacks overlapping annotations vertically.
*/
@available(iOS, deprecated:1.0, message: "Use presenterTransform = ARPresenterStackTransform()")
open var verticalStackingEnabled = false
{
didSet
{
self.presenterTransform = self.verticalStackingEnabled ? ARPresenterStackTransform() : nil
}
}
/**
How much to vertically offset annotations by distance, in pixels per meter. Use it if distanceOffsetMode is manual or automaticOffsetMinDistance.
Also look at distanceOffsetMinThreshold and distanceOffsetMode.
*/
open var distanceOffsetMultiplier: Double?
/**
All annotations farther(from user) than this value will be offset using distanceOffsetMultiplier. Use it if distanceOffsetMode is manual.
Also look at distanceOffsetMultiplier and distanceOffsetMode.
*/
open var distanceOffsetMinThreshold: Double = 0
/**
Distance offset mode, it affects vertical offset of annotations by distance.
*/
open var distanceOffsetMode = DistanceOffsetMode.automatic
/**
If set, it will be used instead of distanceOffsetMultiplier and distanceOffsetMinThreshold if distanceOffsetMode != none
Use it to calculate vartical offset by given distance.
*/
open var distanceOffsetFunction: ((_ distance: Double) -> Double)?
/**
How low on the screen is nearest annotation. 0 = top, 1 = bottom.
*/
open var bottomBorder: Double = 0.55
/**
Distance offset mode, it affects vertical offset of annotations by distance.
*/
public enum DistanceOffsetMode
{
/// Annotations are not offset vertically with distance.
case none
/// Use distanceOffsetMultiplier and distanceOffsetMinThreshold to control offset.
case manual
/// distanceOffsetMinThreshold is set to closest annotation, distanceOffsetMultiplier must be set by user.
case automaticOffsetMinDistance
/**
distanceOffsetMinThreshold is set to closest annotation and distanceOffsetMultiplier
is set to fit all annotations on screen vertically(before stacking)
*/
case automatic
}
open weak var arViewController: ARViewController!
/// All annotations
open var annotations: [ARAnnotation] = []
/// Annotations filtered by distance/maxVisibleAnnotations. Look at activeAnnotationsFromAnnotations.
open var activeAnnotations: [ARAnnotation] = []
/// AnnotionViews for all active annotations, this is set in createAnnotationViews.
open var annotationViews: [ARAnnotationView] = []
/// AnnotationViews that are on visible part of the screen or near its border.
open var visibleAnnotationViews: [ARAnnotationView] = []
/// Responsible for transform/layout of annotations after they have been layouted by ARPresenter. e.g. used for stacking.
open var presenterTransform: ARPresenterTransform?
{
didSet
{
self.presenterTransform?.arPresenter = self
}
}
public init(arViewController: ARViewController)
{
self.arViewController = arViewController
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
/**
Total maximum number of visible annotation views. Default value is 100. Max value is 500.
This will affect performance, especially if stacking is involved.
*/
open var maxVisibleAnnotations = 100
{
didSet
{
if(maxVisibleAnnotations > MAX_VISIBLE_ANNOTATIONS)
{
maxVisibleAnnotations = MAX_VISIBLE_ANNOTATIONS
}
}
}
/**
Maximum distance(in meters) for annotation to be shown.
Default value is 0 meters, which means that distances of annotations don't affect their visiblity.
This can be used to increase performance.
*/
open var maxDistance: Double = 0
//==========================================================================================================================================================
// MARK: Reload - main logic
//==========================================================================================================================================================
/**
This is called from ARViewController, it handles main logic, what is called and when.
*/
open func reload(annotations: [ARAnnotation], reloadType: ARViewController.ReloadType)
{
guard self.arViewController.arStatus.ready else { return }
// Detecting some rare cases, e.g. if clear was called then we need to recreate everything.
let changeDetected = self.annotations.count != annotations.count
// needsRelayout indicates that position of user or positions of annotations have changed. e.g. user moved, annotations moved/changed.
// This means that positions of annotations on the screen must be recalculated.
let needsRelayout = reloadType == .annotationsChanged || reloadType == .reloadLocationChanged || reloadType == .userLocationChanged || changeDetected
// Doing heavier stuff here
if needsRelayout
{
self.annotations = annotations
// Filtering annotations and creating annotation views. Doing this only on big location changes, not on any user location change.
if reloadType != .userLocationChanged || changeDetected
{
self.activeAnnotations = self.activeAnnotationsFromAnnotations(annotations: annotations)
self.createAnnotationViews()
}
self.adjustDistanceOffsetParameters()
for annotationView in self.annotationViews
{
annotationView.bindUi()
}
// This must be done before layout
self.resetLayoutParameters()
}
self.addRemoveAnnotationViews(arStatus: self.arViewController.arStatus)
self.preLayout(arStatus: self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
self.layout(arStatus: self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
self.postLayout(arStatus:self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
//==========================================================================================================================================================
// MARK: Filtering(Active annotations)
//==========================================================================================================================================================
/**
Gives opportunity to the presenter to filter annotations and reduce number of items it is working with.
Default implementation filters by maxVisibleAnnotations and maxDistance.
*/
open func activeAnnotationsFromAnnotations(annotations: [ARAnnotation]) -> [ARAnnotation]
{
var activeAnnotations: [ARAnnotation] = []
for annotation in annotations
{
// maxVisibleAnnotations filter
if activeAnnotations.count >= self.maxVisibleAnnotations
{
annotation.active = false
continue
}
// maxDistance filter
if self.maxDistance != 0 && annotation.distanceFromUser > self.maxDistance
{
annotation.active = false
continue
}
annotation.active = true
activeAnnotations.append(annotation)
}
return activeAnnotations
}
//==========================================================================================================================================================
// MARK: Creating annotation views
//==========================================================================================================================================================
/**
Creates views for active annotations and removes views from inactive annotations.
@IMPROVEMENT: Add reuse logic
*/
open func createAnnotationViews()
{
var annotationViews: [ARAnnotationView] = []
let activeAnnotations = self.activeAnnotations
// Removing existing annotation views and reseting some properties
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
// Destroy views for inactive anntotations
for annotation in self.annotations
{
if(!annotation.active)
{
annotation.annotationView = nil
}
}
// Create views for active annotations
for annotation in activeAnnotations
{
var annotationView: ARAnnotationView? = nil
if annotation.annotationView != nil
{
annotationView = annotation.annotationView
}
else
{
annotationView = self.arViewController.dataSource?.ar(self.arViewController, viewForAnnotation: annotation)
}
annotation.annotationView = annotationView
if let annotationView = annotationView
{
annotationView.annotation = annotation
annotationViews.append(annotationView)
}
}
self.annotationViews = annotationViews
}
/// Removes all annotation views from screen and resets annotations
open func clear()
{
for annotation in self.annotations
{
annotation.active = false
annotation.annotationView = nil
}
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
self.annotations = []
self.activeAnnotations = []
self.annotationViews = []
self.visibleAnnotationViews = []
}
//==========================================================================================================================================================
// MARK: Add/Remove
//==========================================================================================================================================================
/**
Adds/removes annotation views to/from superview depending if view is on visible part of the screen.
Also, if annotation view is on visible part, it is added to visibleAnnotationViews.
*/
open func addRemoveAnnotationViews(arStatus: ARStatus)
{
let degreesDeltaH = arStatus.hFov
let heading = arStatus.heading
self.visibleAnnotationViews.removeAll()
for annotation in self.activeAnnotations
{
guard let annotationView = annotation.annotationView else { continue }
// This is distance of center of annotation to the center of screen, measured in degrees
let delta = deltaAngle(heading, annotation.azimuth)
if fabs(delta) < degreesDeltaH
{
if annotationView.superview == nil
{
// insertSubview at 0 so that farther ones are beneath nearer ones
self.insertSubview(annotationView, at: 0)
}
self.visibleAnnotationViews.append(annotationView)
}
else
{
if annotationView.superview != nil
{
annotationView.removeFromSuperview()
}
}
}
}
//==========================================================================================================================================================
// MARK: Layout
//==========================================================================================================================================================
/**
Layouts annotation views.
- Parameter relayoutAll: If true it will call xPositionForAnnotationView/yPositionForAnnotationView for each annotation view, else
it will only take previously calculated x/y positions and add heading/pitch offsets to visible annotation views.
*/
open func layout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
let pitchYOffset = CGFloat(arStatus.pitch * arStatus.vPixelsPerDegree)
let annotationViews = needsRelayout ? self.annotationViews : self.visibleAnnotationViews
for annotationView in annotationViews
{
guard let annotation = annotationView.annotation else { continue }
if(needsRelayout)
{
let x = self.xPositionForAnnotationView(annotationView, arStatus: arStatus)
let y = self.yPositionForAnnotationView(annotationView, arStatus: arStatus)
annotationView.arPosition = CGPoint(x: x, y: y)
}
let headingXOffset = CGFloat(deltaAngle(annotation.azimuth, arStatus.heading)) * CGFloat(arStatus.hPixelsPerDegree)
let x: CGFloat = annotationView.arPosition.x + headingXOffset
let y: CGFloat = annotationView.arPosition.y + pitchYOffset + annotationView.arPositionOffset.y
// Final position of annotation
annotationView.frame = CGRect(x: x, y: y, width: annotationView.bounds.size.width, height: annotationView.bounds.size.height)
}
}
/**
x position without the heading, heading offset is added in layoutAnnotationViews due to performance.
*/
open func xPositionForAnnotationView(_ annotationView: ARAnnotationView, arStatus: ARStatus) -> CGFloat
{
let centerX = self.bounds.size.width * 0.5
let x = centerX - (annotationView.bounds.size.width * annotationView.centerOffset.x)
return x
}
/**
y position without the pitch, pitch offset is added in layoutAnnotationViews due to performance.
*/
open func yPositionForAnnotationView(_ annotationView: ARAnnotationView, arStatus: ARStatus) -> CGFloat
{
guard let annotation = annotationView.annotation else { return 0}
let bottomY = self.bounds.size.height * CGFloat(self.bottomBorder)
let distance = annotation.distanceFromUser
// Offset by distance
var distanceOffset: Double = 0
if self.distanceOffsetMode != .none
{
if let function = self.distanceOffsetFunction
{
distanceOffset = function(distance)
}
else if distance > self.distanceOffsetMinThreshold, let distanceOffsetMultiplier = self.distanceOffsetMultiplier
{
let distanceForOffsetCalculation = distance - self.distanceOffsetMinThreshold
distanceOffset = -(distanceForOffsetCalculation * distanceOffsetMultiplier)
}
}
// y
let y = bottomY - (annotationView.bounds.size.height * annotationView.centerOffset.y) + CGFloat(distanceOffset)
return y
}
/**
Resets temporary stacking fields. This must be called before stacking and before layout.
*/
open func resetLayoutParameters()
{
for annotationView in self.annotationViews
{
annotationView.arPositionOffset = CGPoint.zero
annotationView.arAlternateFrame = CGRect.zero
}
}
open func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
self.presenterTransform?.preLayout(arStatus: arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
open func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
self.presenterTransform?.postLayout(arStatus: arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
//==========================================================================================================================================================
// MARK: DistanceOffset
//==========================================================================================================================================================
open func adjustDistanceOffsetParameters()
{
guard var minDistance = self.activeAnnotations.first?.distanceFromUser else { return }
guard let maxDistance = self.activeAnnotations.last?.distanceFromUser else { return }
if minDistance > maxDistance { minDistance = maxDistance }
let deltaDistance = maxDistance - minDistance
let availableHeight = Double(self.bounds.size.height) * self.bottomBorder - 30 // 30 because we don't want them to be on top but little bit below
if self.distanceOffsetMode == .automatic
{
self.distanceOffsetMinThreshold = minDistance
self.distanceOffsetMultiplier = deltaDistance > 0 ? availableHeight / deltaDistance : 0
}
else if self.distanceOffsetMode == .automaticOffsetMinDistance
{
self.distanceOffsetMinThreshold = minDistance
}
}
}
| apache-2.0 | 4c40f70a9b1a0f3ed4b9d3c7f20f9347 | 40.31291 | 160 | 0.566367 | 6.184081 | false | false | false | false |
leuski/Coiffeur | Coiffeur/src/Document.swift | 1 | 2857 | //
// Document.swift
// Coiffeur
//
// Created by Anton Leuski on 4/7/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import Cocoa
@objc(Document)
class Document: NSDocument {
var model: CoiffeurController?
override init()
{
super.init()
}
convenience init(type typeName: String) throws
{
self.init()
self.fileType = typeName
self.model = try CoiffeurController.coiffeurWithType(typeName)
}
override var undoManager: UndoManager? {
get {
if let model = self.model {
return model.managedObjectContext.undoManager
} else {
return super.undoManager
}
}
set {
super.undoManager = newValue
}
}
private func _ensureWeHaveModelOfType(
_ typeName: String) throws -> String
{
if let model = self.model {
return type(of: model).documentType
}
self.model = try CoiffeurController.coiffeurWithType(typeName)
return typeName
}
override func read(from absoluteURL: URL, ofType typeName: String) throws
{
let modelTypeName = try _ensureWeHaveModelOfType(typeName)
if modelTypeName != typeName {
throw Errors.cannotReadAs(typeName, modelTypeName)
}
try self.model?.readValuesFromURL(absoluteURL)
}
override func write(to absoluteURL: URL, ofType typeName: String) throws
{
let modelTypeName = try _ensureWeHaveModelOfType(typeName)
if modelTypeName != typeName {
throw Errors.cannotWriteAs(typeName, modelTypeName)
}
try self.model?.writeValuesToURL(absoluteURL)
}
override class var autosavesInPlace: Bool
{
return true
}
override func makeWindowControllers()
{
self.addWindowController(MainWindowController())
}
// override func canCloseDocumentWithDelegate(delegate: AnyObject,
// shouldCloseSelector: Selector, contextInfo: UnsafeMutablePointer<Void>)
// {
// self.model?.managedObjectContext.commitEditing()
// super.canCloseDocumentWithDelegate(delegate,
// shouldCloseSelector:shouldCloseSelector, contextInfo:contextInfo)
// }
override func writableTypes(for _: NSDocument.SaveOperationType)
-> [String]
{
if let model = self.model {
return [type(of: model).documentType]
} else {
return []
}
}
}
| apache-2.0 | 5e2eb9c31546b0b916d46126e144b572 | 23.843478 | 79 | 0.693385 | 4.264179 | false | false | false | false |
Paul-Jouhaud/url_shortener | urlShortenerApp/urlShortener/ShortenerViewController.swift | 1 | 2283 | //
// FirstViewController.swift
// urlShortenerApp
//
// Created by Paul Jouhaud on 20/12/2016.
// Copyright © 2016 Paul Jouhaud. All rights reserved.
//
import UIKit
protocol ShortenerViewControllerDelegate: class {
func shortenerViewController(_ controller: ShortenerViewController, didFinishAdding item: UrlItem)
}
class ShortenerViewController: UIViewController {
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.
}
weak var delegate: ShortenerViewControllerDelegate?
@IBOutlet weak var shortURL: UILabel!
@IBOutlet weak var realURL: UITextField!
@IBAction func generateShortenedURL() {
let realUrlText = realURL.text!
let requestData = ["real_url": realURL.text!]
let url = URL(string: "http://localhost:8000/api/")!
let jsonData = try! JSONSerialization.data(withJSONObject: requestData, options: [])
var request = URLRequest(url: url)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request ) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
let shortUrlText = response["short_url"]! as! String
self.shortURL.text = shortUrlText
let newShortUrl = UrlItem()
newShortUrl.real_url = realUrlText
newShortUrl.short_url = shortUrlText
print(newShortUrl)
self.delegate?.shortenerViewController(self, didFinishAdding: newShortUrl)
} catch {
print("error:", error)
}
}
task.resume()
}
}
| mit | 54e75d65260802196c9d73aa4f70a103 | 34.107692 | 134 | 0.610429 | 4.845011 | false | false | false | false |
LittoCats/coffee-mobile | CoffeeMobile/Base/Utils/CMAsync.swift | 1 | 7707 | //
// Async.swift
// Async
//
// Created by 程巍巍 on 3/31/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
// 为 GCD 添加事务管理,类似 js 中 promise 的效果,
// 通过级连调用的提交的 dispatch_block_t 将按顺序执行
import Foundation
struct CMAsync {
/**
* 缓存将要执行的 dispatch_block_t
* 如果关联事务(block) 被释放(例如销毁了 dispatch_queue_t),后面的事务将被自动释放
*/
private static var ChainedBlockTable = NSMapTable.weakToStrongObjectsMapTable()
private let e_block: dispatch_block_t
private init(_ block: dispatch_block_t, queue: dispatch_queue_t, interval: NSTimeInterval) {
var _block = CMAsync.wrapBlock(block)
if interval <= 0.0 {
dispatch_async(queue, _block)
}else{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)*Int64(interval)), queue, _block)
}
self.e_block = block
}
private init(_ block: dispatch_block_t) {
self.e_block = block
}
private func async(after interval: NSTimeInterval = 0.0, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> CMAsync {
var _block: dispatch_block_t = { () -> Void in
var __block = CMAsync.wrapBlock(block)
if interval <= 0.0 {
dispatch_async(queue, __block)
}else{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)*Int64(interval)), queue, __block)
}
}
CMAsync.ChainedBlockTable.setObject(unsafeBitCast(_block, AnyObject.self), forKey: unsafeBitCast(self.e_block, AnyObject.self))
return CMAsync(block)
}
private static func async(after interval: NSTimeInterval = 0.0, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> CMAsync {
return CMAsync(block, queue: queue, interval: interval)
}
// block wrapper
private static func wrapBlock(block: dispatch_block_t) ->dispatch_block_t{
return { () -> Void in
block()
var n_block_obj: AnyObject? = CMAsync.ChainedBlockTable.objectForKey(unsafeBitCast(block, AnyObject.self))
if n_block_obj == nil {return}
var n_block = unsafeBitCast(n_block_obj, dispatch_block_t.self)
n_block()
}
}
}
// MARK
extension CMAsync {
/* dispatch_async() */
static func main(block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: GCD.MainQueue)
}
static func interactive(block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: GCD.InteractiveQueue)
}
static func initiated(block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: GCD.InitiatedQueue)
}
static func utility(block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: GCD.UtilityQueue)
}
static func background(block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: GCD.BackgroundQueue)
}
static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(block:block, inQueue: queue)
}
/* dispatch_after() */
static func main(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: GCD.MainQueue)
}
static func interactive(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: GCD.InteractiveQueue)
}
static func initiated(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: GCD.InitiatedQueue)
}
static func utility(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: GCD.UtilityQueue)
}
static func background(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: GCD.BackgroundQueue)
}
static func customQueue(after interval: NSTimeInterval, queue: dispatch_queue_t, block: dispatch_block_t) -> CMAsync {
return CMAsync.async(after:interval, block:block, inQueue: queue)
}
}
extension CMAsync {
/* dispatch_async() */
func main(block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: GCD.MainQueue)
}
func interactive(block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: GCD.InteractiveQueue)
}
func initiated(block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: GCD.InitiatedQueue)
}
func utility(block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: GCD.UtilityQueue)
}
func background(block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: GCD.BackgroundQueue)
}
func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> CMAsync {
return async(block:block, inQueue: queue)
}
/* dispatch_after() */
func main(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: GCD.MainQueue)
}
func interactive(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: GCD.InteractiveQueue)
}
func initiated(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: GCD.InitiatedQueue)
}
func utility(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: GCD.UtilityQueue)
}
func background(after interval: NSTimeInterval, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: GCD.BackgroundQueue)
}
func customQueue(after interval: NSTimeInterval, queue: dispatch_queue_t, block: dispatch_block_t) -> CMAsync {
return async(after:interval, block:block, inQueue: queue)
}
}
extension CMAsync {
private struct GCD {
/* dispatch_get_queue() */
static var MainQueue: dispatch_queue_t {
return dispatch_get_main_queue()
}
static var InteractiveQueue: dispatch_queue_t {
// DISPATCH_QUEUE_PRIORITY_HIGH
// return dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.value), 0)
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
}
static var InitiatedQueue: dispatch_queue_t {
// DISPATCH_QUEUE_PRIORITY_DEFAULT
// return dispatch_get_global_queue(Int(QOS_CLASS_DEFAULT.value), 0)
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
}
static var UtilityQueue: dispatch_queue_t {
// DISPATCH_QUEUE_PRIORITY_LOW
// return dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0)
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
}
static var BackgroundQueue: dispatch_queue_t {
// DISPATCH_QUEUE_PRIORITY_BACKGROUND
// return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0)
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
}
}
} | apache-2.0 | 9acc1d61d9e3c29c7c15b2f45e4e3bac | 42.257143 | 138 | 0.653059 | 3.877561 | false | false | false | false |
CeranPaul/SketchCurves | SketchGen/Plane.swift | 1 | 12603 | //
// Plane.swift
// SketchCurves
//
// Created by Paul on 8/11/15.
// Copyright © 2018 Ceran Digital Media. All rights reserved. See LICENSE.md
//
import Foundation
/// Unbounded flat surface
public struct Plane {
/// A point to locate the plane
internal var location: Point3D
/// A vector perpendicular to the plane
internal var normal: Vector3D
/// Records parameters and checks to see that the normal is a legitimate vector
/// - Parameters:
/// - alpha: Origin for the fresh plane
/// - arrow: Unit vector that the plane will be perpendicular to
/// - See: 'testFidelity' under PlaneTests
public init(spot: Point3D, arrow: Vector3D) throws {
guard !arrow.isZero() else { throw ZeroVectorError(dir: arrow) }
guard arrow.isUnit() else { throw NonUnitDirectionError(dir: arrow) }
self.location = spot
self.normal = arrow
}
/// Construct a plane from three points
/// - Parameters:
/// - alpha: First input point and origin of the fresh plane
/// - beta: Second input point
/// - gamma: Third input point
/// - Returns: Fresh plane
/// - Throws: CoincidentPointsError for duplicate or linear inputs
/// - See: 'testInitPts' under PlaneTests
init(alpha: Point3D, beta: Point3D, gamma: Point3D) throws {
guard Point3D.isThreeUnique(alpha: alpha, beta: beta, gamma: gamma) else { throw CoincidentPointsError(dupePt: alpha) }
// TODO: Come up with a better error type
guard !Point3D.isThreeLinear(alpha: alpha, beta: beta, gamma: gamma) else { throw CoincidentPointsError(dupePt: alpha) }
self.location = alpha
let thisWay = Vector3D.built(from: alpha, towards: beta)
let thatWay = Vector3D.built(from: alpha, towards: gamma)
var perpTo = try! Vector3D.crossProduct(lhs: thisWay, rhs: thatWay)
perpTo.normalize()
self.normal = perpTo
}
// TODO: Write a constructor from two lines, and possibly a line and a point.
/// A getter for the point defining the plane
/// - See: 'testLocationGetter' under PlaneTests
public func getLocation() -> Point3D {
return self.location
}
/// A getter for the vector defining the plane
/// - See: 'testNormalGetter' under PlaneTests
public func getNormal() -> Vector3D {
return self.normal
}
/// Build orthogonal vectors from the origin of the plane to the point
/// - Parameters:
/// - pip: Point of interest
/// - Returns: Tuple of Vectors
/// - See: 'testResolveRelative' under PlaneTests
public func resolveRelativeVec(pip: Point3D) -> (inPlane: Vector3D, perp: Vector3D) {
let bridge = Vector3D.built(from: self.location, towards: pip)
let along = Vector3D.dotProduct(lhs: bridge, rhs: self.normal)
let perp = self.normal * along
let inPlane = bridge - perp
return (inPlane, perp)
}
/// Check to see that the line direction is perpendicular to the normal
/// - Parameters:
/// - flat: Reference plane
/// - enil: Line for testing
/// - Returns: Simple flag
/// - See: 'testIsParallelLine' under PlaneTests
public static func isParallel(flat: Plane, enil: Line) -> Bool {
let perp = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: flat.normal)
return abs(perp) < Vector3D.EpsilonV
}
/// Check to see that the line is parallel to the plane, and lies on it
/// - Parameters:
/// - enalp: Reference plane
/// - enil: Line for testing
/// - Returns: Simple flag
/// - See: 'testIsCoincidentLine' under PlaneTests
public static func isCoincident(enalp: Plane, enil: Line) -> Bool {
return self.isParallel(flat: enalp, enil: enil) && Plane.isCoincident(flat: enalp, pip: enil.getOrigin())
}
/// Does the argument point lie on the plane?
/// - Parameters:
/// - flat: Plane for testing
/// - pip: Point for testing
/// - Returns: Simple flag
/// - See: 'testIsCoincident' under PlaneTests
public static func isCoincident(flat: Plane, pip: Point3D) -> Bool {
if pip == flat.getLocation() { return true } // Shortcut!
let bridge = Vector3D.built(from: flat.location, towards: pip)
// This can be positive, negative, or zero
let distanceOffPlane = Vector3D.dotProduct(lhs: bridge, rhs: flat.normal)
return abs(distanceOffPlane) < Point3D.Epsilon
}
/// Are the normals either parallel or opposite?
/// - Parameters:
/// - lhs: One plane for testing
/// - rhs: Another plane for testing
/// - Returns: Simple flag
/// - SeeAlso: isCoincident and ==
/// - See: 'testIsParallelPlane' under PlaneTests
public static func isParallel(lhs: Plane, rhs: Plane) -> Bool{
return lhs.normal == rhs.normal || Vector3D.isOpposite(lhs: lhs.normal, rhs: rhs.normal)
}
/// Planes are parallel, and rhs location lies on lhs
/// - Parameters:
/// - lhs: One plane for testing
/// - rhs: Another plane for testing
/// - Returns: Simple flag
/// - SeeAlso: isParallel and ==
/// - See: 'testIsCoincidentPlane' under PlaneTests
public static func isCoincident(lhs: Plane, rhs: Plane) -> Bool {
return Plane.isCoincident(flat: lhs, pip: rhs.location) && Plane.isParallel(lhs: lhs, rhs: rhs)
}
/// Construct a parallel plane offset some distance.
/// - Parameters:
/// - base: The reference plane
/// - offset: Desired separation. Can be positive or negative.
/// - reverse: Flip the normal, or not
/// - Returns: Fresh plane that has separation
/// - See: 'testBuildParallel' under PlaneTests
public static func buildParallel(base: Plane, offset: Double, reverse: Bool) -> Plane {
let jump = base.normal * offset // Offset could be a negative number
let origPoint = base.location
let newLoc = origPoint.offset(jump: jump)
var newNorm = base.normal
if reverse {
newNorm = base.normal * -1.0
}
let sparkle = try! Plane(spot: newLoc, arrow: newNorm) // Allowable because the new normal mimics the original
return sparkle
}
/// Construct a new plane perpendicular to an existing plane, and through a line on that plane
/// Normal could be the opposite of what you hoped for
/// - Parameters:
/// - enil: Location for a fresh plane
/// - enalp: The reference plane
/// - Returns: Fresh plane
/// - Throws:
/// - CoincidentLinesError if line doesn't lie on the plane
/// - See: 'testBuildPerpThruLine' under PlaneTests
public static func buildPerpThruLine(enil: Line, enalp: Plane) throws -> Plane {
// TODO: Better error type
guard Plane.isCoincident(enalp: enalp, enil: enil) else { throw CoincidentLinesError(enil: enil) }
let newDir = try! Vector3D.crossProduct(lhs: enil.getDirection(), rhs: enalp.normal)
let sparkle = try Plane(spot: enil.getOrigin(), arrow: newDir)
return sparkle
}
/// Generate a point by intersecting a line and a plane
/// - Parameters:
/// - enil: Line of interest
/// - enalp: Flat surface to hit
/// - Returns: Common Point
/// - Throws: ParallelError if the input Line is parallel to the plane
/// - See: 'testIntersectLinePlane' under PlaneTests
public static func intersectLinePlane(enil: Line, enalp: Plane) throws -> Point3D {
// Bail if the line is parallel to the plane
guard !Plane.isParallel(flat: enalp, enil: enil) else { throw ParallelError(enil: enil, enalp: enalp) }
if Plane.isCoincident(flat: enalp, pip: enil.getOrigin()) { return enil.getOrigin() } // Shortcut!
// Resolve the line direction into components normal to the plane and in plane
let lineNormMag = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: enalp.getNormal())
let lineNormComponent = enalp.getNormal() * lineNormMag
let lineInPlaneComponent = enil.getDirection() - lineNormComponent
let projectedLineOrigin = Plane.projectToPlane(pip: enil.getOrigin(), enalp: enalp)
let drop = Vector3D.built(from: enil.getOrigin(), towards: projectedLineOrigin, unit: true)
let closure = Vector3D.dotProduct(lhs: enil.getDirection(), rhs: drop)
let separation = Point3D.dist(pt1: projectedLineOrigin, pt2: enil.getOrigin())
var factor = separation / lineNormComponent.length()
if closure < 0.0 { factor = factor * -1.0 } // Dependent on the line origin's position relative to
// the plane normal
let inPlaneOffset = lineInPlaneComponent * factor
return projectedLineOrigin.offset(jump: inPlaneOffset)
}
/// Construct a line by intersecting two planes
/// - Parameters:
/// - flatA: First plane
/// - flatB: Second plane
/// - Throws: ParallelPlanesError if the inputs are parallel
/// - Throws: CoincidentPlanesError if the inputs are coincident
/// - See: 'testIntersectPlanes' under PlaneTests
public static func intersectPlanes(flatA: Plane, flatB: Plane) throws -> Line {
guard !Plane.isCoincident(lhs: flatA, rhs: flatB) else { throw CoincidentPlanesError(enalpA: flatA) }
guard !Plane.isParallel(lhs: flatA, rhs: flatB) else { throw ParallelPlanesError(enalpA: flatA) }
/// Direction of the intersection line
var lineDir = try! Vector3D.crossProduct(lhs: flatA.getNormal(), rhs: flatB.getNormal())
lineDir.normalize() // Checks in crossProduct should keep this from being a zero vector
/// Vector on plane B that is perpendicular to the intersection line
var perpInB = try! Vector3D.crossProduct(lhs: lineDir, rhs: flatB.getNormal())
perpInB.normalize() // Checks in crossProduct should keep this from being a zero vector
// The ParallelPlanesError or CoincidentPlanesError should be avoided by the guard statements
let lineFromCenterB = try Line(spot: flatB.getLocation(), arrow: perpInB) // Can be either towards flatA,
// or away from it
let intersectionPoint = try Plane.intersectLinePlane(enil: lineFromCenterB, enalp: flatA)
let common = try Line(spot: intersectionPoint, arrow: lineDir)
return common
}
/// Drop the point in the direction opposite of the normal
/// - Parameters:
/// - pip: Point to be projected
/// - enalp: Flat surface to hit
/// - Returns: Closest point on plane
/// - See: 'testProjectToPlane' under PlaneTests
public static func projectToPlane(pip: Point3D, enalp: Plane) -> Point3D {
if Plane.isCoincident(flat: enalp, pip: pip) {return pip } // Shortcut!
let planeCenter = enalp.getLocation() // Referred to multiple times
let bridge = Vector3D.built(from: planeCenter, towards: pip) // Not normalized
// This can be positive, or negative
let distanceOffPlane = Vector3D.dotProduct(lhs: bridge, rhs: enalp.getNormal())
// Resolve "bridge" into components that are perpendicular to the plane and are parallel to it
let bridgeNormComponent = enalp.getNormal() * distanceOffPlane
let bridgeInPlaneComponent = bridge - bridgeNormComponent
return planeCenter.offset(jump: bridgeInPlaneComponent) // Ignore the component normal to the plane
}
}
/// Check for them being identical
/// - SeeAlso: isParallel and isCoincident
/// - See: 'testEquals' under PlaneTests
public func == (lhs: Plane, rhs: Plane) -> Bool {
let flag1 = lhs.normal == rhs.normal // Do they have the same direction?
let flag2 = lhs.location == rhs.location // Do they have identical locations?
return flag1 && flag2
}
| apache-2.0 | 3d6cefb1c17d76bf42bd350bc8337903 | 37.538226 | 130 | 0.61641 | 4.115611 | false | true | false | false |
kshin/Kana | Source/Object.swift | 1 | 464 | //
// Object.swift
// Kana
//
// Created by Ivan Lisovyi on 17/09/2016.
// Copyright © 2016 Ivan Lisovyi. All rights reserved.
//
import Foundation
import Unbox
public class Object: Unboxable {
public internal(set) var id: Int
public required init(unboxer: Unboxer) throws {
self.id = try unboxer.unbox(key: "id")
}
}
extension Object: Equatable {}
public func ==(lhs: Object, rhs: Object) -> Bool {
return lhs.id == rhs.id
}
| mit | f0ba9055876544fe8a1ab5f64662ecc6 | 18.291667 | 55 | 0.647948 | 3.355072 | false | false | false | false |
darkerk/v2ex | V2EX/ViewControllers/DrawerViewController.swift | 1 | 9026 | //
// DrawerViewController.swift
// V2EX
//
// Created by darker on 2017/2/27.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class DrawerSegue: UIStoryboardSegue {
override func perform() {
}
}
class DrawerViewController: UIViewController {
var leftDrawerWidth: CGFloat = 250.0
var leftViewController: UIViewController?
var centerViewController: UIViewController?
var centerOverlayView: UIView?
private let disposeBag = DisposeBag()
var isOpenDrawer = false {
willSet {
guard let leftViewController = leftViewController, let centerViewController = centerViewController else {
return
}
isAnimatingDrawer = true
var leftRect = leftViewController.view.frame
var centerRect = centerViewController.view.frame
leftRect.size.height = centerRect.size.height
leftRect.origin.x = newValue ? 0.0 : -leftDrawerWidth
centerRect.origin.x += newValue ? leftDrawerWidth : -leftDrawerWidth
UIView.animate(withDuration: 0.35,
animations: {
leftViewController.view.frame = leftRect
centerViewController.view.frame = centerRect
self.centerOverlayView?.alpha = newValue ? 0.3 : 0.0
}, completion: {finished in
self.isAnimatingDrawer = false
})
}
}
private var isAnimatingDrawer = false
private var startingPanX: CGFloat = 0
lazy var panGesture = UIPanGestureRecognizer()
override func awakeFromNib() {
guard let _ = storyboard else {
return
}
performSegue(withIdentifier: "left", sender: self)
performSegue(withIdentifier: "center", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
panGesture.rx.event.subscribe(onNext: {[weak self ]sender in
guard let `self` = self else {
return
}
guard let leftViewController = self.leftViewController, let centerViewController = self.centerViewController else {
return
}
switch sender.state {
case .began:
if self.isAnimatingDrawer {
sender.isEnabled = false
break
}else {
self.startingPanX = centerViewController.view.frame.minX
}
case .changed:
let point = sender.translation(in: sender.view)
var leftFrame = leftViewController.view.frame
var centerFrame = centerViewController.view.frame
centerFrame.origin.x = min(self.leftDrawerWidth, max(self.startingPanX + point.x, 0.0))
leftFrame.origin.x = centerFrame.origin.x - leftFrame.width
leftFrame.size.height = centerFrame.size.height
leftViewController.view.frame = leftFrame
centerViewController.view.frame = centerFrame
self.centerOverlayView?.alpha = (centerFrame.minX / self.leftDrawerWidth) * 0.3
case .ended, .cancelled:
let velocity = sender.velocity(in: centerViewController.view)
let animationThreshold: CGFloat = 200.0
let animationVelocity = max(abs(velocity.x), animationThreshold * 2)
let oldFrame = centerViewController.view.frame
var newFrame = oldFrame
if newFrame.minX <= self.leftDrawerWidth / 2.0 {
newFrame.origin.x = 0.0
}else {
newFrame.origin.x = self.leftDrawerWidth
}
var leftFrame = leftViewController.view.frame
leftFrame.origin.x = newFrame.origin.x - leftFrame.width
leftFrame.size.height = oldFrame.size.height
let distance = abs(oldFrame.minX - newFrame.origin.x)
let minimumAnimationDuration: CGFloat = 0.15
let duration: TimeInterval = TimeInterval(max(distance / abs(animationVelocity), minimumAnimationDuration))
let alpha = (newFrame.minX / self.leftDrawerWidth) * 0.3
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: animationVelocity / distance, options: [],
animations: {
self.centerOverlayView?.alpha = alpha
leftViewController.view.frame = leftFrame
centerViewController.view.frame = newFrame
}, completion: {_ in
self.isAnimatingDrawer = false
})
default: break
}
}).disposed(by: disposeBag)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
switch AppStyle.shared.theme {
case .normal:
return .default
case .night:
return .lightContent
}
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue is DrawerSegue {
addChild(segue.destination)
view.addSubview(segue.destination.view)
segue.destination.didMove(toParent: self)
if segue.destination is ProfileViewController {
let controller = segue.destination as! ProfileViewController
var rect = controller.view.frame
rect.origin.x = -leftDrawerWidth
rect.size.width = leftDrawerWidth
controller.view.frame = rect
leftViewController = controller
}else if segue.destination is UINavigationController {
centerViewController = segue.destination
(centerViewController as! UINavigationController).delegate = self
centerOverlayView = UIView()
centerOverlayView?.translatesAutoresizingMaskIntoConstraints = false
centerOverlayView?.backgroundColor = UIColor.black
centerOverlayView?.alpha = 0.0
centerViewController!.view.addSubview(centerOverlayView!)
centerOverlayView?.leadingAnchor.constraint(equalTo: centerViewController!.view.leadingAnchor).isActive = true
centerOverlayView?.trailingAnchor.constraint(equalTo: centerViewController!.view.trailingAnchor).isActive = true
centerOverlayView?.topAnchor.constraint(equalTo: centerViewController!.view.topAnchor).isActive = true
centerOverlayView?.bottomAnchor.constraint(equalTo: centerViewController!.view.bottomAnchor).isActive = true
let tap = UITapGestureRecognizer()
tap.rx.event.subscribe(onNext: {_ in
self.isOpenDrawer = false
}).disposed(by: disposeBag)
centerOverlayView?.addGestureRecognizer(tap)
}
}
}
}
extension DrawerViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if navigationController.viewControllers.count == 1 {
if view.gestureRecognizers?.contains(panGesture) != true {
view.addGestureRecognizer(panGesture)
}
}else {
if view.gestureRecognizers?.contains(panGesture) == true {
view.removeGestureRecognizer(panGesture)
}
}
}
}
extension UIViewController {
var drawerViewController: DrawerViewController? {
var drawer = parent
while drawer != nil {
if let drawer = drawer as? DrawerViewController {
return drawer
}
drawer = parent?.parent
}
if let controller = drawer as? DrawerViewController {
return controller
}
if let controller = presentingViewController as? DrawerViewController {
return controller
}
return drawer as? DrawerViewController
}
}
| mit | 247597296e54ec35228109cf155781e1 | 38.748899 | 159 | 0.576305 | 6.129755 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/APIManager+Post.swift | 1 | 4574 | //
// APIManager+Post.swift
// Insapp
//
// Created by Florent THOMAS-MOREL on 9/14/16.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import UIKit
extension APIManager {
static func fetchLastestPosts(controller: UIViewController, completion:@escaping (_ posts:[Post]) -> ()){
requestWithToken(url: "/post", method: .get, completion: { result in
guard let postJsonArray = result as? [Dictionary<String, AnyObject>] else { completion([]) ; return }
let json = postJsonArray.filter({ (post_json) -> Bool in
if let _ = Post.parseJson(post_json) {
return true
}else{
return false
}
})
let posts = json.map({ (post_json) -> Post in
return Post.parseJson(post_json)!
})
completion(posts)
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func fetchPost(post_id: String, controller: UIViewController, completion:@escaping (_ post:Optional<Post>) -> ()){
requestWithToken(url: "/post/\(post_id)", method: .get, completion: { result in
guard let json = result as? Dictionary<String, AnyObject> else { completion(.none) ; return }
completion(Post.parseJson(json))
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func likePost(post_id: String, controller: UIViewController, completion:@escaping (_ post:Optional<Post>) -> ()){
let user_id = User.fetch()!.id!
requestWithToken(url: "/post/\(post_id)/like/\(user_id)", method: .post, completion: { result in
guard let json = result as? Dictionary<String, AnyObject> else { completion(.none) ; return }
guard let json_post = json["post"] as? Dictionary<String, AnyObject> else{ completion(.none) ; return }
guard let json_user = json["user"] as? Dictionary<String, AnyObject> else{ completion(.none) ; return }
let _ = User.parseJson(json_user)
completion(Post.parseJson(json_post))
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func dislikePost(post_id: String, controller: UIViewController, completion:@escaping (_ post:Optional<Post>) -> ()){
let user_id = User.fetch()!.id!
requestWithToken(url: "/post/\(post_id)/like/\(user_id)", method: .delete, completion: { result in
guard let json = result as? Dictionary<String, AnyObject> else { completion(.none) ; return }
guard let json_post = json["post"] as? Dictionary<String, AnyObject> else{ completion(.none) ; return }
guard let json_user = json["user"] as? Dictionary<String, AnyObject> else{ completion(.none) ; return }
let _ = User.parseJson(json_user)
completion(Post.parseJson(json_post))
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func comment(post_id: String, comment: Comment, controller: UIViewController, completion:@escaping (_ post:Optional<Post>) -> ()){
let params = Comment.toJson(comment)
requestWithToken(url: "/post/\(post_id)/comment", method: .post, parameters: params as [String : AnyObject], completion: { result in
guard let json = result as? Dictionary<String, AnyObject> else { completion(.none) ; return }
completion(Post.parseJson(json))
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func uncomment(post_id: String, comment_id: String, controller: UIViewController, completion:@escaping (_ post:Optional<Post>) -> ()){
requestWithToken(url: "/post/\(post_id)/comment/\(comment_id)", method: .delete, completion: { result in
guard let json = result as? Dictionary<String, AnyObject> else { completion(.none) ; return }
completion(Post.parseJson(json))
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
static func report(comment: Comment, post: Post, controller: UIViewController){
requestWithToken(url: "/report/\(post.id!)/comment/\(comment.id!)", method: .put, completion: { (_) in
}) { (errorMessage, statusCode) in return controller.triggerError(errorMessage, statusCode) }
}
}
| mit | baf36c3d1eb9529361aa011f92405830 | 56.1625 | 145 | 0.638749 | 4.426912 | false | false | false | false |
tkausch/swiftalgorithms | CodePuzzles/RomanIntegers.playground/Contents.swift | 1 | 2193 | //: # Integer to Roman
//: **Question:** Given an integer, convert it to a roman numeral.
let romanNumbers = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100,"C"), (90,"XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
func intToRoman(_ num: Int) -> String {
var number = num
var result = ""
var idx = 0
while number > 0 {
if number - romanNumbers[idx].0 >= 0 {
result += romanNumbers[idx].1
number -= romanNumbers[idx].0
} else {
idx += 1
}
}
return result
}
intToRoman(2017)
intToRoman(9)
intToRoman(549)
//: # Roman to Integer
//: **Question:** Given an roman number, convert it to an integer.
func romanToInt(_ roman: String) -> Int {
var current = roman[roman.startIndex..<roman.endIndex]
var idx = 0
var number = 0
while !current.isEmpty {
let (delta, prefix) = romanNumbers[idx]
while current.starts(with: prefix) {
number += delta
current = current.dropFirst(prefix.count)
}
idx += 1
}
return number
}
//: We can do this even with a better runtime.
func value(char: Character) -> Int {
switch char {
case "M":
return 1000
case "D":
return 500
case "C":
return 100
case "L":
return 50
case "X":
return 10
case "V":
return 5
case "I":
return 1
default:
return -1
}
}
func romanToInt2(_ roman: String) -> Int {
var result = 0
var next = roman.startIndex
while next != roman.endIndex {
let valueNext = value(char: roman[next])
let next2 = roman.index(after: next)
if next2 != roman.endIndex {
let valueNext2 = value(char: roman[next2])
if valueNext >= valueNext2 {
result += valueNext
next = next2
} else {
result += valueNext2 - valueNext
next = roman.index(after: next2)
}
} else {
result += valueNext
next = next2
}
}
return result
}
romanToInt2("DXL")
romanToInt2("DXLIX")
| gpl-3.0 | f00951f3125650265d0e5218df87c65d | 24.5 | 168 | 0.517556 | 3.71066 | false | false | false | false |
btanner/Eureka | Source/Rows/TextAreaRow.swift | 6 | 14756 | // TextAreaRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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
// TODO: Temporary workaround for Xcode 10 beta
#if swift(>=4.2)
import UIKit.UIGeometry
extension UIEdgeInsets {
static let zero = UIEdgeInsets()
}
#endif
public enum TextAreaHeight {
case fixed(cellHeight: CGFloat)
case dynamic(initialTextViewHeight: CGFloat)
}
public enum TextAreaMode {
case normal
case readOnly
}
protocol TextAreaConformance: FormatterConformance {
var placeholder: String? { get set }
var textAreaHeight: TextAreaHeight { get set }
var titlePercentage: CGFloat? { get set}
}
/**
* Protocol for cells that contain a UITextView
*/
public protocol AreaCell: TextInputCell {
var textView: UITextView! { get }
}
extension AreaCell {
public var textInput: UITextInput {
return textView
}
}
open class _TextAreaCell<T> : Cell<T>, UITextViewDelegate, AreaCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textView: UITextView!
@IBOutlet public weak var placeholderLabel: UILabel?
private var awakeFromNibCalled = false
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let textView = UITextView()
self.textView = textView
textView.translatesAutoresizingMaskIntoConstraints = false
textView.keyboardType = .default
textView.font = .preferredFont(forTextStyle: .body)
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = UIEdgeInsets.zero
textView.backgroundColor = .clear
contentView.addSubview(textView)
let placeholderLabel = UILabel()
self.placeholderLabel = placeholderLabel
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
placeholderLabel.numberOfLines = 0
if #available(iOS 13.0, *) {
placeholderLabel.textColor = UIColor.tertiaryLabel
} else {
placeholderLabel.textColor = UIColor(white: 0, alpha: 0.22)
}
placeholderLabel.font = textView.font
contentView.addSubview(placeholderLabel)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
open var dynamicConstraints = [NSLayoutConstraint]()
open override func setup() {
super.setup()
let textAreaRow = row as! TextAreaConformance
switch textAreaRow.textAreaHeight {
case .dynamic(_):
height = { UITableView.automaticDimension }
textView.isScrollEnabled = false
case .fixed(let cellHeight):
height = { cellHeight }
}
textView.delegate = self
selectionStyle = .none
if !awakeFromNibCalled {
imageView?.addObserver(self, forKeyPath: "image", options: [.new, .old], context: nil)
}
setNeedsUpdateConstraints()
}
deinit {
textView?.delegate = nil
if !awakeFromNibCalled {
imageView?.removeObserver(self, forKeyPath: "image")
}
}
open override func update() {
super.update()
textLabel?.text = nil
detailTextLabel?.text = nil
textView.isEditable = !row.isDisabled
if #available(iOS 13.0, *) {
textView.textColor = row.isDisabled ? .tertiaryLabel : .label
} else {
textView.textColor = row.isDisabled ? .gray : .black
}
textView.text = row.displayValueFor?(row.value)
placeholderLabel?.text = (row as? TextAreaConformance)?.placeholder
placeholderLabel?.isHidden = textView.text.count != 0
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textView?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
// workaround to solve https://github.com/xmartlabs/Eureka/issues/887 UIKit issue
textView?.perform(#selector(UITextView.becomeFirstResponder), with: nil, afterDelay: 0.0)
return true
}
open override func cellResignFirstResponder() -> Bool {
return textView?.resignFirstResponder() ?? true
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey], obj === imageView && keyPathValue == "image" &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue, !awakeFromNibCalled {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
//Mark: Helpers
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textView?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textViewDidBeginEditing(_ textView: UITextView) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textView, cell: self)
if let textAreaConformance = (row as? TextAreaConformance), let _ = textAreaConformance.formatter, textAreaConformance.useFormatterOnDidBeginEditing ?? textAreaConformance.useFormatterDuringInput {
textView.text = self.displayValue(useFormatter: true)
} else {
textView.text = self.displayValue(useFormatter: false)
}
}
open func textViewDidEndEditing(_ textView: UITextView) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textView, cell: self)
textViewDidChange(textView)
textView.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textViewDidChange(_ textView: UITextView) {
if let textAreaConformance = row as? TextAreaConformance, case .dynamic = textAreaConformance.textAreaHeight, let tableView = formViewController()?.tableView {
let currentOffset = tableView.contentOffset
UIView.performWithoutAnimation {
tableView.beginUpdates()
tableView.endUpdates()
}
tableView.setContentOffset(currentOffset, animated: false)
}
placeholderLabel?.isHidden = textView.text.count != 0
guard let textValue = textView.text else {
row.value = nil
return
}
guard let formatterRow = row as? FormatterConformance, let formatter = formatterRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if formatterRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textView.selectedTextRange?.start else { return }
let oldVal = textView.text
textView.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textView, oldValue: oldVal, newValue: textView.text) ?? selStartPos
textView.selectedTextRange = textView.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
}
}
}
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return formViewController()?.textInput(textView, shouldChangeCharactersInRange: range, replacementString: text, cell: self) ?? true
}
open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if let textAreaRow = self.row as? _TextAreaRow, textAreaRow.textAreaMode == .readOnly {
return false
}
return formViewController()?.textInputShouldBeginEditing(textView, cell: self) ?? true
}
open func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return formViewController()?.textInputShouldEndEditing(textView, cell: self) ?? true
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String: AnyObject] = ["textView": textView, "label": placeholderLabel!]
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]", options: [], metrics: nil, views: views))
if let textAreaConformance = row as? TextAreaConformance, case .dynamic(let initialTextViewHeight) = textAreaConformance.textAreaHeight {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textView(>=initialHeight@800)]-|", options: [], metrics: ["initialHeight": initialTextViewHeight], views: views))
} else {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textView]-|", options: [], metrics: nil, views: views))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textView]-|", options: [], metrics: nil, views: views))
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-|", options: [], metrics: nil, views: views))
} else if let titlePercentage = (row as? TextAreaConformance)?.titlePercentage, titlePercentage > 0.0 {
textView.textAlignment = .right
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[textView]-|", options: [], metrics: nil, views: views)
let sideSpaces = (layoutMargins.right + layoutMargins.left)
dynamicConstraints.append(NSLayoutConstraint(item: textView!,
attribute: .width,
relatedBy: .equal,
toItem: contentView,
attribute: .width,
multiplier: 1 - titlePercentage,
constant: -sideSpaces))
} else {
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textView]-|", options: [], metrics: nil, views: views))
dynamicConstraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-|", options: [], metrics: nil, views: views))
}
contentView.addConstraints(dynamicConstraints)
}
}
open class TextAreaCell: _TextAreaCell<String>, CellType {
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
open class AreaRow<Cell: CellType>: FormatteableRow<Cell>, TextAreaConformance where Cell: BaseCell, Cell: AreaCell {
open var placeholder: String?
open var textAreaHeight = TextAreaHeight.fixed(cellHeight: 110)
open var textAreaMode = TextAreaMode.normal
/// The percentage of the cell that should be occupied by the remaining space to the left of the textArea. This is equivalent to the space occupied by a title in FieldRow, making the textArea aligned to fieldRows using the same titlePercentage. This behavior works only if the cell does not contain an image, due to its automatically set constraints in the cell.
open var titlePercentage: CGFloat?
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _TextAreaRow: AreaRow<TextAreaCell> {
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with a UITextView where the user can enter large text.
public final class TextAreaRow: _TextAreaRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 62c72eaf9721ca2883d384b6a4a5ef3d | 42.916667 | 366 | 0.670033 | 5.342505 | false | false | false | false |
devincoughlin/swift | test/Constraints/enum_cases.swift | 1 | 4614 | // RUN: %target-typecheck-verify-swift -swift-version 4
// See test/Compatibility/enum_cases.swift for Swift 3 behavior
enum E {
case foo(bar: String)
case bar(_: String)
case two(x: Int, y: Int)
case tuple((x: Int, y: Int))
}
enum G_E<T> {
case foo(bar: T)
case bar(_: T)
case two(x: T, y: T)
case tuple((x: T, y: T))
}
let arr: [String] = []
let _ = arr.map(E.foo) // Ok
let _ = arr.map(E.bar) // Ok
let _ = arr.map(E.two) // expected-error {{cannot invoke 'map' with an argument list of type '(@escaping (Int, Int) -> E)'}}
// expected-note@-1{{expected an argument list of type '((Self.Element) throws -> T)'}}
let _ = arr.map(E.tuple) // expected-error {{cannot invoke 'map' with an argument list of type '(@escaping ((x: Int, y: Int)) -> E)'}}
// expected-note@-1{{expected an argument list of type '((Self.Element) throws -> T)'}}
let _ = arr.map(G_E<String>.foo) // Ok
let _ = arr.map(G_E<String>.bar) // Ok
let _ = arr.map(G_E<String>.two) // expected-error {{cannot invoke 'map' with an argument list of type '(@escaping (String, String) -> G_E<String>)'}}
// expected-note@-1{{expected an argument list of type '((Self.Element) throws -> T)'}}
let _ = arr.map(G_E<Int>.tuple) // expected-error {{cannot invoke 'map' with an argument list of type '(@escaping ((x: Int, y: Int)) -> G_E<Int>)'}}
// expected-note@-1{{expected an argument list of type '((Self.Element) throws -> T)'}}
let _ = E.foo("hello") // expected-error {{missing argument label 'bar:' in call}}
let _ = E.bar("hello") // Ok
let _ = G_E<String>.foo("hello") // expected-error {{missing argument label 'bar:' in call}}
let _ = G_E<String>.bar("hello") // Ok
// Passing enum case as an argument to generic function
func bar_1<T>(_: (T) -> E) {}
func bar_2<T>(_: (T) -> G_E<T>) {}
func bar_3<T, U>(_: (T) -> G_E<U>) {}
bar_1(E.foo) // Ok
bar_1(E.bar) // Ok
// SE-0110: We reverted to allowing this for the time being, but this
// test is valuable in case we end up disallowing it again in the
// future.
bar_1(E.two) // Ok since we backed off on this aspect of SE-0110 for the moment.
bar_1(E.tuple) // Ok - it's going to be ((x: Int, y: Int))
bar_2(G_E<String>.foo) // Ok
bar_2(G_E<Int>.bar) // Ok
bar_2(G_E<Int>.two) // expected-error {{cannot convert value of type '(Int, Int) -> G_E<Int>' to expected argument type '(Int) -> G_E<Int>'}}
bar_2(G_E<Int>.tuple) // expected-error {{cannot convert value of type '((x: Int, y: Int)) -> G_E<Int>' to expected argument type '(_) -> G_E<_>'}}
bar_3(G_E<Int>.tuple) // Ok
// Regular enum case assigned as a value
let foo: (String) -> E = E.foo // Ok
let _ = foo("hello") // Ok
let bar: (String) -> E = E.bar // Ok
let _ = bar("hello") // Ok
let two: (Int, Int) -> E = E.two // Ok
let _ = two(0, 42) // Ok
let tuple: ((x: Int, y: Int)) -> E = E.tuple // Ok
let _ = tuple((x: 0, y: 42)) // Ok
// Generic enum case assigned as a value
let g_foo: (String) -> G_E<String> = G_E<String>.foo // Ok
let _ = g_foo("hello") // Ok
let g_bar: (String) -> G_E<String> = G_E<String>.bar // Ok
let _ = g_bar("hello") // Ok
let g_two: (Int, Int) -> G_E<Int> = G_E<Int>.two // Ok
let _ = g_two(0, 42) // Ok
let g_tuple: ((x: Int, y: Int)) -> G_E<Int> = G_E<Int>.tuple // Ok
let _ = g_tuple((x: 0, y: 42)) // Ok
enum Foo {
case a(x: Int)
case b(y: Int)
}
func foo<T>(_: T, _: T) {}
foo(Foo.a, Foo.b) // Ok in Swift 4 because we strip labels from the arguments
// rdar://problem/32551313 - Useless SE-0110 diagnostic
enum E_32551313<L, R> {
case Left(L)
case Right(R)
}
struct Foo_32551313 {
static func bar() -> E_32551313<(String, Foo_32551313?), (String, String)>? {
return E_32551313.Left("", Foo_32551313()) // expected-error {{enum case 'Left' expects a single parameter of type 'L' [with L = (String, Foo_32551313?)]}}
// expected-note@-1 {{did you mean to pass a tuple?}} {{28-28=(}} {{46-46=)}}
}
}
func rdar34583132() {
enum E {
case timeOut
}
struct S {
func foo(_ x: Int) -> E { return .timeOut }
}
func bar(_ s: S) {
guard s.foo(1 + 2) == .timeout else {
// expected-error@-1 {{enum type 'E' has no case 'timeout'; did you mean 'timeOut'}}
fatalError()
}
}
}
func rdar_49159472() {
struct A {}
struct B {}
struct C {}
enum E {
case foo(a: A, b: B?)
var foo: C? {
return nil
}
}
class Test {
var e: E
init(_ e: E) {
self.e = e
}
func bar() {
e = .foo(a: A(), b: nil) // Ok
e = E.foo(a: A(), b: nil) // Ok
baz(e: .foo(a: A(), b: nil)) // Ok
baz(e: E.foo(a: A(), b: nil)) // Ok
}
func baz(e: E) {}
}
}
| apache-2.0 | de55b14538180f35b4fbd53a9cfcde88 | 28.202532 | 159 | 0.576073 | 2.746429 | false | false | false | false |
barteljan/VISPER | VISPER-Reactive/Classes/Core/SubscriptionReferenceBag.swift | 1 | 2670 | //
// SubscriptionReferenceBag.swift
// ReactiveReSwift
//
// Created by Charlotte Tortorella on 29/11/16.
// Copyright © 2016 Benjamin Encz. All rights reserved.
//
/*
The MIT License (MIT)
Copyright (c) 2016 ReSwift Contributors
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.
*/
/**
A class to hold subscriptions to `SubscriptionReferenceType`.
Very similar to `autoreleasepool` but specifically for disposable types.
Disposes of all held subscriptions when deallocated or `dispose()` is called.
*/
public class SubscriptionReferenceBag {
fileprivate var references: [SubscriptionReferenceType] = []
/// Initialise an empty bag.
public init() {
}
/// Initialise the bag with an array of subscription references.
public init(_ references: SubscriptionReferenceType?...) {
#if swift(>=4.1)
self.references = references.compactMap({ $0 })
#else
self.references = references.flatMap({ $0 })
#endif
}
deinit {
dispose()
}
/// Add a new reference to the bag if the reference is not `nil`.
public func addReference(reference: SubscriptionReferenceType?) {
if let reference = reference {
references.append(reference)
}
}
/// Add a new reference to the bag if the reference is not `nil`.
public static func += (lhs: SubscriptionReferenceBag, rhs: SubscriptionReferenceType?) {
lhs.addReference(reference: rhs)
}
}
extension SubscriptionReferenceBag: SubscriptionReferenceType {
/// Dispose of all subscriptions in the bag.
public func dispose() {
references.forEach { $0.dispose() }
references = []
}
}
| mit | 64381417687435d28a751cd9087219ad | 41.365079 | 461 | 0.718247 | 4.826401 | false | false | false | false |
jimmy54/iRime | iRime/Keyboard/tasty-imitation-keyboard/Views/KeyboardConnector.swift | 1 | 8460 | //
// KeyboardConnector.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
protocol Connectable: class {
func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint)
func attachmentDirection() -> Direction?
func attach(_ direction: Direction?) // call with nil to detach
}
// TODO: Xcode crashes -- as of 2014-10-9, still crashes if implemented
// <ConnectableView: UIView where ConnectableView: Connectable>
class KeyboardConnector: KeyboardKeyBackground {
var start: UIView
var end: UIView
var startDir: Direction
var endDir: Direction
weak var startConnectable: Connectable?
weak var endConnectable: Connectable?
var convertedStartPoints: (CGPoint, CGPoint)!
var convertedEndPoints: (CGPoint, CGPoint)!
var offset: CGPoint
// TODO: until bug is fixed, make sure start/end and startConnectable/endConnectable are the same object
init(cornerRadius: CGFloat, underOffset: CGFloat, start s: UIView, end e: UIView, startConnectable sC: Connectable, endConnectable eC: Connectable, startDirection: Direction, endDirection: Direction) {
start = s
end = e
startDir = startDirection
endDir = endDirection
startConnectable = sC
endConnectable = eC
offset = CGPoint.zero
super.init(cornerRadius: cornerRadius, underOffset: underOffset)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.setNeedsLayout()
}
override func layoutSubviews() {
self.resizeFrame()
super.layoutSubviews()
}
func generateConvertedPoints() {
if self.startConnectable == nil || self.endConnectable == nil {
return
}
if let superview = self.superview {
let startPoints = self.startConnectable!.attachmentPoints(self.startDir)
let endPoints = self.endConnectable!.attachmentPoints(self.endDir)
self.convertedStartPoints = (
superview.convert(startPoints.0, from: self.start),
superview.convert(startPoints.1, from: self.start))
self.convertedEndPoints = (
superview.convert(endPoints.0, from: self.end),
superview.convert(endPoints.1, from: self.end))
}
}
func resizeFrame() {
generateConvertedPoints()
let buffer: CGFloat = 32
self.offset = CGPoint(x: buffer/2, y: buffer/2)
let minX = min(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let minY = min(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let maxX = max(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let maxY = max(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let width = maxX - minX
let height = maxY - minY
self.frame = CGRect(x: minX - buffer/2, y: minY - buffer/2, width: width + buffer, height: height + buffer)
}
override func generatePointsForDrawing(_ bounds: CGRect) {
if self.startConnectable == nil || self.endConnectable == nil {
return
}
//////////////////
// prepare data //
//////////////////
let startPoints = self.startConnectable!.attachmentPoints(self.startDir)
let endPoints = self.endConnectable!.attachmentPoints(self.endDir)
var myConvertedStartPoints = (
self.convert(startPoints.0, from: self.start),
self.convert(startPoints.1, from: self.start))
let myConvertedEndPoints = (
self.convert(endPoints.0, from: self.end),
self.convert(endPoints.1, from: self.end))
if self.startDir == self.endDir {
let tempPoint = myConvertedStartPoints.0
myConvertedStartPoints.0 = myConvertedStartPoints.1
myConvertedStartPoints.1 = tempPoint
}
let path = CGMutablePath();
// CGPathMoveToPoint(path, nil, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
path.move(to: CGPoint(x:myConvertedStartPoints.0.x, y:myConvertedStartPoints.0.y))
// CGPathAddLineToPoint(path, nil, myConvertedEndPoints.1.x, myConvertedEndPoints.1.y)
path.addLine(to: CGPoint(x:myConvertedEndPoints.1.x, y:myConvertedEndPoints.1.y))
// CGPathAddLineToPoint(path, nil, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
path.addLine(to: CGPoint(x:myConvertedEndPoints.0.x, y:myConvertedEndPoints.0.y))
// CGPathAddLineToPoint(path, nil, myConvertedStartPoints.1.x, myConvertedStartPoints.1.y)
path.addLine(to: CGPoint(x:myConvertedStartPoints.1.x, y:myConvertedStartPoints.1.y))
path.closeSubpath()
// for now, assuming axis-aligned attachment points
let isVertical = (self.startDir == Direction.up || self.startDir == Direction.down) && (self.endDir == Direction.up || self.endDir == Direction.down)
var midpoint: CGFloat
if isVertical {
midpoint = myConvertedStartPoints.0.y + (myConvertedEndPoints.1.y - myConvertedStartPoints.0.y) / 2
}
else {
midpoint = myConvertedStartPoints.0.x + (myConvertedEndPoints.1.x - myConvertedStartPoints.0.x) / 2
}
let bezierPath = UIBezierPath()
var currentEdgePath = UIBezierPath()
var edgePaths = [UIBezierPath]()
bezierPath.move(to: myConvertedStartPoints.0)
bezierPath.addCurve(
to: myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPoint(x: myConvertedStartPoints.0.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPoint(x: myConvertedEndPoints.1.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedEndPoints.1.y)))
currentEdgePath = UIBezierPath()
currentEdgePath.move(to: myConvertedStartPoints.0)
currentEdgePath.addCurve(
to: myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPoint(x: myConvertedStartPoints.0.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPoint(x: myConvertedEndPoints.1.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedEndPoints.1.y)))
currentEdgePath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
edgePaths.append(currentEdgePath)
bezierPath.addLine(to: myConvertedEndPoints.0)
bezierPath.addCurve(
to: myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPoint(x: myConvertedEndPoints.0.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPoint(x: myConvertedStartPoints.1.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedStartPoints.1.y)))
bezierPath.addLine(to: myConvertedStartPoints.0)
currentEdgePath = UIBezierPath()
currentEdgePath.move(to: myConvertedEndPoints.0)
currentEdgePath.addCurve(
to: myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPoint(x: myConvertedEndPoints.0.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPoint(x: myConvertedStartPoints.1.x, y: midpoint) :
CGPoint(x: midpoint, y: myConvertedStartPoints.1.y)))
currentEdgePath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
edgePaths.append(currentEdgePath)
bezierPath.addLine(to: myConvertedStartPoints.0)
bezierPath.close()
bezierPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
self.fillPath = bezierPath
self.edgePaths = edgePaths
}
}
| gpl-3.0 | f6f6bbcc340ef1333264d4689c6b56df | 40.268293 | 205 | 0.641844 | 4.787776 | false | false | false | false |
avito-tech/Marshroute | Marshroute/Sources/Transitions/TransitionContexts/TransitionsHandlerBox.swift | 1 | 2157 | /// Варианты хранения обработчика переходов показанного модуля
public enum TransitionsHandlerBox {
case animating(strongBox: StrongBox<AnimatingTransitionsHandler>)
case containing(strongBox: StrongBox<ContainingTransitionsHandler>)
// MARK: - Init
public init?(completedTransitionTargetTransitionsHandlerBox: CompletedTransitionTargetTransitionsHandlerBox)
{
switch completedTransitionTargetTransitionsHandlerBox {
case .animating(let weakBox):
if let animatingTransitionsHandler = weakBox.unbox() {
self = .init(animatingTransitionsHandler: animatingTransitionsHandler)
} else { return nil }
case .containing(let weakBox):
if let containingTransitionsHandler = weakBox.unbox() {
self = .init(containingTransitionsHandler: containingTransitionsHandler)
} else { return nil }
}
}
public init(animatingTransitionsHandler: AnimatingTransitionsHandler) {
self = .animating(strongBox: StrongBox<AnimatingTransitionsHandler>(animatingTransitionsHandler))
}
public init(containingTransitionsHandler: ContainingTransitionsHandler) {
self = .containing(strongBox: StrongBox<ContainingTransitionsHandler>(containingTransitionsHandler))
}
// MARK: - helpers
public func unbox() -> TransitionsHandler
{
switch self {
case .animating(let weakBox):
return weakBox.unbox()
case .containing(let weakBox):
return weakBox.unbox()
}
}
public func unboxAnimatingTransitionsHandler() -> AnimatingTransitionsHandler?
{
switch self {
case .animating(let weakBox):
return weakBox.unbox()
default:
return nil
}
}
public func unboxContainingTransitionsHandler() -> ContainingTransitionsHandler?
{
switch self {
case .containing(let weakBox):
return weakBox.unbox()
default:
return nil
}
}
}
| mit | 8668d001502644b8da634e9392c6d8d4 | 32.396825 | 112 | 0.649715 | 5.96034 | false | false | false | false |
silence0201/Swift-Study | GuidedTour/16AutomaticReferenceCounting.playground/Contents.swift | 1 | 4106 | //: Playground - noun: a place where people can play
// 引用计数
class Person{
let name: String
init(name: String){
self.name = name
print("\(name) is being init")
}
deinit {
print("\(name) is being deinit")
}
}
var reference1: Person?
var reference2: Person?
var reference3: Person?
reference1 = Person(name: "Jhnh")
reference2 = reference1
reference3 = reference1
reference1 = nil
reference2 = nil
reference3 = nil
// 循环引用
class Person2{
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit {
print("\(name) is being deinitialized")
}
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person2?
deinit { print("Apartment #\(unit) is being deinitialized") }
}
var john: Person2?
var unit4A: Apartment?
john = Person2(name: "John")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil
unit4A = nil
// 若引用
class Person3{
let name: String
init(name: String) {
self.name = name
}
var apartment: Apartment3?
deinit { print("\(name) is being deinitialized") }
}
class Apartment3{
let unit: String
init(unit: String) {
self.unit = unit
}
weak var tenant:Person3?
deinit {
print("Apartment #\(unit) is being deinitialized")
}
}
var james: Person3?
var number74: Apartment3?
james = Person3(name: "James Appleseed")
number74 = Apartment3(unit: "74")
james!.apartment = number74
number74!.tenant = james
james = nil
number74 = nil
// 无主引用
class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
deinit { print("\(name) is being deinitialized") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { print("Card #\(number) is being deinitialized") }
}
var justin: Customer?
justin = Customer(name: "Justin McIntyre")
justin!.card = CreditCard(number: 1234_5678_9012_3456, customer: justin!)
justin = nil
class Country {
let name: String
var capitalCity: City!
init(name: String, capitalName: String) {
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City {
let name: String
unowned let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}
var country = Country(name: "Canada", capitalName: "Ottawa")
print("\(country.name)'s capital city is called \(country.capitalCity.name)")
// 闭包循环引用
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
let heading = HTMLElement(name: "h1")
let defaultText = "some default text"
heading.asHTML = {
return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>"
}
print(heading.asHTML())
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
paragraph = nil
class HTMLElement2 {
let name: String
let text: String?
lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
var paragraph2: HTMLElement2? = HTMLElement2(name: "p", text: "hello, world")
print(paragraph2!.asHTML())
paragraph2 = nil
| mit | 4d59d8016db2bbf83d711e6739077cdb | 20.849462 | 78 | 0.614665 | 3.571178 | false | false | false | false |
tardieu/swift | stdlib/public/core/UnicodeScalar.swift | 9 | 13678 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// UnicodeScalar Type
//===----------------------------------------------------------------------===//
/// A Unicode scalar value.
///
/// The `UnicodeScalar` type, representing a single Unicode scalar value, is
/// the element type of a string's `unicodeScalars` collection.
///
/// You can create a `UnicodeScalar` instance by using a string literal that
/// contains a single character representing exactly one Unicode scalar value.
///
/// let letterK: UnicodeScalar = "K"
/// let kim: UnicodeScalar = "김"
/// print(letterK, kim)
/// // Prints "K 김"
///
/// You can also create Unicode scalar values directly from their numeric
/// representation.
///
/// let airplane = UnicodeScalar(9992)
/// print(airplane)
/// // Prints "✈︎"
@_fixed_layout
public struct UnicodeScalar :
_ExpressibleByBuiltinUnicodeScalarLiteral,
ExpressibleByUnicodeScalarLiteral {
@_versioned
var _value: UInt32
/// A numeric representation of the Unicode scalar.
public var value: UInt32 { return _value }
@_transparent
public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self._value = UInt32(value)
}
/// Creates a Unicode scalar with the specified value.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you use a string literal to initialize a `UnicodeScalar` instance.
///
/// let letterK: UnicodeScalar = "K"
/// print(letterK)
/// // Prints "K"
///
/// In this example, the assignment to the `letterK` constant is handled by
/// this initializer behind the scenes.
@_transparent
public init(unicodeScalarLiteral value: UnicodeScalar) {
self = value
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// - Parameter v: The Unicode code point to use for the scalar. `v` must be
/// a valid Unicode scalar value, in the range `0...0xD7FF` or
/// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is
/// returned.
///
/// For example, the following code sample creates a `UnicodeScalar` instance
/// with a value of an emoji character:
///
/// let codepoint: UInt32 = 127881
/// let emoji = UnicodeScalar(codepoint)
/// print(emoji!)
/// // Prints "🎉"
///
/// In case of an invalid input value, nil is returned.
///
/// let codepoint: UInt32 = extValue // This might be an invalid value.
/// if let emoji = UnicodeScalar(codepoint) {
/// print(emoji)
/// } else {
/// // Do something else
/// }
public init?(_ v: UInt32) {
// Unicode 6.3.0:
//
// D9. Unicode codespace: A range of integers from 0 to 10FFFF.
//
// D76. Unicode scalar value: Any Unicode code point except
// high-surrogate and low-surrogate code points.
//
// * As a result of this definition, the set of Unicode scalar values
// consists of the ranges 0 to D7FF and E000 to 10FFFF, inclusive.
if (v < 0xD800 || v > 0xDFFF) && v <= 0x10FFFF {
self._value = v
return
}
// Return nil in case of invalid unicode scalar value.
return nil
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// - Parameter v: The Unicode code point to use for the scalar. `v` must be
/// a valid Unicode scalar value, in the range `0...0xD7FF` or
/// `0xE000...0xFFFF`. In case of an invalid unicode scalar value, nil is
/// returned.
///
/// For example, the following code sample creates a `UnicodeScalar` instance
/// with a value of `밥`, the Korean word for rice:
///
/// let codepoint: UInt16 = 48165
/// let bap = UnicodeScalar(codepoint)
/// print(bap!)
/// // Prints "밥"
///
/// In case an invalid input value, nil is returned.
///
/// let codepoint: UInt32 = extValue // This might be an invalid value.
/// if let bap = UnicodeScalar(codepoint) {
/// print(bap)
/// } else {
/// // Do something else
/// }
public init?(_ v: UInt16) {
self.init(UInt32(v))
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// For example, the following code sample creates a `UnicodeScalar` instance
/// with a value of `7`:
///
/// let codepoint: UInt8 = 55
/// let seven = UnicodeScalar(codepoint)
/// print(seven!)
/// // Prints "7"
///
/// - Parameter v: The code point to use for the scalar.
public init(_ v: UInt8) {
self._value = UInt32(v)
}
/// Creates a duplicate of the given Unicode scalar.
public init(_ v: UnicodeScalar) {
// This constructor allows one to provide necessary type context to
// disambiguate between function overloads on 'String' and 'UnicodeScalar'.
self = v
}
/// Returns a string representation of the Unicode scalar.
///
/// Scalar values representing characters that are normally unprintable or
/// that otherwise require escaping are escaped with a backslash.
///
/// let tab = UnicodeScalar(9)
/// print(tab)
/// // Prints " "
/// print(tab.escaped(asASCII: false))
/// // Prints "\t"
///
/// When the `forceASCII` parameter is `true`, a `UnicodeScalar` instance
/// with a value greater than 127 is represented using an escaped numeric
/// value; otherwise, non-ASCII characters are represented using their
/// typical string value.
///
/// let bap = UnicodeScalar(48165)
/// print(bap.escaped(asASCII: false))
/// // Prints "밥"
/// print(bap.escaped(asASCII: true))
/// // Prints "\u{BC25}"
///
/// - Parameter forceASCII: Pass `true` if you need the result to use only
/// ASCII characters; otherwise, pass `false`.
/// - Returns: A string representation of the scalar.
public func escaped(asASCII forceASCII: Bool) -> String {
func lowNibbleAsHex(_ v: UInt32) -> String {
let nibble = v & 15
if nibble < 10 {
return String(UnicodeScalar(nibble+48)!) // 48 = '0'
} else {
// FIXME: was UnicodeScalar(nibble-10+65), which is now
// ambiguous. <rdar://problem/18506025>
return String(UnicodeScalar(nibble+65-10)!) // 65 = 'A'
}
}
if self == "\\" {
return "\\\\"
} else if self == "\'" {
return "\\\'"
} else if self == "\"" {
return "\\\""
} else if _isPrintableASCII {
return String(self)
} else if self == "\0" {
return "\\0"
} else if self == "\n" {
return "\\n"
} else if self == "\r" {
return "\\r"
} else if self == "\t" {
return "\\t"
} else if UInt32(self) < 128 {
return "\\u{"
+ lowNibbleAsHex(UInt32(self) >> 4)
+ lowNibbleAsHex(UInt32(self)) + "}"
} else if !forceASCII {
return String(self)
} else if UInt32(self) <= 0xFFFF {
var result = "\\u{"
result += lowNibbleAsHex(UInt32(self) >> 12)
result += lowNibbleAsHex(UInt32(self) >> 8)
result += lowNibbleAsHex(UInt32(self) >> 4)
result += lowNibbleAsHex(UInt32(self))
result += "}"
return result
} else {
// FIXME: Type checker performance prohibits this from being a
// single chained "+".
var result = "\\u{"
result += lowNibbleAsHex(UInt32(self) >> 28)
result += lowNibbleAsHex(UInt32(self) >> 24)
result += lowNibbleAsHex(UInt32(self) >> 20)
result += lowNibbleAsHex(UInt32(self) >> 16)
result += lowNibbleAsHex(UInt32(self) >> 12)
result += lowNibbleAsHex(UInt32(self) >> 8)
result += lowNibbleAsHex(UInt32(self) >> 4)
result += lowNibbleAsHex(UInt32(self))
result += "}"
return result
}
}
/// A Boolean value indicating whether the Unicode scalar is an ASCII
/// character.
///
/// ASCII characters have a scalar value between 0 and 127, inclusive. For
/// example:
///
/// let canyon = "Cañón"
/// for scalar in canyon.unicodeScalars {
/// print(scalar, scalar.isASCII, scalar.value)
/// }
/// // Prints "C true 67"
/// // Prints "a true 97"
/// // Prints "ñ false 241"
/// // Prints "ó false 243"
/// // Prints "n true 110"
public var isASCII: Bool {
return value <= 127
}
// FIXME: Is there a similar term of art in Unicode?
public var _isASCIIDigit: Bool {
return self >= "0" && self <= "9"
}
// FIXME: Unicode makes this interesting.
internal var _isPrintableASCII: Bool {
return (self >= UnicodeScalar(0o040) && self <= UnicodeScalar(0o176))
}
}
extension UnicodeScalar : CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the Unicode scalar.
public var description: String {
return String._fromWellFormedCodeUnitSequence(
UTF32.self,
input: repeatElement(self.value, count: 1))
}
/// An escaped textual representation of the Unicode scalar, suitable for
/// debugging.
public var debugDescription: String {
return "\"\(escaped(asASCII: true))\""
}
}
extension UnicodeScalar : LosslessStringConvertible {
public init?(_ description: String) {
let scalars = description.unicodeScalars
guard let v = scalars.first, scalars.count == 1 else {
return nil
}
self = v
}
}
extension UnicodeScalar : Hashable {
/// The Unicode scalar's hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
return Int(self.value)
}
}
extension UnicodeScalar {
/// Creates a Unicode scalar with the specified numeric value.
///
/// - Parameter v: The Unicode code point to use for the scalar. `v` must be
/// a valid Unicode scalar value, in the ranges `0...0xD7FF` or
/// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is
/// returned.
///
/// For example, the following code sample creates a `UnicodeScalar` instance
/// with a value of an emoji character:
///
/// let codepoint = 127881
/// let emoji = UnicodeScalar(codepoint)
/// print(emoji)
/// // Prints "🎉"
///
/// In case an invalid input value, nil is returned.
///
/// let codepoint: UInt32 = extValue // This might be an invalid value.
/// if let emoji = UnicodeScalar(codepoint) {
/// print(emoji)
/// } else {
/// // Do something else
/// }
public init?(_ v: Int) {
if let us = UnicodeScalar(UInt32(v)) {
self = us
} else {
return nil
}
}
}
extension UInt8 {
/// Construct with value `v.value`.
///
/// - Precondition: `v.value` can be represented as ASCII (0..<128).
public init(ascii v: UnicodeScalar) {
_precondition(v.value < 128,
"Code point value does not fit into ASCII")
self = UInt8(v.value)
}
}
extension UInt32 {
/// Construct with value `v.value`.
public init(_ v: UnicodeScalar) {
self = v.value
}
}
extension UInt64 {
/// Construct with value `v.value`.
public init(_ v: UnicodeScalar) {
self = UInt64(v.value)
}
}
extension UnicodeScalar : Equatable {
public static func == (lhs: UnicodeScalar, rhs: UnicodeScalar) -> Bool {
return lhs.value == rhs.value
}
}
extension UnicodeScalar : Comparable {
public static func < (lhs: UnicodeScalar, rhs: UnicodeScalar) -> Bool {
return lhs.value < rhs.value
}
}
extension UnicodeScalar {
public struct UTF16View {
internal var value: UnicodeScalar
}
public var utf16: UTF16View {
return UTF16View(value: self)
}
}
extension UnicodeScalar.UTF16View : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// The position of the first code unit.
public var startIndex: Int {
return 0
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Int {
return 0 + UTF16.width(value)
}
/// Accesses the code unit at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
public subscript(position: Int) -> UTF16.CodeUnit {
return position == 0 ? (
endIndex == 1 ? UTF16.CodeUnit(value.value) : UTF16.leadSurrogate(value)
) : UTF16.trailSurrogate(value)
}
}
/// Returns c as a UTF16.CodeUnit. Meant to be used as _ascii16("x").
public // SPI(SwiftExperimental)
func _ascii16(_ c: UnicodeScalar) -> UTF16.CodeUnit {
_sanityCheck(c.value >= 0 && c.value <= 0x7F, "not ASCII")
return UTF16.CodeUnit(c.value)
}
extension UnicodeScalar {
/// Creates an instance of the NUL scalar value.
@available(*, unavailable, message: "use 'UnicodeScalar(0)'")
public init() {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "escaped(asASCII:)")
public func escape(asASCII forceASCII: Bool) -> String {
Builtin.unreachable()
}
}
| apache-2.0 | 060bd074e020987e73d5e28065e5366f | 30.753488 | 81 | 0.613959 | 3.979598 | false | false | false | false |
mxcl/PromiseKit | Tests/CorePromise/GuaranteeTests.swift | 1 | 5176 | import PromiseKit
import XCTest
class GuaranteeTests: XCTestCase {
func testInit() {
let ex = expectation(description: "")
Guarantee { seal in
seal(1)
}.done {
XCTAssertEqual(1, $0)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testMap() {
let ex = expectation(description: "")
Guarantee.value(1).map {
$0 * 2
}.done {
XCTAssertEqual(2, $0)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testMapByKeyPath() {
let ex = expectation(description: "")
Guarantee.value(Person(name: "Max")).map(\.name).done {
XCTAssertEqual("Max", $0)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testWait() {
XCTAssertEqual(after(.milliseconds(100)).map(on: nil){ 1 }.wait(), 1)
}
func testMapValues() {
let ex = expectation(description: "")
Guarantee.value([1, 2, 3])
.mapValues { $0 * 2 }
.done { values in
XCTAssertEqual([2, 4, 6], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testMapValuesByKeyPath() {
let ex = expectation(description: "")
Guarantee.value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")])
.mapValues(\.name)
.done { values in
XCTAssertEqual(["Max", "Roman", "John"], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testFlatMapValues() {
let ex = expectation(description: "")
Guarantee.value([1, 2, 3])
.flatMapValues { [$0, $0] }
.done { values in
XCTAssertEqual([1, 1, 2, 2, 3, 3], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testCompactMapValues() {
let ex = expectation(description: "")
Guarantee.value(["1","2","a","3"])
.compactMapValues { Int($0) }
.done { values in
XCTAssertEqual([1, 2, 3], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testCompactMapValuesByKeyPath() {
let ex = expectation(description: "")
Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)])
.compactMapValues(\.age)
.done { values in
XCTAssertEqual([26, 23], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testThenMap() {
let ex = expectation(description: "")
Guarantee.value([1, 2, 3])
.thenMap { Guarantee.value($0 * 2) }
.done { values in
XCTAssertEqual([2, 4, 6], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testThenFlatMap() {
let ex = expectation(description: "")
Guarantee.value([1, 2, 3])
.thenFlatMap { Guarantee.value([$0, $0]) }
.done { values in
XCTAssertEqual([1, 1, 2, 2, 3, 3], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testFilterValues() {
let ex = expectation(description: "")
Guarantee.value([1, 2, 3])
.filterValues { $0 > 1 }
.done { values in
XCTAssertEqual([2, 3], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testFilterValuesByKeyPath() {
let ex = expectation(description: "")
Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)])
.filterValues(\.isStudent)
.done { values in
XCTAssertEqual([Person(name: "John", age: 23, isStudent: true)], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testSorted() {
let ex = expectation(description: "")
Guarantee.value([5, 2, 3, 4, 1])
.sortedValues()
.done { values in
XCTAssertEqual([1, 2, 3, 4, 5], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
func testSortedBy() {
let ex = expectation(description: "")
Guarantee.value([5, 2, 3, 4, 1])
.sortedValues { $0 > $1 }
.done { values in
XCTAssertEqual([5, 4, 3, 2, 1], values)
ex.fulfill()
}
wait(for: [ex], timeout: 10)
}
#if swift(>=3.1)
func testNoAmbiguityForValue() {
let ex = expectation(description: "")
let a = Guarantee<Void>.value
let b = Guarantee<Void>.value(Void())
let c = Guarantee<Void>.value(())
when(fulfilled: a, b, c).done {
ex.fulfill()
}.cauterize()
wait(for: [ex], timeout: 10)
}
#endif
}
| mit | f066a1d666e861f5fe770109f0b19665 | 24.24878 | 144 | 0.474884 | 4.130886 | false | true | false | false |
swghosh/infinnovation-stock-exchange-simulator-ios-app | Infinnovation Stock Exchange Simulator/FullStockItem.swift | 1 | 1021 | //
// FullStockItem.swift
// Infinnovation Stock Exchange Simulator
//
// Created by SwG Ghosh on 03/04/17.
// Copyright © 2017 infinnovation. All rights reserved.
//
class FullStockItem: StockItem {
// defines a data model for a stock item holds the full details of the stock
// inherits capabailities of StockItem
var pclose: Int
var ovalue: Int
var lcircuit: Int
var ucircuit: Int
var dividend: Int
var bvalue: Int
// initializer
init(name: String, current: Int, difference: Int, percentage: Double, sector: String, profile: String, pclose: Int, ovalue: Int, lcircuit: Int, ucircuit: Int, dividend: Int, bvalue: Int) {
self.pclose = pclose
self.ovalue = ovalue
self.lcircuit = lcircuit
self.ucircuit = ucircuit
self.dividend = dividend
self.bvalue = bvalue
super.init(name: name, current: current, difference: difference, percentage: percentage, sector: sector)
self.profile = profile
}
}
| mit | c201b2c3021ba24229fef0931c8dc344 | 30.875 | 192 | 0.661765 | 3.736264 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.