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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JerrySir/YCOA | YCOA/Main/Stock/View/StockVC_ItemTableViewCell.swift | 1 | 10130 | //
// StockVC_ItemTableViewCell.swift
// YCOA
//
// Created by Jerry on 2017/1/11.
// Copyright © 2017年 com.baochunsteel. All rights reserved.
//
import UIKit
import SnapKit
class StockVC_ItemTableViewCell: UITableViewCell {
// private var id_: String!
private var ownerLabelLeft: UILabel! //货主
private var owner: UILabel!
private var storageLocationLabelLeft: UILabel! //库位
private var storageLocation: UILabel!
private var supplierLabelLeft: UILabel! //供应商
private var supplier: UILabel!
private var materielLabelLeft: UILabel! //物料
private var materiel: UILabel!
private var specificationsLabelLeft: UILabel! //规格
private var specifications: UILabel!
private var stockQuantityLabelLeft: UILabel! //库存量
private var stockQuantity: UILabel!
private var actionButton: UIButton! //去处理按钮
private var BGView: UIView! //背景视图
/// 配置Cell
///
/// - Parameters:
/// - owner: 货主
/// - storageLocation: 库位
/// - supplier: 供应商
/// - materiel: 物料
/// - specifications: 规格
/// - stockQuantity: 库存量
/// - tap: 处理按钮点击事件,参数是id_
func configure(id_: String, owner: String, storageLocation: String, supplier: String, materiel: String, specifications: String, stockQuantity: String, tap: @escaping (_ id_: String)->Void)
{
// self.id_ = id_
self.owner.text = owner
self.storageLocation.text = storageLocation + storageLocation + storageLocation + storageLocation
self.supplier.text = supplier
self.materiel.text = materiel
self.specifications.text = specifications
self.stockQuantity.text = stockQuantity
self.actionButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (_) in
tap(id_)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.contentView.backgroundColor = UIColor.groupTableViewBackground
self.BGView = UIView()
self.contentView.addSubview(self.BGView)
self.BGView.backgroundColor = UIColor.white
self.BGView.layer.masksToBounds = true
self.BGView.layer.cornerRadius = 1/10
self.BGView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(8, 8, 8, 8))
}
self.ownerLabelLeft = UILabel()
self.BGView.addSubview(self.ownerLabelLeft)
self.ownerLabelLeft.text = "货主:"
self.ownerLabelLeft.textColor = UIColor.lightGray
self.ownerLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.ownerLabelLeft.snp.makeConstraints { (make) in
make.left.top.equalTo(8)
}
self.owner = UILabel()
self.BGView.addSubview(self.owner)
self.owner.text = ""
self.owner.textColor = UIColor.black
self.owner.font = UIFont.systemFont(ofSize: 15)
self.owner.numberOfLines = 0
self.owner.textAlignment = .right
self.owner.snp.makeConstraints { (make) in
make.left.equalTo(self.ownerLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.ownerLabelLeft)
}
self.storageLocationLabelLeft = UILabel()
self.BGView.addSubview(self.storageLocationLabelLeft)
self.storageLocationLabelLeft.text = "库位:"
self.storageLocationLabelLeft.textColor = UIColor.lightGray
self.storageLocationLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.storageLocationLabelLeft.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.owner.snp.bottom).offset(13)
make.height.equalTo(self.ownerLabelLeft.snp.height)
}
self.storageLocation = UILabel()
self.BGView.addSubview(self.storageLocation)
self.storageLocation.text = ""
self.storageLocation.textColor = UIColor.black
self.storageLocation.font = UIFont.systemFont(ofSize: 15)
self.storageLocation.numberOfLines = 0
self.storageLocation.textAlignment = .right
self.storageLocation.snp.makeConstraints { (make) in
make.left.equalTo(self.storageLocationLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.storageLocationLabelLeft)
}
self.supplierLabelLeft = UILabel()
self.BGView.addSubview(self.supplierLabelLeft)
self.supplierLabelLeft.text = "供应商:"
self.supplierLabelLeft.textColor = UIColor.lightGray
self.supplierLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.supplierLabelLeft.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.storageLocation.snp.bottom).offset(13)
make.height.equalTo(self.storageLocationLabelLeft.snp.height)
}
self.supplier = UILabel()
self.BGView.addSubview(self.supplier)
self.supplier.text = ""
self.supplier.textColor = UIColor.black
self.supplier.font = UIFont.systemFont(ofSize: 15)
self.supplier.numberOfLines = 0
self.supplier.textAlignment = .right
self.supplier.snp.makeConstraints { (make) in
make.left.equalTo(self.supplierLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.supplierLabelLeft)
}
self.materielLabelLeft = UILabel()
self.BGView.addSubview(self.materielLabelLeft)
self.materielLabelLeft.text = "物料:"
self.materielLabelLeft.textColor = UIColor.lightGray
self.materielLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.materielLabelLeft.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.supplier.snp.bottom).offset(13)
make.height.equalTo(self.supplierLabelLeft.snp.height)
}
self.materiel = UILabel()
self.BGView.addSubview(self.materiel)
self.materiel.text = ""
self.materiel.textColor = UIColor.black
self.materiel.font = UIFont.systemFont(ofSize: 15)
self.materiel.numberOfLines = 0
self.materiel.textAlignment = .right
self.materiel.snp.makeConstraints { (make) in
make.left.equalTo(self.materielLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.materielLabelLeft)
}
self.specificationsLabelLeft = UILabel()
self.BGView.addSubview(self.specificationsLabelLeft)
self.specificationsLabelLeft.text = "规格:"
self.specificationsLabelLeft.textColor = UIColor.lightGray
self.specificationsLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.specificationsLabelLeft.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.materiel.snp.bottom).offset(13)
make.height.equalTo(self.materielLabelLeft.snp.height)
}
self.specifications = UILabel()
self.BGView.addSubview(self.specifications)
self.specifications.text = ""
self.specifications.textColor = UIColor.black
self.specifications.font = UIFont.systemFont(ofSize: 15)
self.specifications.numberOfLines = 0
self.specifications.textAlignment = .right
self.specifications.snp.makeConstraints { (make) in
make.left.equalTo(self.specificationsLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.specificationsLabelLeft)
}
self.stockQuantityLabelLeft = UILabel()
self.BGView.addSubview(self.stockQuantityLabelLeft)
self.stockQuantityLabelLeft.text = "库存:"
self.stockQuantityLabelLeft.textColor = UIColor.lightGray
self.stockQuantityLabelLeft.font = UIFont.systemFont(ofSize: 15)
self.stockQuantityLabelLeft.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.specifications.snp.bottom).offset(13)
make.height.equalTo(self.specificationsLabelLeft.snp.height)
}
self.stockQuantity = UILabel()
self.BGView.addSubview(self.stockQuantity)
self.stockQuantity.text = ""
self.stockQuantity.textColor = UIColor.black
self.stockQuantity.font = UIFont.systemFont(ofSize: 15)
self.stockQuantity.numberOfLines = 0
self.stockQuantity.textAlignment = .right
self.stockQuantity.snp.makeConstraints { (make) in
make.left.equalTo(self.stockQuantityLabelLeft.snp.right).offset(8)
make.right.equalTo(-8)
make.top.equalTo(self.stockQuantityLabelLeft)
}
self.actionButton = UIButton(type: .custom)
self.BGView.addSubview(self.actionButton)
self.actionButton.setTitleColor(UIColor.blue, for: .normal)
self.actionButton.setTitle("去处理>>", for: .normal)
self.textLabel!.textColor = UIColor.blue
self.textLabel!.font = UIFont.systemFont(ofSize: 15)
self.actionButton.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(self.stockQuantity.snp.bottom).offset(8)
make.bottom.equalTo(-8)
make.height.equalTo(25)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 4d522fd560c6973959ac60441f8c3d07 | 38.820717 | 192 | 0.649525 | 4.640204 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | companion-iPad/Venue-companion/Controllers/BadgesViewController.swift | 1 | 2367 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
class BadgesViewController: UIViewController {
var challenges: [Challenge] = []
override func viewDidLoad() {
super.viewDidLoad()
guard let currentUser = ApplicationDataManager.sharedInstance.currentUser else {
return
}
// Do any additional setup after loading the view.
challenges = currentUser.challengesCompleted
if challenges.count < 4 {
// TODO: Think of better way to do this. This is not well optimized.
var challengeProgress: [Challenge: Double] = [:]
for challenge in ApplicationDataManager.sharedInstance.challenges {
var progress = 0
for neededTask in challenge.tasksNeeded {
for completedTask in currentUser.tasksCompleted {
if completedTask.id == neededTask {
progress++
}
}
}
challengeProgress[challenge] = Double(progress)/Double(challenge.tasksNeeded.count)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension BadgesViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return challenges.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("badgeCell", forIndexPath: indexPath) as? BadgeCollectionViewCell {
if let image = UIImage(named: challenges[indexPath.row].imageUrl) {
cell.imageView.image = image
}
return cell
}
return UICollectionViewCell()
}
}
extension BadgesViewController: UICollectionViewDelegate {
}
| epl-1.0 | 444992f078c4ce7a1d9669ef453f0cb9 | 29.333333 | 143 | 0.60355 | 6.394595 | false | false | false | false |
luzefeng/MLSwiftBasic | MLSwiftBasic/Classes/Base/MBBaseCommon.swift | 2 | 985 | // github: https://github.com/MakeZL/MLSwiftBasic
// author: @email <[email protected]>
//
// MBBaseCommon.swift
// MLSwiftBasic
//
// Created by 张磊 on 15/7/6.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
// 背景色
let BG_COLOR = UIColor(rgba: "e6e6e6")
// 返回按钮的图片名
let BACK_NAME = "nav_back"
// 自定义导航高度
let NAV_BAR_HEIGHT:CGFloat = 44
// 顶部的Y值
let NAV_BAR_Y:CGFloat = 20
// 按钮的宽度
let NAV_ITEM_LEFT_W:CGFloat = 45
let NAV_ITEM_RIGHT_W:CGFloat = 45
// 按钮的字体
let NAV_ITEM_FONT:UIFont = UIFont.systemFontOfSize(16)
// 标题的字体
let NAV_TITLE_FONT:UIFont = UIFont.systemFontOfSize(18)
// 字体的颜色
let NAV_TEXT_COLOR:UIColor = UIColor.whiteColor()
// 导航栏的颜色
let NAV_BG_COLOR = UIColor(rgba: "ff9814")
// 顶部的Y
let TOP_Y:CGFloat = (CGFloat((UIDevice.currentDevice().systemVersion as NSString).floatValue) >= 7.0) ? 64.0 : 44.0
// Margin
let MARGIN_8:CGFloat = 8.0
| mit | 38b69545e31a8ff3d8abd67d178d52b1 | 24.057143 | 115 | 0.700114 | 2.766562 | false | false | false | false |
naoyashiga/animated-tab-bar | RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift | 1 | 9358 | // AnimationTabBarController.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.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 UIKit
class RAMAnimatedTabBarItem: UITabBarItem {
@IBOutlet weak var animation: RAMItemAnimation!
@IBInspectable var textColor: UIColor = UIColor.blackColor()
func playAnimation(icon: UIImageView, textLabel: UILabel) {
assert(animation != nil, "add animation in UITabBarItem")
if animation != nil {
animation.playAnimation(icon, textLabel: textLabel)
}
}
func deselectAnimation(icon: UIImageView, textLabel: UILabel) {
if animation != nil {
animation.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor)
}
}
func selectedState(icon: UIImageView, textLabel: UILabel) {
if animation != nil {
animation.selectedState(icon, textLabel: textLabel)
}
}
}
class RAMAnimatedTabBarController: UITabBarController {
var iconsView: [(icon: UIImageView, textLabel: UILabel)] = Array()
// MARK: life circle
override func viewDidLoad() {
super.viewDidLoad()
let containers = createViewContainers()
createCustomIcons(containers)
}
// MARK: create methods
func createCustomIcons(containers : NSDictionary) {
if let items = tabBar.items {
let itemsCount = tabBar.items!.count as Int - 1
var index = 0
for item in self.tabBar.items as! [RAMAnimatedTabBarItem] {
assert(item.image != nil, "add image icon in UITabBarItem")
var container : UIView = containers["container\(itemsCount-index)"] as! UIView
container.tag = index
var icon = UIImageView(image: item.image)
icon.setTranslatesAutoresizingMaskIntoConstraints(false)
icon.tintColor = UIColor.clearColor()
// text
var textLabel = UILabel()
textLabel.text = item.title
textLabel.backgroundColor = UIColor.clearColor()
textLabel.textColor = item.textColor
textLabel.font = UIFont.systemFontOfSize(10)
textLabel.textAlignment = NSTextAlignment.Center
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
container.addSubview(icon)
createConstraints(icon, container: container, size: item.image!.size, yOffset: -5)
container.addSubview(textLabel)
let textLabelWidth = tabBar.frame.size.width / CGFloat(tabBar.items!.count) - 5.0
createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16)
let iconsAndLabels = (icon:icon, textLabel:textLabel)
iconsView.append(iconsAndLabels)
if 0 == index { // selected first elemet
item.selectedState(icon, textLabel: textLabel)
}
item.image = nil
item.title = ""
index++
}
}
}
func createConstraints(view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) {
var constX = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0)
container.addConstraint(constX)
var constY = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: yOffset)
container.addConstraint(constY)
var constW = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.width)
view.addConstraint(constW)
var constH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.height)
view.addConstraint(constH)
}
func createViewContainers() -> NSDictionary {
var containersDict = NSMutableDictionary()
let itemsCount : Int = tabBar.items!.count as Int - 1
for index in 0...itemsCount {
var viewContainer = createViewContainer()
containersDict.setValue(viewContainer, forKey: "container\(index)")
}
var keys = containersDict.allKeys
var formatString = "H:|-(0)-[container0]"
for index in 1...itemsCount {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
var constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
options:NSLayoutFormatOptions.DirectionRightToLeft,
metrics: nil,
views: containersDict as [NSObject : AnyObject])
view.addConstraints(constranints)
return containersDict
}
func createViewContainer() -> UIView {
var viewContainer = UIView();
viewContainer.backgroundColor = UIColor.clearColor() // for test
viewContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(viewContainer)
// add gesture
var tapGesture = UITapGestureRecognizer(target: self, action: "tapHandler:")
tapGesture.numberOfTouchesRequired = 1
viewContainer.addGestureRecognizer(tapGesture)
// add constrains
var constY = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0)
view.addConstraint(constY)
var constH = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: tabBar.frame.size.height)
viewContainer.addConstraint(constH)
return viewContainer
}
// MARK: actions
func tapHandler(gesture:UIGestureRecognizer) {
let items = tabBar.items as! [RAMAnimatedTabBarItem]
let currentIndex = gesture.view!.tag
if selectedIndex != currentIndex {
var animationItem : RAMAnimatedTabBarItem = items[currentIndex]
var icon = iconsView[currentIndex].icon
var textLabel = iconsView[currentIndex].textLabel
animationItem.playAnimation(icon, textLabel: textLabel)
let deselelectIcon = iconsView[selectedIndex].icon
let deselelectTextLabel = iconsView[selectedIndex].textLabel
let deselectItem = items[selectedIndex]
deselectItem.deselectAnimation(deselelectIcon, textLabel: deselelectTextLabel)
selectedIndex = gesture.view!.tag
}
}
func setSelectIndex(#from:Int,to:Int) {
self.selectedIndex = to
let items = self.tabBar.items as! [RAMAnimatedTabBarItem]
items[from].deselectAnimation(iconsView[from].icon, textLabel: iconsView[from].textLabel)
items[to].playAnimation(iconsView[to].icon, textLabel: iconsView[to].textLabel)
}
}
| mit | 7a4afebb302e4640906fd10f18d86076 | 37.352459 | 129 | 0.612738 | 5.650966 | false | false | false | false |
mcomella/prox | Prox/Prox/PlaceDetails/MapButton.swift | 1 | 1149 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class MapButton: UIButton {
private let shadowRadius: CGFloat = 3
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
let shadow = NSShadow()
shadow.shadowColor = Colors.detailsViewMapButtonShadow
shadow.shadowOffset = CGSize(width: 0.5, height: 0.75)
shadow.shadowBlurRadius = shadowRadius
// Drawing code
let ovalPath = UIBezierPath(ovalIn: CGRect(x: (shadowRadius / 2) - shadow.shadowOffset.width, y: (shadowRadius / 2) - shadow.shadowOffset.height, width: rect.width - shadowRadius, height: rect.height - shadowRadius))
context.saveGState()
context.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: (shadow.shadowColor as! UIColor).cgColor)
Colors.detailsViewMapButtonBackground.setFill()
ovalPath.fill()
context.restoreGState()
}
}
| mpl-2.0 | 35b7ce1706d5c0e150d31ec03724fa88 | 40.035714 | 225 | 0.693647 | 4.436293 | false | false | false | false |
cnoon/swift-compiler-crashes | crashes-duplicates/05274-swift-sourcemanager-getmessage.swift | 11 | 449 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
g: a {
protocol P {
class a {
let i: a {
typealias e : a {
typealias e : C {
var d where T where T {
}
class func f: a {
struct S<T : c {
let t: a {
let f = {
let f = [Void{
var d where T : a {
case c,
var d = [Void{
typealias e : NSObject {
typealias e == {
class
case c,
struct
| mit | d73f640488756cc3061e366ffbb73c3d | 16.96 | 87 | 0.659243 | 3.033784 | false | true | false | false |
tbkka/swift-protobuf | Sources/protoc-gen-swift/FileGenerator.swift | 3 | 8702 | // Sources/protoc-gen-swift/FileGenerator.swift - File-level generation logic
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This provides the logic for each file that is stored in the plugin request.
/// In particular, generateOutputFile() actually builds a Swift source file
/// to represent a single .proto input. Note that requests typically contain
/// a number of proto files that are not to be generated.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
class FileGenerator {
private let fileDescriptor: FileDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
var outputFilename: String {
let ext = ".pb.swift"
let pathParts = splitPath(pathname: fileDescriptor.name)
switch generatorOptions.outputNaming {
case .FullPath:
return pathParts.dir + pathParts.base + ext
case .PathToUnderscores:
let dirWithUnderscores =
pathParts.dir.replacingOccurrences(of: "/", with: "_")
return dirWithUnderscores + pathParts.base + ext
case .DropPath:
return pathParts.base + ext
}
}
init(fileDescriptor: FileDescriptor,
generatorOptions: GeneratorOptions) {
self.fileDescriptor = fileDescriptor
self.generatorOptions = generatorOptions
namer = SwiftProtobufNamer(currentFile: fileDescriptor,
protoFileToModuleMappings: generatorOptions.protoToModuleMappings)
}
/// Generate, if `errorString` gets filled in, then report error instead of using
/// what written into `printer`.
func generateOutputFile(printer p: inout CodePrinter, errorString: inout String?) {
guard fileDescriptor.fileOptions.swiftPrefix.isEmpty ||
isValidSwiftIdentifier(fileDescriptor.fileOptions.swiftPrefix,
allowQuoted: false) else {
errorString = "\(fileDescriptor.name) has an 'swift_prefix' that isn't a valid Swift identifier (\(fileDescriptor.fileOptions.swiftPrefix))."
return
}
p.print(
"// DO NOT EDIT.\n",
"// swift-format-ignore-file\n",
"//\n",
"// Generated by the Swift generator plugin for the protocol buffer compiler.\n",
"// Source: \(fileDescriptor.name)\n",
"//\n",
"// For information on using the generated types, please see the documentation:\n",
"// https://github.com/apple/swift-protobuf/\n",
"\n")
// Attempt to bring over the comments at the top of the .proto file as
// they likely contain copyrights/preamble/etc.
//
// The C++ FileDescriptor::GetSourceLocation(), says the location for
// the file is an empty path. That never seems to have comments on it.
// https://github.com/protocolbuffers/protobuf/issues/2249 opened to
// figure out the right way to do this since the syntax entry is
// optional.
let syntaxPath = IndexPath(index: Google_Protobuf_FileDescriptorProto.FieldNumbers.syntax)
if let syntaxLocation = fileDescriptor.sourceCodeInfoLocation(path: syntaxPath) {
let comments = syntaxLocation.asSourceComment(commentPrefix: "///",
leadingDetachedPrefix: "//")
if !comments.isEmpty {
p.print(comments)
// If the was a leading or tailing comment it won't have a blank
// line, after it, so ensure there is one.
if !comments.hasSuffix("\n\n") {
p.print("\n")
}
}
}
p.print("import Foundation\n")
if !fileDescriptor.isBundledProto {
// The well known types ship with the runtime, everything else needs
// to import the runtime.
p.print("import \(namer.swiftProtobufModuleName)\n")
}
if let neededImports = generatorOptions.protoToModuleMappings.neededModules(forFile: fileDescriptor) {
p.print("\n")
for i in neededImports {
p.print("import \(i)\n")
}
}
p.print("\n")
generateVersionCheck(printer: &p)
let extensionSet =
ExtensionSetGenerator(fileDescriptor: fileDescriptor,
generatorOptions: generatorOptions,
namer: namer)
extensionSet.add(extensionFields: fileDescriptor.extensions)
let enums = fileDescriptor.enums.map {
return EnumGenerator(descriptor: $0, generatorOptions: generatorOptions, namer: namer)
}
let messages = fileDescriptor.messages.map {
return MessageGenerator(descriptor: $0,
generatorOptions: generatorOptions,
namer: namer,
extensionSet: extensionSet)
}
for e in enums {
e.generateMainEnum(printer: &p)
e.generateCaseIterable(printer: &p)
}
for m in messages {
m.generateMainStruct(printer: &p, parent: nil, errorString: &errorString)
var caseIterablePrinter = CodePrinter()
m.generateEnumCaseIterable(printer: &caseIterablePrinter)
if !caseIterablePrinter.isEmpty {
p.print("\n#if swift(>=4.2)\n")
p.print(caseIterablePrinter.content)
p.print("\n#endif // swift(>=4.2)\n")
}
}
if !extensionSet.isEmpty {
let pathParts = splitPath(pathname: fileDescriptor.name)
let filename = pathParts.base + pathParts.suffix
p.print(
"\n",
"// MARK: - Extension support defined in \(filename).\n")
// Generate the Swift Extensions on the Messages that provide the api
// for using the protobuf extension.
extensionSet.generateMessageSwiftExtensions(printer: &p)
// Generate a registry for the file.
extensionSet.generateFileProtobufExtensionRegistry(printer: &p)
// Generate the Extension's declarations (used by the two above things).
//
// This is done after the other two as the only time developers will need
// these symbols is if they are manually building their own ExtensionMap;
// so the others are assumed more interesting.
extensionSet.generateProtobufExtensionDeclarations(printer: &p)
}
let protoPackage = fileDescriptor.package
let needsProtoPackage: Bool = !protoPackage.isEmpty && !messages.isEmpty
if needsProtoPackage || !enums.isEmpty || !messages.isEmpty {
p.print(
"\n",
"// MARK: - Code below here is support for the SwiftProtobuf runtime.\n")
if needsProtoPackage {
p.print(
"\n",
"fileprivate let _protobuf_package = \"\(protoPackage)\"\n")
}
for e in enums {
e.generateRuntimeSupport(printer: &p)
}
for m in messages {
m.generateRuntimeSupport(printer: &p, file: self, parent: nil)
}
}
}
private func generateVersionCheck(printer p: inout CodePrinter) {
let v = Version.compatibilityVersion
p.print(
"// If the compiler emits an error on this type, it is because this file\n",
"// was generated by a version of the `protoc` Swift plug-in that is\n",
"// incompatible with the version of SwiftProtobuf to which you are linking.\n",
"// Please ensure that you are building against the same version of the API\n",
"// that was used to generate this file.\n",
"fileprivate struct _GeneratedWithProtocGenSwiftVersion: \(namer.swiftProtobufModuleName).ProtobufAPIVersionCheck {\n")
p.indent()
p.print(
"struct _\(v): \(namer.swiftProtobufModuleName).ProtobufAPIVersion_\(v) {}\n",
"typealias Version = _\(v)\n")
p.outdent()
p.print("}\n")
}
}
| apache-2.0 | 6326ea72e38a1118faab5166895b2f53 | 42.293532 | 151 | 0.5886 | 5.28997 | false | false | false | false |
rhx/gir2swift | Sources/libgir2swift/models/gir elements/GirArgument.swift | 1 | 6300 | //
// GirArgument.swift
// gir2swift
//
// Created by Rene Hexel on 25/03/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020, 2022 Rene Hexel. All rights reserved.
//
import SwiftLibXML
extension GIR {
/// data type representing a function/method argument or return type
public class Argument: CType {
public override var kind: String { return "Argument" }
/// is this an instance parameter or return type?
public let instance: Bool
/// is this a varargs (...) parameter?
public let _varargs: Bool
/// is this a nullable parameter or return type?
public let isNullable: Bool
/// is this a parameter that can be ommitted?
public let allowNone: Bool
/// is this an optional (out) parameter?
public let isOptional: Bool
/// is this a caller-allocated (out) parameter?
public let callerAllocates: Bool
/// model of ownership transfer used
public let ownershipTransfer: OwnershipTransfer
/// whether this is an `in`, `out`, or `inout` parameter
public let direction: ParameterDirection
/// indicate whether the given parameter is varargs
public var varargs: Bool {
return _varargs || name.hasPrefix("...")
}
/// default constructor
/// - Parameters:
/// - name: The name of the `Argument` to initialise
/// - cname: C identifier
/// - type: The corresponding, underlying GIR type
/// - instance: `true` if this is an instance parameter
/// - comment: Documentation text for the type
/// - introspectable: Set to `true` if introspectable
/// - deprecated: Documentation on deprecation status if non-`nil`
/// - varargs: `true` if this is a varargs `(...)` parameter
/// - isNullable: `true` if this is a nullable parameter or return type
/// - allowNone: `true` if this parameter can be omitted
/// - isOptional: `true` if this is an optional (out) parameter
/// - callerAllocates: `true` if this is caller allocated
/// - ownershipTransfer: model of ownership transfer used
/// - direction: whether this is an `in`, `out`, or `inout` paramete
public init(name: String, cname:String, type: TypeReference, instance: Bool, comment: String, introspectable: Bool = false, deprecated: String? = nil, varargs: Bool = false, isNullable: Bool = false, allowNone: Bool = false, isOptional: Bool = false, callerAllocates: Bool = false, ownershipTransfer: OwnershipTransfer = .none, direction: ParameterDirection = .in) {
self.instance = instance
_varargs = varargs
self.isNullable = isNullable
self.allowNone = allowNone
self.isOptional = isOptional
self.callerAllocates = callerAllocates
self.ownershipTransfer = ownershipTransfer
self.direction = direction
super.init(name: name, cname: cname, type: type, comment: comment, introspectable: introspectable, deprecated: deprecated)
}
/// XML constructor
public init(node: XMLElement, at index: Int, defaultDirection: ParameterDirection = .in) {
instance = node.name.hasPrefix("instance")
_varargs = node.children.lazy.first(where: { $0.name == "varargs"}) != nil
let allowNone = node.attribute(named: "allow-none")
if let allowNone = allowNone, !allowNone.isEmpty && allowNone != "0" && allowNone != "false" {
self.allowNone = true
} else {
self.allowNone = false
}
if let nullable = node.attribute(named: "nullable") ?? allowNone, !nullable.isEmpty && nullable != "0" && nullable != "false" {
isNullable = true
} else {
isNullable = false
}
if let optional = node.attribute(named: "optional") ?? allowNone, !optional.isEmpty && optional != "0" && optional != "false" {
isOptional = true
} else {
isOptional = false
}
if let callerAlloc = node.attribute(named: "caller-allocates"), !callerAlloc.isEmpty && callerAlloc != "0" && callerAlloc != "false" {
callerAllocates = true
} else {
callerAllocates = false
}
ownershipTransfer = node.attribute(named: "transfer-ownership").flatMap { OwnershipTransfer(rawValue: $0) } ?? .none
direction = node.attribute(named: "direction").flatMap { ParameterDirection(rawValue: $0) } ?? defaultDirection
super.init(fromChildrenOf: node, at: index)
}
/// XML constructor for functions/methods/callbacks
public init(node: XMLElement, at index: Int, varargs: Bool, defaultDirection: ParameterDirection = .in) {
instance = node.name.hasPrefix("instance")
_varargs = varargs
let allowNone = node.attribute(named: "allow-none")
if let allowNone = allowNone, !allowNone.isEmpty && allowNone != "0" && allowNone != "false" {
self.allowNone = true
} else {
self.allowNone = false
}
if let nullable = node.attribute(named: "nullable") ?? allowNone, nullable != "0" && nullable != "false" {
isNullable = true
} else {
isNullable = false
}
if let optional = node.attribute(named: "optional") ?? allowNone, optional != "0" && optional != "false" {
isOptional = true
} else {
isOptional = false
}
if let callerAlloc = node.attribute(named: "caller-allocates"), callerAlloc != "0" && callerAlloc != "false" {
callerAllocates = true
} else {
callerAllocates = false
}
ownershipTransfer = node.attribute(named: "transfer-ownership").flatMap { OwnershipTransfer(rawValue: $0) } ?? .none
direction = node.attribute(named: "direction").flatMap { ParameterDirection(rawValue: $0) } ?? defaultDirection
super.init(node: node, at: index)
}
}
}
| bsd-2-clause | 66051873b9b94f696e8b39936a2378fb | 49.798387 | 374 | 0.587236 | 4.882946 | false | false | false | false |
viscovery/viscovery-ad-sdk-ios | ViscoveryADSDK/Classes/Vendor/Cartography/Align.swift | 10 | 8515 | //
// Align.swift
// Cartography
//
// Created by Robert Böhnke on 17/02/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
private func makeEqual<P: RelativeEquality>(by attribute: (LayoutProxy) -> P, elements: [LayoutProxy]) -> [NSLayoutConstraint] {
if let first = elements.first {
first.view.car_translatesAutoresizingMaskIntoConstraints = false
let rest = elements.dropFirst()
return rest.reduce([]) { acc, current in
current.view.car_translatesAutoresizingMaskIntoConstraints = false
return acc + [ attribute(first) == attribute(current) ]
}
} else {
return []
}
}
/// Aligns multiple views by their top edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(top views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.top }, elements: views)
}
/// Aligns multiple views by their right edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(right views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.right }, elements: views)
}
/// Aligns multiple views by their bottom edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(bottom views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.bottom }, elements: views)
}
/// Aligns multiple views by their left edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(left views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.left }, elements: views)
}
/// Aligns multiple views by their leading edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(leading views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.leading }, elements: views)
}
/// Aligns multiple views by their trailing edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(trailing views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.trailing }, elements: views)
}
/// Aligns multiple views by their horizontal center.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(centerX views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.centerX }, elements: views)
}
/// Aligns multiple views by their vertical center.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(centerY views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.centerY }, elements: views)
}
/// Aligns multiple views by their baseline.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter views: an array of views to align
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(baseline views: [LayoutProxy]) -> [NSLayoutConstraint] {
return makeEqual(by: { $0.baseline }, elements: views)
}
/// Aligns multiple views by their top edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(top first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(top: [first] + rest)
}
/// Aligns multiple views by their right edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(right first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(right: [first] + rest)
}
/// Aligns multiple views by their bottom edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(bottom first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(bottom: [first] + rest)
}
/// Aligns multiple views by their left edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(left first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(left: [first] + rest)
}
/// Aligns multiple views by their leading edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(leading first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(leading: [first] + rest)
}
/// Aligns multiple vies by their trailing edge.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(trailing first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(trailing: [first] + rest)
}
/// Aligns multiple views by their horizontal center.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(centerX first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(centerX: [first] + rest)
}
/// Aligns multiple views by their vertical center.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(centerY first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(centerY: [first] + rest)
}
/// Aligns multiple views by their baseline.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func align(baseline first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return align(baseline: [first] + rest)
}
| apache-2.0 | feed727296521feff37f1b57048f57a2 | 33.746939 | 128 | 0.71197 | 4.51618 | false | false | false | false |
jingwei-huang1/LayoutKit | LayoutKitTests/ButtonLayoutTests.swift | 3 | 4188 | // Copyright 2016 LinkedIn Corp.
// 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.
import XCTest
import LayoutKit
class ButtonLayoutTests: XCTestCase {
func testNeedsView() {
let b = ButtonLayout(type: .custom, title: "Hi").arrangement().makeViews()
XCTAssertNotNil(b as? UIButton)
}
func testButtonLayouts() {
let types: [ButtonLayoutType] = [
.custom,
.system,
.detailDisclosure,
.infoDark,
.infoLight,
.contactAdd,
]
let images: [ButtonLayoutImage] = [
.defaultImage,
.size(CGSize(width: 1, height: 1)),
.size(CGSize(width: 5, height: 5)),
.size(CGSize(width: 10, height: 10)),
.size(CGSize(width: 20, height: 20)),
]
let contentInsets: [UIEdgeInsets] = [
.zero,
UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1),
UIEdgeInsets(top: 20, left: 40, bottom: 20, right: 40), // default for tvOS system buttons
]
for textTestCase in Text.testCases {
for type in types {
for image in images {
for contentInset in contentInsets {
verifyButtonLayout(textTestCase: textTestCase, type: type, image: image, contentEdgeInsets: contentInset)
}
}
}
}
}
private func verifyButtonLayout(textTestCase: Text.TestCase, type: ButtonLayoutType, image: ButtonLayoutImage, contentEdgeInsets: UIEdgeInsets) {
guard case .unattributed(let title) = textTestCase.text else {
// TODO: ButtonLayout doesn't currently support attributed text.
// If/when it does, remove this guard.
return
}
let button = UIButton(type: type.buttonType)
button.contentEdgeInsets = contentEdgeInsets
if let font = textTestCase.font {
button.titleLabel?.font = font
}
switch textTestCase.text {
case .unattributed(let text):
button.setTitle(text, for: .normal)
case .attributed(let text):
button.setAttributedTitle(text, for: .normal)
}
switch image {
case .image(let image):
button.setImage(image, for: .normal)
case .size(let size):
if let image = imageOfSize(size) {
button.setImage(image, for: .normal)
}
case .defaultImage:
break
}
let layout = textTestCase.font.map({ (font: UIFont) -> Layout in
return ButtonLayout(type: type, title: title, image: image, font: font, contentEdgeInsets: contentEdgeInsets)
}) ?? ButtonLayout(type: type, title: title, image: image, contentEdgeInsets: contentEdgeInsets)
XCTAssertEqual(layout.arrangement().frame.size, button.intrinsicContentSize, "fontName:\(textTestCase.font?.fontName) title:'\(textTestCase.text)' image:\(image) fontSize:\(textTestCase.font?.pointSize) type:\(type) contentEdgeInsets:\(contentEdgeInsets)")
}
private func imageOfSize(_ size: CGSize) -> UIImage? {
if size == .zero {
return nil
}
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0.0)
UIColor.black.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
extension UIView {
var recursiveDescription: String {
var lines = [description]
for subview in subviews {
lines.append(" | \(subview.recursiveDescription)")
}
return lines.joined(separator: "\n")
}
}
| apache-2.0 | 2ba969c85614a7cc0675f78aff299e4c | 35.736842 | 264 | 0.604585 | 4.791762 | false | true | false | false |
Ribeiro/Swifter | SwifterCommon/SwifterOAuthClient.swift | 3 | 8230 | //
// SwifterOAuthClient.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Accounts
class SwifterOAuthClient: SwifterClientProtocol {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
var consumerKey: String
var consumerSecret: String
var credential: SwifterCredential?
var stringEncoding: NSStringEncoding
init(consumerKey: String, consumerSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.stringEncoding = NSUTF8StringEncoding
}
init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret)
self.credential = SwifterCredential(accessToken: credentialAccessToken)
self.stringEncoding = NSUTF8StringEncoding
}
func get(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let url = NSURL(string: path, relativeToURL: baseURL)
let method = "GET"
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: false)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.stringEncoding
request.start()
}
func post(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let url = NSURL(string: path, relativeToURL: baseURL)
let method = "POST"
var localParameters = parameters
var postData: NSData?
var postDataKey: String?
if let key : AnyObject = localParameters[Swifter.DataParameters.dataKey] {
postDataKey = key as? String
postData = localParameters[postDataKey!] as? NSData
localParameters.removeValueForKey(Swifter.DataParameters.dataKey)
localParameters.removeValueForKey(postDataKey!)
}
var postDataFileName: String?
if let fileName : AnyObject = localParameters[Swifter.DataParameters.fileNameKey] {
postDataFileName = fileName as? String
localParameters.removeValueForKey(postDataFileName!)
}
let request = SwifterHTTPRequest(URL: url, method: method, parameters: localParameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: localParameters, isMediaUpload: postData != nil)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.stringEncoding
if postData {
let fileName = postDataFileName ? postDataFileName! as String : "media.jpg"
request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName)
}
request.start()
}
func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, isMediaUpload: Bool) -> String {
var authorizationParameters = Dictionary<String, AnyObject>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = self.consumerKey
authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = NSUUID().UUIDString.bridgeToObjectiveC()
if self.credential?.accessToken {
authorizationParameters["oauth_token"] = self.credential!.accessToken!.key
}
for (key, value: AnyObject) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters.join(parameters)
let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters
authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken)
let authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.stringEncoding).componentsSeparatedByString("&") as String[]
authorizationParameterComponents.sort { $0 < $1 }
var headerComponents = String[]()
for component in authorizationParameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as String[]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + headerComponents.bridgeToObjectiveC().componentsJoinedByString(", ")
}
func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String {
var tokenSecret: NSString = ""
if token {
tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.stringEncoding)
}
let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.stringEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
let signingKeyData = signingKey.bridgeToObjectiveC().dataUsingEncoding(self.stringEncoding)
let parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.stringEncoding).componentsSeparatedByString("&") as String[]
parameterComponents.sort { $0 < $1 }
let parameterString = parameterComponents.bridgeToObjectiveC().componentsJoinedByString("&")
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.stringEncoding)
let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(self.stringEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
let signatureBaseStringData = signatureBaseString.dataUsingEncoding(self.stringEncoding)
return HMACSHA1Signature.signatureForKey(signingKeyData, data: signatureBaseStringData).base64EncodedStringWithOptions(nil)
}
} | mit | 03a03803eb0fa107d1f94bcd74a8121b | 46.304598 | 300 | 0.724301 | 5.739191 | false | false | false | false |
prajwalabove/VideoFeedAutoplayer | VideoFeedAutoplayer/VimeoModels/PRVimeoData.swift | 1 | 13258 | //
// PRVimeoData.swift
//
// Created by Prajwal on 08/11/2015
// Copyright (c) Above Solutions India Pvt Ltd. All rights reserved.
//
import Foundation
import SwiftyJSON
import ObjectMapper
public class PRVimeoData: NSObject, Mappable, NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kPRVimeoDataTitleKey: String = "title"
internal let kPRVimeoDataThumbnailLargeKey: String = "thumbnail_large"
internal let kPRVimeoDataThumbnailSmallKey: String = "thumbnail_small"
internal let kPRVimeoDataWidthKey: String = "width"
internal let kPRVimeoDataStatsNumberOfLikesKey: String = "stats_number_of_likes"
internal let kPRVimeoDataStatsNumberOfPlaysKey: String = "stats_number_of_plays"
internal let kPRVimeoDataDescriptionValueKey: String = "description"
internal let kPRVimeoDataDurationKey: String = "duration"
internal let kPRVimeoDataEmbedPrivacyKey: String = "embed_privacy"
internal let kPRVimeoDataUserPortraitSmallKey: String = "user_portrait_small"
internal let kPRVimeoDataThumbnailMediumKey: String = "thumbnail_medium"
internal let kPRVimeoDataUserNameKey: String = "user_name"
internal let kPRVimeoDataTagsKey: String = "tags"
internal let kPRVimeoDataMobileUrlKey: String = "mobile_url"
internal let kPRVimeoDataInternalIdentifierKey: String = "id"
internal let kPRVimeoDataStatsNumberOfCommentsKey: String = "stats_number_of_comments"
internal let kPRVimeoDataHeightKey: String = "height"
internal let kPRVimeoDataUserIdKey: String = "user_id"
internal let kPRVimeoDataUploadDateKey: String = "upload_date"
internal let kPRVimeoDataUserPortraitLargeKey: String = "user_portrait_large"
internal let kPRVimeoDataUserUrlKey: String = "user_url"
internal let kPRVimeoDataUserPortraitMediumKey: String = "user_portrait_medium"
internal let kPRVimeoDataUrlKey: String = "url"
internal let kPRVimeoDataUserPortraitHugeKey: String = "user_portrait_huge"
// MARK: Properties
public var title: String?
public var thumbnailLarge: String?
public var thumbnailSmall: String?
public var width: Int?
public var statsNumberOfLikes: Int?
public var statsNumberOfPlays: Int?
public var descriptionValue: String?
public var duration: Int?
public var embedPrivacy: String?
public var userPortraitSmall: String?
public var thumbnailMedium: String?
public var userName: String?
public var tags: String?
public var mobileUrl: String?
public var internalIdentifier: Int?
public var statsNumberOfComments: Int?
public var height: Int?
public var userId: Int?
public var uploadDate: String?
public var userPortraitLarge: String?
public var userUrl: String?
public var userPortraitMedium: String?
public var url: String?
public var userPortraitHuge: String?
// MARK: SwiftyJSON Initalizers
/**
Initates the class based on the object
- parameter object: The object of either Dictionary or Array kind that was passed.
- returns: An initalized instance of the class.
*/
convenience public init(object: AnyObject) {
self.init(json: JSON(object))
}
/**
Initates the class based on the JSON that was passed.
- parameter json: JSON object from SwiftyJSON.
- returns: An initalized instance of the class.
*/
public init(json: JSON) {
title = json[kPRVimeoDataTitleKey].string
thumbnailLarge = json[kPRVimeoDataThumbnailLargeKey].string
thumbnailSmall = json[kPRVimeoDataThumbnailSmallKey].string
width = json[kPRVimeoDataWidthKey].int
statsNumberOfLikes = json[kPRVimeoDataStatsNumberOfLikesKey].int
statsNumberOfPlays = json[kPRVimeoDataStatsNumberOfPlaysKey].int
descriptionValue = json[kPRVimeoDataDescriptionValueKey].string
duration = json[kPRVimeoDataDurationKey].int
embedPrivacy = json[kPRVimeoDataEmbedPrivacyKey].string
userPortraitSmall = json[kPRVimeoDataUserPortraitSmallKey].string
thumbnailMedium = json[kPRVimeoDataThumbnailMediumKey].string
userName = json[kPRVimeoDataUserNameKey].string
tags = json[kPRVimeoDataTagsKey].string
mobileUrl = json[kPRVimeoDataMobileUrlKey].string
internalIdentifier = json[kPRVimeoDataInternalIdentifierKey].int
statsNumberOfComments = json[kPRVimeoDataStatsNumberOfCommentsKey].int
height = json[kPRVimeoDataHeightKey].int
userId = json[kPRVimeoDataUserIdKey].int
uploadDate = json[kPRVimeoDataUploadDateKey].string
userPortraitLarge = json[kPRVimeoDataUserPortraitLargeKey].string
userUrl = json[kPRVimeoDataUserUrlKey].string
userPortraitMedium = json[kPRVimeoDataUserPortraitMediumKey].string
url = json[kPRVimeoDataUrlKey].string
userPortraitHuge = json[kPRVimeoDataUserPortraitHugeKey].string
}
// MARK: ObjectMapper Initalizers
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
required public init?(_ map: Map){
}
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
public func mapping(map: Map) {
title <- map["kPRVimeoDataTitleKey"]
thumbnailLarge <- map["kPRVimeoDataThumbnailLargeKey"]
thumbnailSmall <- map["kPRVimeoDataThumbnailSmallKey"]
width <- map["kPRVimeoDataWidthKey"]
statsNumberOfLikes <- map["kPRVimeoDataStatsNumberOfLikesKey"]
statsNumberOfPlays <- map["kPRVimeoDataStatsNumberOfPlaysKey"]
descriptionValue <- map["kPRVimeoDataDescriptionValueKey"]
duration <- map["kPRVimeoDataDurationKey"]
embedPrivacy <- map["kPRVimeoDataEmbedPrivacyKey"]
userPortraitSmall <- map["kPRVimeoDataUserPortraitSmallKey"]
thumbnailMedium <- map["kPRVimeoDataThumbnailMediumKey"]
userName <- map["kPRVimeoDataUserNameKey"]
tags <- map["kPRVimeoDataTagsKey"]
mobileUrl <- map["kPRVimeoDataMobileUrlKey"]
internalIdentifier <- map["kPRVimeoDataInternalIdentifierKey"]
statsNumberOfComments <- map["kPRVimeoDataStatsNumberOfCommentsKey"]
height <- map["kPRVimeoDataHeightKey"]
userId <- map["kPRVimeoDataUserIdKey"]
uploadDate <- map["kPRVimeoDataUploadDateKey"]
userPortraitLarge <- map["kPRVimeoDataUserPortraitLargeKey"]
userUrl <- map["kPRVimeoDataUserUrlKey"]
userPortraitMedium <- map["kPRVimeoDataUserPortraitMediumKey"]
url <- map["kPRVimeoDataUrlKey"]
userPortraitHuge <- map["kPRVimeoDataUserPortraitHugeKey"]
}
/**
Generates description of the object in the form of a NSDictionary.
- returns: A Key value pair containing all valid values in the object.
*/
public func dictionaryRepresentation() -> [String : AnyObject] {
var dictionary: [String : AnyObject] = [ : ]
if title != nil {
dictionary.updateValue(title!, forKey: kPRVimeoDataTitleKey)
}
if thumbnailLarge != nil {
dictionary.updateValue(thumbnailLarge!, forKey: kPRVimeoDataThumbnailLargeKey)
}
if thumbnailSmall != nil {
dictionary.updateValue(thumbnailSmall!, forKey: kPRVimeoDataThumbnailSmallKey)
}
if width != nil {
dictionary.updateValue(width!, forKey: kPRVimeoDataWidthKey)
}
if statsNumberOfLikes != nil {
dictionary.updateValue(statsNumberOfLikes!, forKey: kPRVimeoDataStatsNumberOfLikesKey)
}
if statsNumberOfPlays != nil {
dictionary.updateValue(statsNumberOfPlays!, forKey: kPRVimeoDataStatsNumberOfPlaysKey)
}
if descriptionValue != nil {
dictionary.updateValue(descriptionValue!, forKey: kPRVimeoDataDescriptionValueKey)
}
if duration != nil {
dictionary.updateValue(duration!, forKey: kPRVimeoDataDurationKey)
}
if embedPrivacy != nil {
dictionary.updateValue(embedPrivacy!, forKey: kPRVimeoDataEmbedPrivacyKey)
}
if userPortraitSmall != nil {
dictionary.updateValue(userPortraitSmall!, forKey: kPRVimeoDataUserPortraitSmallKey)
}
if thumbnailMedium != nil {
dictionary.updateValue(thumbnailMedium!, forKey: kPRVimeoDataThumbnailMediumKey)
}
if userName != nil {
dictionary.updateValue(userName!, forKey: kPRVimeoDataUserNameKey)
}
if tags != nil {
dictionary.updateValue(tags!, forKey: kPRVimeoDataTagsKey)
}
if mobileUrl != nil {
dictionary.updateValue(mobileUrl!, forKey: kPRVimeoDataMobileUrlKey)
}
if internalIdentifier != nil {
dictionary.updateValue(internalIdentifier!, forKey: kPRVimeoDataInternalIdentifierKey)
}
if statsNumberOfComments != nil {
dictionary.updateValue(statsNumberOfComments!, forKey: kPRVimeoDataStatsNumberOfCommentsKey)
}
if height != nil {
dictionary.updateValue(height!, forKey: kPRVimeoDataHeightKey)
}
if userId != nil {
dictionary.updateValue(userId!, forKey: kPRVimeoDataUserIdKey)
}
if uploadDate != nil {
dictionary.updateValue(uploadDate!, forKey: kPRVimeoDataUploadDateKey)
}
if userPortraitLarge != nil {
dictionary.updateValue(userPortraitLarge!, forKey: kPRVimeoDataUserPortraitLargeKey)
}
if userUrl != nil {
dictionary.updateValue(userUrl!, forKey: kPRVimeoDataUserUrlKey)
}
if userPortraitMedium != nil {
dictionary.updateValue(userPortraitMedium!, forKey: kPRVimeoDataUserPortraitMediumKey)
}
if url != nil {
dictionary.updateValue(url!, forKey: kPRVimeoDataUrlKey)
}
if userPortraitHuge != nil {
dictionary.updateValue(userPortraitHuge!, forKey: kPRVimeoDataUserPortraitHugeKey)
}
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey(kPRVimeoDataTitleKey) as? String
self.thumbnailLarge = aDecoder.decodeObjectForKey(kPRVimeoDataThumbnailLargeKey) as? String
self.thumbnailSmall = aDecoder.decodeObjectForKey(kPRVimeoDataThumbnailSmallKey) as? String
self.width = aDecoder.decodeObjectForKey(kPRVimeoDataWidthKey) as? Int
self.statsNumberOfLikes = aDecoder.decodeObjectForKey(kPRVimeoDataStatsNumberOfLikesKey) as? Int
self.statsNumberOfPlays = aDecoder.decodeObjectForKey(kPRVimeoDataStatsNumberOfPlaysKey) as? Int
self.descriptionValue = aDecoder.decodeObjectForKey(kPRVimeoDataDescriptionValueKey) as? String
self.duration = aDecoder.decodeObjectForKey(kPRVimeoDataDurationKey) as? Int
self.embedPrivacy = aDecoder.decodeObjectForKey(kPRVimeoDataEmbedPrivacyKey) as? String
self.userPortraitSmall = aDecoder.decodeObjectForKey(kPRVimeoDataUserPortraitSmallKey) as? String
self.thumbnailMedium = aDecoder.decodeObjectForKey(kPRVimeoDataThumbnailMediumKey) as? String
self.userName = aDecoder.decodeObjectForKey(kPRVimeoDataUserNameKey) as? String
self.tags = aDecoder.decodeObjectForKey(kPRVimeoDataTagsKey) as? String
self.mobileUrl = aDecoder.decodeObjectForKey(kPRVimeoDataMobileUrlKey) as? String
self.internalIdentifier = aDecoder.decodeObjectForKey(kPRVimeoDataInternalIdentifierKey) as? Int
self.statsNumberOfComments = aDecoder.decodeObjectForKey(kPRVimeoDataStatsNumberOfCommentsKey) as? Int
self.height = aDecoder.decodeObjectForKey(kPRVimeoDataHeightKey) as? Int
self.userId = aDecoder.decodeObjectForKey(kPRVimeoDataUserIdKey) as? Int
self.uploadDate = aDecoder.decodeObjectForKey(kPRVimeoDataUploadDateKey) as? String
self.userPortraitLarge = aDecoder.decodeObjectForKey(kPRVimeoDataUserPortraitLargeKey) as? String
self.userUrl = aDecoder.decodeObjectForKey(kPRVimeoDataUserUrlKey) as? String
self.userPortraitMedium = aDecoder.decodeObjectForKey(kPRVimeoDataUserPortraitMediumKey) as? String
self.url = aDecoder.decodeObjectForKey(kPRVimeoDataUrlKey) as? String
self.userPortraitHuge = aDecoder.decodeObjectForKey(kPRVimeoDataUserPortraitHugeKey) as? String
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: kPRVimeoDataTitleKey)
aCoder.encodeObject(thumbnailLarge, forKey: kPRVimeoDataThumbnailLargeKey)
aCoder.encodeObject(thumbnailSmall, forKey: kPRVimeoDataThumbnailSmallKey)
aCoder.encodeObject(width, forKey: kPRVimeoDataWidthKey)
aCoder.encodeObject(statsNumberOfLikes, forKey: kPRVimeoDataStatsNumberOfLikesKey)
aCoder.encodeObject(statsNumberOfPlays, forKey: kPRVimeoDataStatsNumberOfPlaysKey)
aCoder.encodeObject(descriptionValue, forKey: kPRVimeoDataDescriptionValueKey)
aCoder.encodeObject(duration, forKey: kPRVimeoDataDurationKey)
aCoder.encodeObject(embedPrivacy, forKey: kPRVimeoDataEmbedPrivacyKey)
aCoder.encodeObject(userPortraitSmall, forKey: kPRVimeoDataUserPortraitSmallKey)
aCoder.encodeObject(thumbnailMedium, forKey: kPRVimeoDataThumbnailMediumKey)
aCoder.encodeObject(userName, forKey: kPRVimeoDataUserNameKey)
aCoder.encodeObject(tags, forKey: kPRVimeoDataTagsKey)
aCoder.encodeObject(mobileUrl, forKey: kPRVimeoDataMobileUrlKey)
aCoder.encodeObject(internalIdentifier, forKey: kPRVimeoDataInternalIdentifierKey)
aCoder.encodeObject(statsNumberOfComments, forKey: kPRVimeoDataStatsNumberOfCommentsKey)
aCoder.encodeObject(height, forKey: kPRVimeoDataHeightKey)
aCoder.encodeObject(userId, forKey: kPRVimeoDataUserIdKey)
aCoder.encodeObject(uploadDate, forKey: kPRVimeoDataUploadDateKey)
aCoder.encodeObject(userPortraitLarge, forKey: kPRVimeoDataUserPortraitLargeKey)
aCoder.encodeObject(userUrl, forKey: kPRVimeoDataUserUrlKey)
aCoder.encodeObject(userPortraitMedium, forKey: kPRVimeoDataUserPortraitMediumKey)
aCoder.encodeObject(url, forKey: kPRVimeoDataUrlKey)
aCoder.encodeObject(userPortraitHuge, forKey: kPRVimeoDataUserPortraitHugeKey)
}
}
| gpl-2.0 | eddab86e86446abacd6dcdc558536b89 | 44.717241 | 104 | 0.795293 | 4.935964 | false | false | false | false |
kaideyi/KDYSample | KYChat/KYChat/BizsClass/Conversation/Controller/KYConversationController+Delegate.swift | 1 | 3058 | //
// KYConversationController+Delegate.swift
// KYChat
//
// Created by KYCoder on 2017/9/5.
// Copyright © 2017年 mac. All rights reserved.
//
import Foundation
// MARK: - UITableViewDataSource
extension KYConversationController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ConversationCell = tableView.dequeueReusableCell(for: indexPath)
cell.model = dataSource[indexPath.row] as! ConversationModel
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "删除"
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let model = dataSource[indexPath.row] as! ConversationModel
let alertController = UIAlertController(title: "删除将清空该聊天的消息记录", message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { (alert) in
// 删除数据源
EMClient.shared().chatManager.deleteConversation(model.conversation.conversationId, isDeleteMessages: true, completion: nil)
self.dataSource.removeObject(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .top)
// 更新未读消息数
let unReadCounts = Int(model.conversation.unreadMessagesCount)
var badgeNumber = UIApplication.shared.applicationIconBadgeNumber
badgeNumber -= unReadCounts
if badgeNumber > 0 {
UIApplication.shared.applicationIconBadgeNumber = badgeNumber
self.tabBarItem.badgeValue = String(format: "%d", badgeNumber)
} else {
UIApplication.shared.applicationIconBadgeNumber = 0
self.tabBarItem.badgeValue = nil
}
}))
alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: - UITableViewDelegate
extension KYConversationController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - EMChatManagerDelegate
extension KYConversationController: EMChatManagerDelegate {
}
| mit | 41d332ea4d633e144e5e5ce5085346c6 | 35.5 | 140 | 0.637153 | 5.563197 | false | false | false | false |
gbuela/kanjiryokucha | KanjiRyokucha/KoohiiRequest.swift | 1 | 5901 | //
// KoohiiRequest.swift
// KanjiRyokucha
//
// Created by German Buela on 2/12/17.
// Copyright © 2017 German Buela. All rights reserved.
//
import Foundation
import ReactiveSwift
enum BuildType {
case production
case development
case staging
}
let buildType: BuildType = {
if let buildType = Bundle.main.infoDictionary?["BUILDTYPE"] as? String {
if buildType == "DEV" {
return .development
} else if buildType == "STAGING" {
return .staging
} else if buildType == "PROD" {
return .production
}
}
fatalError("Undefined or unknown BUILDTYPE in Info.plist!")
}()
protocol BackendAccess {
var backendDomain: String { get }
var backendProtocol: String { get }
var backendHost: String { get }
}
extension BackendAccess {
var backendDomain: String {
switch buildType {
case .production:
return "kanji.koohii.com"
case .development:
return "localhost:8888"
case .staging:
return "staging.koohii.com"
}
}
var backendProtocol: String {
switch buildType {
case .development:
return "http"
default:
return "https"
}
}
var backendHost: String {
return backendProtocol + "://" + backendDomain
}
}
protocol KoohiiRequest : Request, BackendAccess {
var endpoint: String { get }
}
extension KoohiiRequest {
var endpoint: String {
return backendHost + "/api/v1/"
}
}
extension KoohiiRequest {
private func isSessionExpired(data: Data) -> Bool {
let decoder = JSONDecoder()
let statResult: StatResult
do {
statResult = try decoder.decode(StatResult.self, from: data)
if statResult.status == "fail",
statResult.code == 96 {
return true
}
return false
} catch {
return false
}
}
func requestProducer() -> SignalProducer<Response, FetchError>? {
guard let rq = self.urlRequest else {
return nil
}
return SignalProducer { sink, disposable in
let session = URLSession.init(configuration: .default,
delegate: NoRedirectSessionDelegate(),
delegateQueue: .main)
Global.latestRequestDate = Date()
let task = session.dataTask(with: rq) { (data, response, error) -> Void in
let status = self.statusCode(response)
let headers = self.headerFields(response)
switch (data, error) {
case (_, let error?):
log("task failed! \(error)")
sink.send(error: .connectionError(error: error))
case (let data?, _):
log("task completed")
if self.isSessionExpired(data: data) {
log("Session expired found in \(self.apiMethod)")
if self is AccountInfoRequest {
log("Delaying expiration result")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
sink.send(error: .notAuthenticated)
NotificationCenter.default.post(name: NSNotification.Name(sessionExpiredNotification), object: nil)
})
} else {
sink.send(error: .notAuthenticated)
NotificationCenter.default.post(name: NSNotification.Name(sessionExpiredNotification), object: nil)
}
}
else {
let model = self.modelFrom(data: data)
let resp = Response(statusCode: status,
string: String(data:data, encoding:.utf8),
data: data,
model: model,
headers: headers,
originatingRequest: self)
resp.saveCookies()
sink.send(value: resp)
sink.sendCompleted()
}
default:
sink.sendCompleted()
}
}
log("launching task " + (rq.url?.absoluteString ?? ""))
task.resume()
session.finishTasksAndInvalidate()
}
}
}
private extension KoohiiRequest {
var isApiPublic: Bool {
return true
}
var urlRequest: URLRequest? {
let qsParams = sendApiKey && !isApiPublic ? querystringParams.merged(with: ["api_key":ApiKeys.koohii]) : querystringParams
let uriQs = (useEndpoint ? endpoint : backendHost) + apiMethod + "?" + joinParams(qsParams)
guard let url = URL(string: uriQs),
let bodyParams = self.httpBodyParams else {
return nil
}
var rq = URLRequest(url: url)
rq.httpMethod = self.httpMethod
rq.httpBody = contentType == .json ? jsonObject?.toJsonData() : bodyParams
rq.cachePolicy = .reloadIgnoringLocalCacheData
for header in headers {
rq.setValue(header.value, forHTTPHeaderField: header.key)
}
rq.setValue(contentTypeValue(contentType: contentType), forHTTPHeaderField: HeaderKeys.contentType)
rq.setValue("utf-8", forHTTPHeaderField: HeaderKeys.charset)
return rq
}
}
| mit | 8969a04f2cf8d8199a193b6df7e166ca | 31.596685 | 131 | 0.507627 | 5.383212 | false | false | false | false |
lorentey/swift | test/decl/class/override.swift | 28 | 22073 | // RUN: %target-typecheck-verify-swift -parse-as-library -enable-objc-interop
class A {
func ret_sametype() -> Int { return 0 }
func ret_subclass() -> A { return self }
func ret_subclass_rev() -> B { return B() }
func ret_nonclass_optional() -> Int? { return .none }
func ret_nonclass_optional_rev() -> Int { return 0 }
func ret_class_optional() -> B? { return .none }
func ret_class_optional_rev() -> A { return self }
func ret_class_uoptional() -> B! { return B() }
func ret_class_uoptional_rev() -> A { return self }
func ret_class_optional_uoptional() -> B? { return .none }
func ret_class_optional_uoptional_rev() -> A! { return self }
func param_sametype(_ x : Int) {}
func param_subclass(_ x : B) {}
func param_subclass_rev(_ x : A) {}
func param_nonclass_optional(_ x : Int) {}
func param_nonclass_optional_rev(_ x : Int?) {}
func param_class_optional(_ x : B) {}
func param_class_optional_rev(_ x : B?) {}
func param_class_uoptional(_ x : B) {}
func param_class_uoptional_rev(_ x : B!) {}
func param_class_optional_uoptional(_ x : B!) {}
func param_class_optional_uoptional_rev(_ x : B?) {}
}
class B : A {
override func ret_sametype() -> Int { return 1 }
override func ret_subclass() -> B { return self }
func ret_subclass_rev() -> A { return self }
override func ret_nonclass_optional() -> Int { return 0 }
func ret_nonclass_optional_rev() -> Int? { return 0 }
override func ret_class_optional() -> B { return self }
func ret_class_optional_rev() -> A? { return self }
override func ret_class_uoptional() -> B { return self }
func ret_class_uoptional_rev() -> A! { return self }
override func ret_class_optional_uoptional() -> B! { return self }
override func ret_class_optional_uoptional_rev() -> A? { return self }
override func param_sametype(_ x : Int) {}
override func param_subclass(_ x : A) {}
func param_subclass_rev(_ x : B) {}
override func param_nonclass_optional(_ x : Int?) {}
func param_nonclass_optional_rev(_ x : Int) {}
override func param_class_optional(_ x : B?) {}
func param_class_optional_rev(_ x : B) {}
override func param_class_uoptional(_ x : B!) {}
func param_class_uoptional_rev(_ x : B) {}
override func param_class_optional_uoptional(_ x : B?) {}
override func param_class_optional_uoptional_rev(_ x : B!) {}
}
class C<T> {
func ret_T() -> T {}
}
class D<T> : C<[T]> {
override func ret_T() -> [T] {}
}
class E {
var var_sametype: Int { get { return 0 } set {} }
var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional: Int? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}}
var var_class_optional: F? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_uoptional: F? { get { return .none } set {} }
var var_class_optional_uoptional_rev: E! { get { return self } set {} }
var ro_sametype: Int { return 0 }
var ro_subclass: E { return self }
var ro_subclass_rev: F { return F() }
var ro_nonclass_optional: Int? { return 0 }
var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}}
var ro_class_optional: F? { return .none }
var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_uoptional: F! { return F() }
var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_optional_uoptional: F? { return .none }
var ro_class_optional_uoptional_rev: E! { return self }
}
class F : E {
override var var_sametype: Int { get { return 0 } set {} }
override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}}
override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}}
override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}}
override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}}
override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F?' with covariant type 'F'}}
override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_optional_uoptional: F! { get { return .none } set {} }
override var var_class_optional_uoptional_rev: E? { get { return self } set {} }
override var ro_sametype: Int { return 0 }
override var ro_subclass: E { return self }
override var ro_subclass_rev: F { return F() }
override var ro_nonclass_optional: Int { return 0 }
override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var ro_class_optional: F { return self }
override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_uoptional: F { return F() }
override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_optional_uoptional: F! { return .none }
override var ro_class_optional_uoptional_rev: E? { return self }
}
class G {
func f1(_: Int, int: Int) { }
func f2(_: Int, int: Int) { }
func f3(_: Int, int: Int) { }
func f4(_: Int, int: Int) { }
func f5(_: Int, int: Int) { }
func f6(_: Int, int: Int) { }
func f7(_: Int, int: Int) { }
func g1(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g1(_:string:)' here}} {{28-28=string }}
func g1(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g1(_:path:)' here}} {{28-28=path }}
func g2(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g2(_:string:)' here}} {{none}}
func g2(_: Int, path: String) { }
func g3(_: Int, _ another: Int) { }
func g3(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g3(_:path:)' here}} {{none}}
func g4(_: Int, _ another: Int) { }
func g4(_: Int, path: String) { }
init(a: Int) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{none}}
init(a: String) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{17-17=a }} expected-note {{potential overridden initializer 'init(a:)' here}} {{none}}
init(b: String) {} // expected-note {{potential overridden initializer 'init(b:)' here}} {{17-17=b }} expected-note {{potential overridden initializer 'init(b:)' here}} {{none}}
}
class H : G {
override func f1(_: Int, _: Int) { } // expected-error{{argument labels for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }}
override func f2(_: Int, value: Int) { } // expected-error{{argument labels for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }}
override func f3(_: Int, value int: Int) { } // expected-error{{argument labels for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}}
override func f4(_: Int, _ int: Int) { } // expected-error{{argument labels for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}}
override func f5(_: Int, value inValue: Int) { } // expected-error{{argument labels for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}}
override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument labels for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}}
override func f7(_: Int, int value: Int) { } // okay
override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument labels from any potential overrides}}{{none}}
override func g2(_: Int, string: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}}
override func g3(_: Int, path: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}}
override func g4(_: Int, string: Int) { } // expected-error{{argument labels for method 'g4(_:string:)' do not match those of overridden method 'g4'}} {{28-28=_ }}
override init(x: Int) {} // expected-error{{argument labels for initializer 'init(x:)' do not match those of overridden initializer 'init(a:)'}} {{17-17=a }}
override init(x: String) {} // expected-error{{declaration 'init(x:)' has different argument labels from any potential overrides}} {{none}}
override init(a: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}}
override init(b: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}}
}
@objc class IUOTestBaseClass {
@objc func none() {}
@objc func oneA(_: AnyObject) {}
@objc func oneB(x: AnyObject) {}
@objc func oneC(_ x: AnyObject) {}
@objc func manyA(_: AnyObject, _: AnyObject) {}
@objc func manyB(_ a: AnyObject, b: AnyObject) {}
@objc func manyC(var a: AnyObject, // expected-warning {{'var' in this position is interpreted as an argument label}} {{20-23=`var`}}
var b: AnyObject) {} // expected-warning {{'var' in this position is interpreted as an argument label}} {{20-23=`var`}}
@objc func result() -> AnyObject? { return nil }
@objc func both(_ x: AnyObject) -> AnyObject? { return x }
@objc init(_: AnyObject) {}
@objc init(one: AnyObject) {}
@objc init(a: AnyObject, b: AnyObject) {}
}
class IUOTestSubclass : IUOTestBaseClass {
override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyB(_ a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}}
// expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}}
override func both(_ x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{use '?' to make the result optional}} {{51-52=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}}
override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}}
override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
}
class IUOTestSubclass2 : IUOTestBaseClass {
override func oneA(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
}
class IUOTestSubclassOkay : IUOTestBaseClass {
override func oneA(_: AnyObject?) {}
override func oneC(_ x: AnyObject) {}
}
class GenericBase<T> {}
class ConcreteDerived: GenericBase<Int> {}
class OverriddenWithConcreteDerived<T> {
func foo() -> GenericBase<T> {} // expected-note{{potential overridden instance method 'foo()' here}}
}
class OverridesWithMismatchedConcreteDerived<T>:
OverriddenWithConcreteDerived<T> {
override func foo() -> ConcreteDerived {} //expected-error{{does not override}}
}
class OverridesWithConcreteDerived:
OverriddenWithConcreteDerived<Int> {
override func foo() -> ConcreteDerived {}
}
// <rdar://problem/24646184>
class Ty {}
class SubTy : Ty {}
class Base24646184 {
init(_: SubTy) { }
func foo(_: SubTy) { }
init(ok: Ty) { }
init(ok: SubTy) { }
func foo(ok: Ty) { }
func foo(ok: SubTy) { }
}
class Derived24646184 : Base24646184 {
override init(_: Ty) { } // expected-note {{'init(_:)' previously overridden here}}
override init(_: SubTy) { } // expected-error {{'init(_:)' has already been overridden}}
override func foo(_: Ty) { } // expected-note {{'foo' previously overridden here}}
override func foo(_: SubTy) { } // expected-error {{'foo' has already been overridden}}
override init(ok: Ty) { }
override init(ok: SubTy) { }
override func foo(ok: Ty) { }
override func foo(ok: SubTy) { }
}
// Subscripts
class SubscriptBase {
subscript(a a: Int) -> Int { return a }
}
class SubscriptDerived : SubscriptBase {
override subscript(a: Int) -> Int { return a }
// expected-error@-1 {{argument labels for method 'subscript(_:)' do not match those of overridden method 'subscript(a:)'}}
}
// Generic subscripts
class GenericSubscriptBase {
var dict: [AnyHashable : Any] = [:]
subscript<T : Hashable, U>(t: T) -> U {
get {
return dict[t] as! U
}
set {
dict[t] = newValue
}
}
}
class GenericSubscriptDerived : GenericSubscriptBase {
override subscript<K : Hashable, V>(t: K) -> V {
get {
return super[t]
}
set {
super[t] = newValue
}
}
}
// @escaping
class CallbackBase {
func perform(handler: @escaping () -> Void) {} // expected-note * {{here}}
func perform(optHandler: (() -> Void)?) {} // expected-note * {{here}}
func perform(nonescapingHandler: () -> Void) {} // expected-note * {{here}}
}
class CallbackSubA: CallbackBase {
override func perform(handler: () -> Void) {} // expected-error {{method does not override any method from its superclass}}
// expected-note@-1 {{type does not match superclass instance method with type '(@escaping () -> Void) -> ()'}}
override func perform(optHandler: () -> Void) {} // expected-error {{method does not override any method from its superclass}}
override func perform(nonescapingHandler: () -> Void) {}
}
class CallbackSubB : CallbackBase {
override func perform(handler: (() -> Void)?) {}
override func perform(optHandler: (() -> Void)?) {}
override func perform(nonescapingHandler: (() -> Void)?) {} // expected-error {{method does not override any method from its superclass}}
}
class CallbackSubC : CallbackBase {
override func perform(handler: @escaping () -> Void) {}
override func perform(optHandler: @escaping () -> Void) {} // expected-error {{cannot override instance method parameter of type '(() -> Void)?' with non-optional type '() -> Void'}}
override func perform(nonescapingHandler: @escaping () -> Void) {} // expected-error {{method does not override any method from its superclass}}
}
// inout, varargs
class HasFlagsBase {
func modify(x: inout B) {} // expected-note 2{{potential overridden instance method 'modify(x:)' here}}
func tweak(x: inout A) {} // expected-note 2{{potential overridden instance method 'tweak(x:)' here}}
func collect(x: B...) {} // expected-note 2{{potential overridden instance method 'collect(x:)' here}}
}
class HasFlagsDerivedGood : HasFlagsBase {
override func modify(x: inout B) {}
override func tweak(x: inout A) {}
override func collect(x: B...) {}
}
class HasFlagsDerivedBad1 : HasFlagsBase {
override func modify(x: inout A) {} // expected-error {{method does not override any method from its superclass}}
override func tweak(x: inout B) {} // expected-error {{method does not override any method from its superclass}}
override func collect(x: A...) {} // expected-error {{method does not override any method from its superclass}}
}
class HasFlagsDerivedBad2 : HasFlagsBase {
override func modify(x: B) {} // expected-error {{method does not override any method from its superclass}}
override func tweak(x: A) {} // expected-error {{method does not override any method from its superclass}}
override func collect(x: [B]) {} // expected-error {{method does not override any method from its superclass}}
}
// Issues with overrides of internal(set) and fileprivate(set) members
public class BaseWithInternalSetter {
public internal(set) var someValue: Int = 0
}
public class DerivedWithInternalSetter: BaseWithInternalSetter {
override public internal(set) var someValue: Int {
get { return 0 }
set { }
}
}
class BaseWithFilePrivateSetter {
fileprivate(set) var someValue: Int = 0
}
class DerivedWithFilePrivateSetter: BaseWithFilePrivateSetter {
override fileprivate(set) var someValue: Int {
get { return 0 }
set { }
}
}
open class OpenBase {
open func instanceMethod() {}
open class func classMethod() {}
}
public class PublicDerived : OpenBase {
override public func instanceMethod() {}
override public class func classMethod() {}
}
open class OpenDerived : OpenBase {
override open func instanceMethod() {}
override open class func classMethod() {}
}
open class OpenDerivedPublic : OpenBase {
override public func instanceMethod() {} // Ok
override public class func classMethod() {} // Ok
}
open class OpenDerivedFinal : OpenBase {
override public final func instanceMethod() {}
override public class final func classMethod() {}
}
open class OpenDerivedStatic : OpenBase {
override public static func classMethod() {}
}
| apache-2.0 | 480481469a66863106372abd48a14f87 | 52.060096 | 333 | 0.675169 | 3.901202 | false | false | false | false |
kumabook/MusicFav | MusicFav/AccessibilityLabel.swift | 1 | 623 | //
// AccessibilityLabel.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 5/5/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import Foundation
enum AccessibilityLabel: String {
case EntryStreamTableView = "EntryStreamTableView"
case MenuButton = "MenuButton"
case PlaylistStreamTableView = "PlaylistStreamTableView"
case NewPlaylistButton = "New Playlist"
case PlaylistName = "Playlist name"
case PlaylistMenuButton = "Show playlist list"
case StreamPageMenu = "StreamPageMenu"
var s: String { return rawValue }
} | mit | de67b748ec2fdb0e8e90d12d3978f6de | 30.2 | 60 | 0.675762 | 4.41844 | false | false | false | false |
pkl728/ZombieInjection | Pods/ReactiveKit/Sources/Signal.swift | 4 | 1938 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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 signal represents a sequence of elements.
public struct Signal<Element, Error: Swift.Error>: SignalProtocol {
public typealias Producer = (AtomicObserver<Element, Error>) -> Disposable
private let producer: Producer
/// Create new signal given a producer closure.
public init(producer: @escaping Producer) {
self.producer = producer
}
/// Register the observer that will receive events from the signal.
public func observe(with observer: @escaping Observer<Element, Error>) -> Disposable {
let serialDisposable = SerialDisposable(otherDisposable: nil)
let observer = AtomicObserver(disposable: serialDisposable, observer: observer)
serialDisposable.otherDisposable = producer(observer)
return observer.disposable
}
}
| mit | b5e286d10a42387a72b638353f699d87 | 43.045455 | 88 | 0.749226 | 4.58156 | false | false | false | false |
Headmast/openfights | MoneyHelper/Library/Reusable Layer/Designable.swift | 1 | 976 | //
// Preloadable.swift
// MoneyHelper
//
// Created by Kirill Klebanov on 17/09/2017.
// Copyright © 2017 Surf. All rights reserved.
//
import Foundation
import UIKit
/// Inherit custom subview from this class instead of UIView,
/// mark it as @IBDesignable,
/// set the file's owner and do not set the View's class,
/// =>
/// It renders in the IB!
class DesignableView: UIView {
var view: UIView! {
return subviews.first
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// TODO: check it
_ = setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
_ = setup()
}
func setup() -> UIView? {
let view = Bundle(for: type(of: self)).loadNibNamed(self.nameOfClass, owner: self, options: nil)?.first as? UIView
if let v = view {
addSubview(v)
v.frame = self.bounds
}
return view
}
}
| apache-2.0 | f7e70df26e8a25d6879566bb48c2b4eb | 21.159091 | 122 | 0.580513 | 3.9 | false | false | false | false |
JRG-Developer/ObservableType | ObservableType/Library/ObservableCollection.swift | 1 | 5533 | //
// ObservableCollection.swift
// ObservableType
//
// Created by Joshua Greene on 1/16/17.
// Copyright © 2017 Joshua Greene. 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.
// MARK: - ObservableCollection
/// `ObservableCollection` is a base protocol for `ObservableCollectionArray` and `ObservableCollectionSet`.
///
/// **Warning**: You SHOULD NOT conform to this type; this is ONLY for use within `ObservableType`.
///
/// The only reason it's `public` is to allow methods that use it to be `public`.
public protocol ObservableCollection: Collection, ExpressibleByArrayLiteral {
/// This method is used to add an element to the collection.
///
/// - Parameter element: The element to be added
mutating func add(_ element: Self.Element)
/// This method is used to remove an element at a given index from the collection.
///
/// - Parameter index: The index for the element to be removed
@discardableResult mutating func remove(at index: Self.Index) -> Self.Element
/// Use this initializer to create a new concrete `ObservableCollection` instance from an array of elements.
///
/// - Parameter array: The elements array
init(elements: Array<Element>)
}
extension ObservableCollection where Element: Updatable {
/// Use this method to update this collection with a new version.
///
/// This method iterates through each element within the new version. If there's a matching element by `identifier` found within this collection, it will be updated and added to a new collection. If a match isn't found, it's simply added to the new collection.
///
/// Finally, this collection will be set to the new collection.
///
/// - Parameter newVersion: The new version of the collection
/// - Returns: `true` if the collection was updated or `false` otherwise
@discardableResult public mutating func update(with newVersion: Self) -> Bool {
guard newVersion.count > 0 else {
guard count > 0 else { return false }
self = []
return true
}
var updated = newVersion.count != count
var newCollection: Self = []
newVersion.forEach { newElement in
guard let index = index(where: { $0.identifier == newElement.identifier}) else {
newCollection.add(newElement)
updated = true
return
}
let element = self[index]
updated = updated || element.update(with: newElement)
newCollection.add(element)
}
guard updated else { return false }
self = newCollection
return true
}
/// Use this method to find and update a matching element by `identifier`.
///
/// - Parameter newVersion: The new version
/// - Returns: `true` if an element was found and updated or `false` otherwise
@discardableResult public func updateMatchingElement(_ newVersion: Element) -> Bool {
guard let index = index(where: { $0.identifier == newVersion.identifier}) else { return false }
return self[index].update(with: newVersion)
}
}
// MARK: - ObservableCollectionArray
/// `ObservableCollectionArray` is a protocol that's exclusively conformed to by `Swift.Array`; this allows generic methods to be created that use an `Array.
///
/// **Warning**: You SHOULD NOT conform to this type; this is ONLY for use within `ObservableType`.
///
/// The only reason it's `public` is to allow methods that use it to be `public`.
public protocol ObservableCollectionArray: ObservableCollection {
/// This computed property is used to cast this instance to an `Array`.
var array: Array<Element> { get }
}
extension Array: ObservableCollectionArray {
public var array: Array<Element> {
return self
}
mutating public func add(_ object: Element) {
append(object)
}
public init(elements: Array<Element>) {
self = elements
}
}
// MARK: - ObservableCollectionSet
/// `ObservableCollectionArray` is a protocol that's exclusively conformed to by `Swift.Set`; this allows generic methods to be created that use a `Set.
///
/// **Warning**: You SHOULD NOT conform to this type; this is ONLY for use within `ObservableType`.
///
/// The only reason it's `public` is to allow methods that use it to be `public`.
public protocol ObservableCollectionSet: ObservableCollection {
// for naming purposes only
}
extension Set: ObservableCollectionSet {
public mutating func add(_ object: Element) {
insert(object)
}
public init(elements: Array<Element>) {
self = Set(elements)
}
}
| mit | 40f24fe2b19e701c7bae5725e1e47d0d | 38.234043 | 262 | 0.712762 | 4.508557 | false | false | false | false |
blockstack/blockstack-portal | native/macos/Blockstack/Pods/Swifter/Sources/Socket+File.swift | 5 | 1751 | //
// Socket+File.swift
// Swifter
//
// Created by Damian Kolakowski on 13/07/16.
//
import Foundation
#if os(iOS) || os(tvOS) || os (Linux)
struct sf_hdtr { }
private func sendfileImpl(_ source: UnsafeMutablePointer<FILE>, _ target: Int32, _: off_t, _: UnsafeMutablePointer<off_t>, _: UnsafeMutablePointer<sf_hdtr>, _: Int32) -> Int32 {
var buffer = [UInt8](repeating: 0, count: 1024)
while true {
let readResult = fread(&buffer, 1, buffer.count, source)
guard readResult > 0 else {
return Int32(readResult)
}
var writeCounter = 0
while writeCounter < readResult {
#if os(Linux)
let writeResult = send(target, &buffer + writeCounter, readResult - writeCounter, Int32(MSG_NOSIGNAL))
#else
let writeResult = write(target, &buffer + writeCounter, readResult - writeCounter)
#endif
guard writeResult > 0 else {
return Int32(writeResult)
}
writeCounter = writeCounter + writeResult
}
}
}
#endif
extension Socket {
public func writeFile(_ file: String.File) throws -> Void {
var offset: off_t = 0
var sf: sf_hdtr = sf_hdtr()
#if os(iOS) || os(tvOS) || os (Linux)
let result = sendfileImpl(file.pointer, self.socketFileDescriptor, 0, &offset, &sf, 0)
#else
let result = sendfile(fileno(file.pointer), self.socketFileDescriptor, 0, &offset, &sf, 0)
#endif
if result == -1 {
throw SocketError.writeFailed("sendfile: " + Errno.description())
}
}
}
| mpl-2.0 | b9dcdc40131368325722311bf6d6df06 | 32.037736 | 181 | 0.546545 | 4.229469 | false | false | false | false |
hipposan/LemonDeer | Sources/M3u8Playlist.swift | 2 | 385 | //
// M3u8Playlist.swift
// WindmillComic
//
// Created by hippo_san on 08/06/2017.
// Copyright © 2017 Ziyideas. All rights reserved.
//
import Foundation
class M3u8Playlist {
var tsSegmentArray = [M3u8TsSegmentModel]()
var length = 0
var identifier = ""
func initSegment(with array: [M3u8TsSegmentModel]) {
tsSegmentArray = array
length = array.count
}
}
| mit | 3bf102944acb9062a8ab259cec80ab97 | 18.2 | 54 | 0.684896 | 3.121951 | false | false | false | false |
joerocca/GitHawk | Classes/Systems/Autocomplete/AutocompleteCell.swift | 1 | 2866 | //
// AutocompleteCell.swift
// Freetime
//
// Created by Ryan Nystrom on 7/23/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
import SDWebImage
final class AutocompleteCell: StyledTableCell {
enum State {
case emoji(emoji: String, term: String)
case user(avatarURL: URL, login: String)
}
private let thumbnailImageView = UIImageView()
private let emojiLabel = UILabel()
private let titleLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.backgroundColor = Styles.Colors.Gray.lighter.color
thumbnailImageView.layer.cornerRadius = Styles.Sizes.avatarCornerRadius
thumbnailImageView.layer.borderColor = Styles.Colors.Gray.light.color.cgColor
thumbnailImageView.layer.borderWidth = 1.0 / UIScreen.main.scale
thumbnailImageView.clipsToBounds = true
thumbnailImageView.isUserInteractionEnabled = true
contentView.addSubview(thumbnailImageView)
thumbnailImageView.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter)
make.size.equalTo(Styles.Sizes.avatar)
make.centerY.equalTo(contentView)
}
emojiLabel.font = UIFont.systemFont(ofSize: 20)
contentView.addSubview(emojiLabel)
emojiLabel.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter)
make.size.equalTo(Styles.Sizes.avatar)
make.centerY.equalTo(contentView)
}
titleLabel.font = Styles.Fonts.body
titleLabel.textColor = Styles.Colors.Gray.dark.color
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter + Styles.Sizes.avatar.width + Styles.Sizes.columnSpacing)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public API
func configure(state: State) {
let emojiHidden: Bool
let thumbnailHidden: Bool
let title: String
switch state {
case .emoji(let emoji, let term):
emojiHidden = false
thumbnailHidden = true
emojiLabel.text = emoji
title = term
case .user(let avatarURL, let login):
emojiHidden = true
thumbnailHidden = false
thumbnailImageView.sd_setImage(with: avatarURL)
title = login
}
emojiLabel.isHidden = emojiHidden
thumbnailImageView.isHidden = thumbnailHidden
titleLabel.text = title
}
}
| mit | 979fcf41918cd6abafc080ae37c0b6f9 | 31.556818 | 107 | 0.66178 | 4.973958 | false | false | false | false |
grachro/swift-layout | add-on/ScrollViewPuller.swift | 1 | 5254 | //
// ScrollViewPuller.swift
// swift-layout
//
// Created by grachro on 2014/09/15.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
protocol ScrollViewPullArea {
func minHeight() -> CGFloat
func maxHeight() -> CGFloat
func animationSpeed() -> TimeInterval
func show(viewHeight:CGFloat, pullAreaHeight:CGFloat)
}
class ScrollViewPuller {
fileprivate var target:UIScrollView? = nil
fileprivate var pullArea:ScrollViewPullArea? = nil
fileprivate var pullAreaHeight:CGFloat = 0
fileprivate var lastScrollViewOffsetY:CGFloat = 0
fileprivate var draggingDistance:CGFloat = 0
fileprivate var isDrag = false
fileprivate var isPull:Bool {
get {
return (scrollHeight < 0) //引っ張り中?
}
}
fileprivate var isUpWay:Bool {
get {
return (draggingDistance < 0) //上に移動中
}
}
fileprivate var isDownWay:Bool {
get {
return (0 < draggingDistance) //下に移動中
}
}
fileprivate var scrollHeight:CGFloat {
get {
if self.target == nil {
return 0
}
return self.target!.contentOffset.y
}
}
}
extension ScrollViewPuller {
func begin(_ target:UIScrollView, pullArea:ScrollViewPullArea) {
self.target = target
self.pullArea = pullArea
self.minDisplay()
}
//ドラッグスクロール開始
//call from scrollViewWillBeginDragging(scrollView: UIScrollView!)
func beginDragScroll(_ scrollView: UIScrollView!) {
self.isDrag=true
}
//ドラッグスクロール終了
//call from scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool)
func endDragScroll(_ scrollView: UIScrollView?!, willDecelerate decelerate: Bool) {
if self.target == nil {
return
}
self.isDrag=false
if isDownWay {
//println("下,isPull=\(isPull)")
}
if isUpWay {
//println("上,isPull=\(isPull)")
}
if isDownWay && isPull {
let needFullOpen = self.pullAreaHeight < self.pullArea!.maxHeight()
self.pullAreaHeight = self.pullArea!.maxHeight()
self.display(self.pullAreaHeight, needFullOpen: needFullOpen)
} else if isUpWay && 0 < self.pullAreaHeight {
self.pullAreaHeight = self.pullArea!.minHeight()
if decelerate {
//慣性移動中
return
}
minDisplay()
}
}
//慣性スクロール終了(this event is after endDragScroll())
//call from scrollViewDidEndDecelerating(scrollView: UIScrollView!)
func endScroll(_ scrollView: UIScrollView!) {
let offsetY = self.target!.contentOffset.y
if self.pullArea!.maxHeight() <= -offsetY {
maxDisplay()
} else if self.pullArea!.minHeight() != offsetY {
minDisplay()
}
}
//スクロール中
//call from scrollViewDidScroll(scrollView: UIScrollView!)
func dragScroll(_ scrollView: UIScrollView!) {
if self.target == nil {
return
}
if self.isDrag {
self.draggingDistance = self.lastScrollViewOffsetY - self.scrollHeight
} else {
self.draggingDistance = 0
}
changeDragginAndPulling()
self.lastScrollViewOffsetY = self.scrollHeight
}
fileprivate func changeDragginAndPulling() {
if self.target == nil {
return
}
if !self.isDrag || !isPull {
return
}
self.pullAreaHeight = -self.scrollHeight
if self.pullAreaHeight < self.pullArea!.minHeight() {
self.pullAreaHeight = self.pullArea!.minHeight()
} else if self.pullAreaHeight > self.pullArea!.maxHeight() {
self.pullAreaHeight = self.pullArea!.maxHeight()
}
self.target!.contentInset.top = self.pullAreaHeight
if self.pullArea != nil {
self.pullArea!.show(viewHeight:self.pullAreaHeight,pullAreaHeight:-self.scrollHeight)
}
}
fileprivate func display(_ height:CGFloat,needFullOpen:Bool) {
UIView.animate(withDuration: self.pullArea!.animationSpeed(), animations: {
var inset = self.target!.contentInset
inset.top = height
self.target!.contentInset = inset
if needFullOpen {
self.target!.contentOffset.y = -height
}
if self.pullArea != nil {
self.pullArea!.show(viewHeight:height, pullAreaHeight:height)
}
})
}
fileprivate func minDisplay() {
display(self.pullArea!.minHeight(), needFullOpen:false)
}
fileprivate func maxDisplay() {
display(self.pullArea!.maxHeight(), needFullOpen:true)
}
}
| mit | 98478d54d1ba50069a5fd8b6f058673e | 25.739583 | 100 | 0.563109 | 5.068115 | false | false | false | false |
djxmax/MultiCircleImageView | Pod/Classes/MultiCircleImageView.swift | 1 | 1660 | //
// MultiCicrleImageView.swift
// MultiCicrleImageView
//
// Created by Maxime Lucquin on 15/10/2015.
// Copyright © 2015 maximelucquin. All rights reserved.
//
import UIKit
public class MultiCircleImageView{
var frame = CGRect!()
public init(frame: CGRect) {
self.frame = frame
}
public func addView(rootView: UIView, imageList: [UIImage]) -> [UIImageView] {
frame.origin = CGPoint(x: 0, y: 0)
rootView.subviews.forEach({ $0.removeFromSuperview() })
if(imageList.count==1){
let view = OneView(frame: frame, image0: imageList[0])
rootView.addSubview(view)
return view.setup()
} else if(imageList.count == 2){
let view = TwoViews(frame: frame, image0: imageList[0], image1: imageList[1])
rootView.addSubview(view)
return view.setup()
} else if(imageList.count == 3){
let view = ThreeViews(frame: frame, image0: imageList[0], image1: imageList[1], image2: imageList[2])
rootView.addSubview(view)
return view.setup()
} else if(imageList.count == 4){
let view = FourViews(frame: frame, image0: imageList[0], image1: imageList[1], image2: imageList[2], image3: imageList[3])
rootView.addSubview(view)
return view.setup()
} else if(imageList.count == 5){
let view = FiveViews(frame: frame, image0: imageList[0], image1: imageList[1], image2: imageList[2], image3: imageList[3], image4: imageList[4])
rootView.addSubview(view)
return view.setup()
}
return []
}
}
| mit | 5c0f8c6add3286905710e62fb89a0475 | 35.866667 | 156 | 0.599156 | 3.921986 | false | false | false | false |
natecook1000/swift | test/stdlib/Mirror.swift | 1 | 47143 | //===--- Mirror.swift -----------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
//
// RUN: if [ %target-runtime == "objc" ]; \
// RUN: then \
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g && \
// RUN: %target-build-swift %t/main.swift %S/Inputs/Mirror/MirrorOther.swift -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/Mirror; \
// RUN: else \
// RUN: %target-build-swift %t/main.swift %S/Inputs/Mirror/MirrorOther.swift -o %t/Mirror; \
// RUN: fi
// RUN: %target-codesign %t/Mirror
// RUN: %target-run %t/Mirror
// REQUIRES: executable_test
import StdlibUnittest
var mirrors = TestSuite("Mirrors")
extension Mirror {
public var testDescription: String {
let nil_ = "nil"
return "[" +
children.lazy
.map { "\($0.0 ?? nil_): \(String(reflecting: $0.1))" }
.joined(separator: ", ")
+ "]"
}
}
mirrors.test("RandomAccessStructure") {
struct Eggs : CustomReflectable {
var customMirror: Mirror {
return Mirror(self, unlabeledChildren: ["aay", "bee", "cee"])
}
}
let x = Eggs().customMirror
expectEqual("[nil: \"aay\", nil: \"bee\", nil: \"cee\"]", x.testDescription)
}
let letters = "abcdefghijklmnopqrstuvwxyz "
func find(_ substring: String, within domain: String) -> String.Index? {
let domainCount = domain.count
let substringCount = substring.count
if (domainCount < substringCount) { return nil }
var sliceStart = domain.startIndex
var sliceEnd = domain.index(sliceStart, offsetBy: substringCount)
var i = 0
while true {
if domain[sliceStart..<sliceEnd] == substring {
return sliceStart
}
if i == domainCount - substringCount { break }
sliceStart = domain.index(after: sliceStart)
sliceEnd = domain.index(after: sliceEnd)
i += 1
}
return nil
}
mirrors.test("ForwardStructure") {
struct DoubleYou : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: Set(letters),
displayStyle: .`set`)
}
}
let w = DoubleYou().customMirror
expectEqual(.`set`, w.displayStyle)
expectEqual(letters.count, numericCast(w.children.count))
// Because we don't control the order of a Set, we need to do a
// fancy dance in order to validate the result.
let description = w.testDescription
for c in letters {
let expected = "nil: \"\(c)\""
expectNotNil(find(expected, within: description))
}
}
mirrors.test("BidirectionalStructure") {
struct Why : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: letters,
displayStyle: .collection)
}
}
// Test that the basics seem to work
let y = Why().customMirror
expectEqual(.`collection`, y.displayStyle)
let description = y.testDescription
expectEqual(
"[nil: \"a\", nil: \"b\", nil: \"c\", nil: \"",
description[description.startIndex..<description.firstIndex(of: "d")!])
}
mirrors.test("LabeledStructure") {
struct Zee : CustomReflectable, CustomStringConvertible {
var customMirror: Mirror {
return Mirror(self, children: ["bark": 1, "bite": 0])
}
var description: String { return "Zee" }
}
let z = Zee().customMirror
expectEqual("[bark: 1, bite: 0]", z.testDescription)
expectNil(z.displayStyle)
struct Zee2 : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self, children: ["bark": 1, "bite": 0], displayStyle: .dictionary)
}
}
let z2 = Zee2().customMirror
expectEqual(.dictionary, z2.displayStyle)
expectEqual("[bark: 1, bite: 0]", z2.testDescription)
struct Heterogeny : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self, children: ["bark": 1, "bite": Zee()])
}
}
let h = Heterogeny().customMirror
expectEqual("[bark: 1, bite: Zee]", h.testDescription)
}
mirrors.test("Legacy") {
let m = Mirror(reflecting: [1, 2, 3])
expectTrue(m.subjectType == [Int].self)
let x0: [Mirror.Child] = [
(label: nil, value: 1),
(label: nil, value: 2),
(label: nil, value: 3)
]
expectFalse(
zip(x0, m.children).contains {
$0.0.value as! Int != $0.1.value as! Int
})
class B { let bx: Int = 0 }
class D : B { let dx: Int = 1 }
let mb = Mirror(reflecting: B())
func expectBMirror(
_ mb: Mirror, stackTrace: SourceLocStack = SourceLocStack(),
file: String = #file, line: UInt = #line
) {
expectTrue(mb.subjectType == B.self,
stackTrace: stackTrace, file: file, line: line)
expectNil(
mb.superclassMirror,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
1, mb.children.count,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
"bx", mb.children.first?.label,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
0, mb.children.first?.value as? Int,
stackTrace: stackTrace, file: file, line: line)
}
expectBMirror(mb)
// Ensure that the base class instance is properly filtered out of
// the child list
do {
let md = Mirror(reflecting: D())
expectTrue(md.subjectType == D.self)
expectEqual(1, md.children.count)
expectEqual("dx", md.children.first?.label)
expectEqual(1, md.children.first?.value as? Int)
expectNotNil(md.superclassMirror)
if let mb2 = md.superclassMirror { expectBMirror(mb2) }
}
do {
// Ensure that we reflect on the dynamic type of the subject
let md = Mirror(reflecting: D() as B)
expectTrue(md.subjectType == D.self)
expectEqual(1, md.children.count)
expectEqual("dx", md.children.first?.label)
expectEqual(1, md.children.first?.value as? Int)
expectNotNil(md.superclassMirror)
if let mb2 = md.superclassMirror { expectBMirror(mb2) }
}
}
//===----------------------------------------------------------------------===//
//===--- Class Support ----------------------------------------------------===//
class DullClass {}
mirrors.test("ClassReflection") {
expectEqual(.`class`, Mirror(reflecting: DullClass()).displayStyle)
}
mirrors.test("Class/Root/Uncustomized") {
class A { var a: Int = 1 }
let a = Mirror(reflecting: A())
expectTrue(a.subjectType == A.self)
expectNil(a.superclassMirror)
expectEqual(1, a.children.count)
expectEqual("a", a.children.first!.label)
}
//===--- Generated Superclass Mirrors -------------------------------------===//
mirrors.test("Class/Root/superclass:.generated") {
class B : CustomReflectable {
var b: String = "two"
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
expectEqual(1, b.children.count)
expectEqual("bee", b.children.first!.label)
expectEqual("two", b.children.first!.value as? String)
}
mirrors.test("class/Root/superclass:<default>") {
class C : CustomReflectable {
var c: UInt = 3
var customMirror: Mirror {
return Mirror(self, children: ["sea": c + 1])
}
}
let c = Mirror(reflecting: C())
expectTrue(c.subjectType == C.self)
expectNil(c.superclassMirror)
expectEqual(1, c.children.count)
expectEqual("sea", c.children.first!.label)
expectEqual(4, c.children.first!.value as? UInt)
}
mirrors.test("class/Plain/Plain") {
class A { var a: Int = 1 }
class B : A { var b: UInt = 42 }
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let bChild = expectNotNil(b.children.first) {
expectEqual("b", bChild.label)
expectEqual(42, bChild.value as? UInt)
}
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aChild = expectNotNil(a.children.first) {
expectEqual("a", aChild.label)
expectEqual(1, aChild.value as? Int)
expectNil(a.superclassMirror)
}
}
}
mirrors.test("class/UncustomizedSuper/Synthesized/Implicit") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first?.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/UncustomizedSuper/Synthesized/Explicit") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/CustomizedSuper/Synthesized") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
// This is an unusual case: when writing override on a
// customMirror implementation you would typically want to pass
// ancestorRepresentation: .customized(super.customMirror) or, in
// rare cases, ancestorRepresentation: .Suppressed. However, it
// has an expected behavior, which we test here.
override var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
#if _runtime(_ObjC)
import Foundation
import MirrorObjC
//===--- ObjC Base Classes ------------------------------------------------===//
mirrors.test("class/ObjCPlain/Plain") {
class A : NSObject { var a: Int = 1 }
class B : A { var b: UInt = 42 }
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let bChild = expectNotNil(b.children.first) {
expectEqual("b", bChild.label)
expectEqual(42, bChild.value as? UInt)
}
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aChild = expectNotNil(a.children.first) {
expectEqual("a", aChild.label)
expectEqual(1, aChild.value as? Int)
if let o = expectNotNil(a.superclassMirror) {
expectEqual("NSObject", String(reflecting: o.subjectType))
}
}
}
}
mirrors.test("class/ObjCUncustomizedSuper/Synthesized/Implicit") {
class A : NSObject { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first?.label)
if let o = expectNotNil(a.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
}
}
}
mirrors.test("class/ObjCUncustomizedSuper/Synthesized/Explicit") {
class A : NSObject { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
if let o = expectNotNil(a.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
}
}
}
mirrors.test("class/ObjCCustomizedSuper/Synthesized") {
class A : DateFormatter, CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
// This is an unusual case: when writing override on a
// customMirror implementation you would typically want to pass
// ancestorRepresentation: .customized(super.customMirror) or, in
// rare cases, ancestorRepresentation: .Suppressed. However, it
// has an expected behavior, which we test here.
override var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
if let d = expectNotNil(a.superclassMirror) {
expectTrue(d.subjectType == DateFormatter.self)
if let f = expectNotNil(d.superclassMirror) {
expectTrue(f.subjectType == Formatter.self)
if let o = expectNotNil(f.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
expectNil(o.superclassMirror)
}
}
}
}
}
mirrors.test("ObjC") {
// Some Foundation classes lie about their ivars, which would crash
// a mirror; make sure we are not automatically exposing ivars of
// Objective-C classes from the default mirror implementation.
expectEqual(0, Mirror(reflecting: HasIVars()).children.count)
}
// rdar://problem/39629937
@objc class ObjCClass : NSObject {
let value: Int
init(value: Int) { self.value = value }
override var description: String {
return "\(value)"
}
}
struct WrapObjCClassArray {
var array: [ObjCClass]
}
mirrors.test("struct/WrapNSArray") {
let nsArray: NSArray = [
ObjCClass(value: 1), ObjCClass(value: 2),
ObjCClass(value: 3), ObjCClass(value: 4)
]
let s = String(describing: WrapObjCClassArray(array: nsArray as! [ObjCClass]))
expectEqual("WrapObjCClassArray(array: [1, 2, 3, 4])", s)
}
#endif // _runtime(_ObjC)
//===--- Suppressed Superclass Mirrors ------------------------------------===//
mirrors.test("Class/Root/NoSuperclassMirror") {
class B : CustomReflectable {
var b: String = "two"
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
expectEqual(1, b.children.count)
expectEqual("bee", b.children.first!.label)
}
mirrors.test("class/UncustomizedSuper/NoSuperclassMirror") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
}
mirrors.test("class/CustomizedSuper/NoSuperclassMirror") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
}
//===--- Override Superclass Mirrors --------------------------------------===//
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Direct") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
// B inherits A directly
class B : A {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("aye", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Indirect") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
// B inherits A indirectly through X and Y
class B : Y {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let y = expectNotNil(b.superclassMirror) {
expectTrue(y.subjectType == Y.self)
if let x = expectNotNil(y.superclassMirror) {
expectTrue(x.subjectType == X.self)
expectEqual(0, x.children.count)
if let a = expectNotNil(x.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
}
}
}
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Indirect2") {
class A : CustomLeafReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(
self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
// B inherits A indirectly through X and Y
class B : Y {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
}
mirrors.test("class/Cluster") {
class A : CustomLeafReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(
self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
let a = Mirror(reflecting: Y())
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
//===--- Miscellaneous ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("Addressing") {
let m0 = Mirror(reflecting: [1, 2, 3])
expectEqual(1, m0.descendant(0) as? Int)
expectEqual(2, m0.descendant(1) as? Int)
expectEqual(3, m0.descendant(2) as? Int)
let m1 = Mirror(reflecting: (a: ["one", "two", "three"], 4))
let ott0 = m1.descendant(0) as? [String]
expectNotNil(ott0)
let ott1 = m1.descendant("a") as? [String]
expectNotNil(ott1)
if ott0 != nil && ott1 != nil {
expectEqualSequence(ott0!, ott1!)
}
expectEqual(4, m1.descendant(1) as? Int)
expectEqual(4, m1.descendant(".1") as? Int)
expectEqual("one", m1.descendant(0, 0) as? String)
expectEqual("two", m1.descendant(0, 1) as? String)
expectEqual("three", m1.descendant(0, 2) as? String)
expectEqual("one", m1.descendant("a", 0) as? String)
struct Zee : CustomReflectable {
var customMirror: Mirror {
return Mirror(self, children: ["bark": 1, "bite": 0])
}
}
let x = [
(a: ["one", "two", "three"], b: Zee()),
(a: ["five"], b: Zee()),
(a: [], b: Zee())]
let m = Mirror(reflecting: x)
let two = m.descendant(0, "a", 1)
expectEqual("two", two as? String)
expectEqual(1, m.descendant(1, 1, "bark") as? Int)
expectEqual(0, m.descendant(1, 1, "bite") as? Int)
expectNil(m.descendant(1, 1, "bork"))
}
mirrors.test("Invalid Path Type")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
struct X : MirrorPath {}
let m = Mirror(reflecting: [1, 2, 3])
expectEqual(1, m.descendant(0) as? Int)
expectCrashLater()
_ = m.descendant(X())
}
mirrors.test("PlaygroundQuickLook") {
// Customization works.
struct CustomQuickie : CustomPlaygroundQuickLookable {
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .point(1.25, 42)
}
}
switch PlaygroundQuickLook(reflecting: CustomQuickie()) {
case .point(1.25, 42): break
default: expectTrue(false)
}
// PlaygroundQuickLook support from Legacy Mirrors works.
switch PlaygroundQuickLook(reflecting: true) {
case .bool(true): break
default: expectTrue(false)
}
// With no Legacy Mirror QuickLook support, we fall back to
// String(reflecting: ).
struct X {}
switch PlaygroundQuickLook(reflecting: X()) {
case .text(let text):
#if _runtime(_ObjC)
// FIXME: Enable if non-objc hasSuffix is implemented.
expectTrue(text.contains(").X"), text)
#endif
default:
expectTrue(false)
}
struct Y : CustomDebugStringConvertible {
var debugDescription: String { return "Why?" }
}
switch PlaygroundQuickLook(reflecting: Y()) {
case .text("Why?"): break
default: expectTrue(false)
}
}
class Parent {}
extension Parent : _DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook {
return .text("base")
}
}
class Child : Parent { }
class FancyChild : Parent, CustomPlaygroundQuickLookable {
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text("child")
}
}
mirrors.test("_DefaultCustomPlaygroundQuickLookable") {
// testing the workaround for custom quicklookables in subclasses
switch PlaygroundQuickLook(reflecting: Child()) {
case .text("base"): break
default: expectUnreachable("Base custom quicklookable was expected")
}
switch PlaygroundQuickLook(reflecting: FancyChild()) {
case .text("child"): break
default: expectUnreachable("FancyChild custom quicklookable was expected")
}
}
mirrors.test("String.init") {
expectEqual("42", String(42))
expectEqual("42", String("42"))
expectEqual("42", String(reflecting: 42))
expectEqual("\"42\"", String(reflecting: "42"))
}
//===--- Structs ----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
struct StructWithDefaultMirror {
let s: String
init (_ s: String) {
self.s = s
}
}
mirrors.test("Struct/NonGeneric/DefaultMirror") {
do {
var output = ""
dump(StructWithDefaultMirror("123"), to: &output)
expectEqual("▿ Mirror.StructWithDefaultMirror\n - s: \"123\"\n", output)
}
do {
// Build a String around an interpolation as a way of smoke-testing that
// the internal _Mirror implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), to: &output)
expectEqual("▿ Mirror.StructWithDefaultMirror\n - s: \"456\"\n", output)
}
expectEqual(
.`struct`,
Mirror(reflecting: StructWithDefaultMirror("")).displayStyle)
}
struct GenericStructWithDefaultMirror<T, U> {
let first: T
let second: U
}
mirrors.test("Struct/Generic/DefaultMirror") {
do {
var value = GenericStructWithDefaultMirror<Int, [Any?]>(
first: 123,
second: ["abc", 456, 789.25])
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<Any>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ Optional(\"abc\")\n" +
" - some: \"abc\"\n" +
" ▿ Optional(456)\n" +
" - some: 456\n" +
" ▿ Optional(789.25)\n" +
" - some: 789.25\n"
expectEqual(expected, output)
}
}
//===--- Enums ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
enum NoPayloadEnumWithDefaultMirror {
case A, ß
}
mirrors.test("Enum/NoPayload/DefaultMirror") {
do {
let value: [NoPayloadEnumWithDefaultMirror] =
[.A, .ß]
var output = ""
dump(value, to: &output)
let expected =
"▿ 2 elements\n" +
" - Mirror.NoPayloadEnumWithDefaultMirror.A\n" +
" - Mirror.NoPayloadEnumWithDefaultMirror.ß\n"
expectEqual(expected, output)
}
}
enum SingletonNonGenericEnumWithDefaultMirror {
case OnlyOne(Int)
}
mirrors.test("Enum/SingletonNonGeneric/DefaultMirror") {
do {
let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5)
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" +
" - OnlyOne: 5\n"
expectEqual(expected, output)
}
}
enum SingletonGenericEnumWithDefaultMirror<T> {
case OnlyOne(T)
}
mirrors.test("Enum/SingletonGeneric/DefaultMirror") {
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx")
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" +
" - OnlyOne: \"IIfx\"\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne(
LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum SinglePayloadNonGenericEnumWithDefaultMirror {
case Cat
case Dog
case Volleyball(String, Int)
}
mirrors.test("Enum/SinglePayloadNonGeneric/DefaultMirror") {
do {
let value: [SinglePayloadNonGenericEnumWithDefaultMirror] =
[.Cat,
.Dog,
.Volleyball("Wilson", 2000)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" +
" ▿ Volleyball: (2 elements)\n" +
" - .0: \"Wilson\"\n" +
" - .1: 2000\n"
expectEqual(expected, output)
}
}
enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
case Well
case Faucet
case Pipe(T, U)
}
mirrors.test("Enum/SinglePayloadGeneric/DefaultMirror") {
do {
let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] =
[.Well,
.Faucet,
.Pipe(408, [415])]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - 415\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror {
case Plus
case SE30
case Classic(mhz: Int)
case Performa(model: Int)
}
mirrors.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] =
[.Plus,
.SE30,
.Classic(mhz: 16),
.Performa(model: 220)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 4 elements\n" +
" - Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" ▿ Classic: (1 element)\n" +
" - mhz: 16\n" +
" ▿ Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" +
" ▿ Performa: (1 element)\n" +
" - model: 220\n"
expectEqual(expected, output)
}
}
class Floppy {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
class CDROM {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Floppy)
case HyperCard(cdrom: CDROM)
}
mirrors.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: Floppy(capacity: 800)),
.HyperCard(cdrom: CDROM(capacity: 600))]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: (1 element)\n" +
" ▿ floppy: Mirror.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: (1 element)\n" +
" ▿ cdrom: Mirror.CDROM #1\n" +
" - capacity: 600\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Bool)
case HyperCard(cdrom: Bool)
}
mirrors.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: true),
.HyperCard(cdrom: false)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: (1 element)\n" +
" - floppy: true\n" +
" ▿ Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: (1 element)\n" +
" - cdrom: false\n"
expectEqual(expected, output)
}
}
enum MultiPayloadGenericEnumWithDefaultMirror<T, U> {
case IIe
case IIgs
case Centris(ram: T)
case Quadra(hdd: U)
case PowerBook170
case PowerBookDuo220
}
mirrors.test("Enum/MultiPayloadGeneric/DefaultMirror") {
do {
let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] =
[.IIe,
.IIgs,
.Centris(ram: 4096),
.Quadra(hdd: "160MB"),
.PowerBook170,
.PowerBookDuo220]
var output = ""
dump(value, to: &output)
let expected =
"▿ 6 elements\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" ▿ Centris: (1 element)\n" +
" - ram: 4096\n" +
" ▿ Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" ▿ Quadra: (1 element)\n" +
" - hdd: \"160MB\"\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked,
LifetimeTracked>
.Quadra(hdd: LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum Foo<T> {
indirect case Foo(Int)
case Bar(T)
}
enum List<T> {
case Nil
indirect case Cons(first: T, rest: List<T>)
}
mirrors.test("Enum/IndirectGeneric/DefaultMirror") {
let x = Foo<String>.Foo(22)
let y = Foo<String>.Bar("twenty-two")
expectEqual("\(x)", "Foo(22)")
expectEqual("\(y)", "Bar(\"twenty-two\")")
let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil))
expectEqual("Cons(first: 0, rest: Mirror.List<Swift.Int>.Cons(first: 1, rest: Mirror.List<Swift.Int>.Nil))",
"\(list)")
}
enum MyError: Error {
case myFirstError(LifetimeTracked)
}
mirrors.test("Enum/CaseName/Error") {
// Just make sure this doesn't leak.
let e: Error = MyError.myFirstError(LifetimeTracked(0))
_ = String(describing: e)
}
class Brilliant : CustomReflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
var customMirror: Mirror {
return Mirror(self, children: ["first": first, "second": second, "self": self])
}
}
//===--- Custom mirrors ---------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Subclasses inherit their parents' custom mirrors.
class Irradiant : Brilliant {
init() {
super.init(400, "")
}
}
mirrors.test("CustomMirror") {
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" ▿ self: Mirror.Brilliant #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxDepth: 0)
expectEqual("▹ Mirror.Brilliant #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 3)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" (1 more child)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 2)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 1)
let expected =
"▿ Mirror.Brilliant #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
}
mirrors.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), to: &output)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 400\n" +
" - second: \"\"\n" +
" ▿ self: Mirror.Brilliant #0\n"
expectEqual(expected, output)
}
}
//===--- Metatypes --------------------------------------------------------===//
//===----------------------------------------------------------------------===//
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
class SomeClass {}
mirrors.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, to: &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, to: &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, to: &output)
expectEqual(expectedInt, output)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- Mirror.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- Mirror.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, to: &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
//===--- Tuples -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: Mirror.Brilliant #0\n" +
" - first: 384\n" +
" - second: \"seven six eight\"\n" +
" ▿ self: Mirror.Brilliant #0\n" +
" ▿ .1: Mirror.StructWithDefaultMirror\n" +
" - s: \"nine\"\n"
expectEqual(expected, output)
expectEqual(.tuple, Mirror(reflecting: tuple).displayStyle)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, to: &output)
let expected =
"▿ (4 elements)\n" +
" - .0: 1\n" +
" - .1: 2.5\n" +
" - .2: false\n" +
" - .3: \"three\"\n"
expectEqual(expected, output)
}
do {
// A nested tuple.
var output = ""
let tuple = (1, ("Hello", "World"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" - .0: 1\n" +
" ▿ .1: (2 elements)\n" +
" - .0: \"Hello\"\n" +
" - .1: \"World\"\n"
expectEqual(expected, output)
}
}
//===--- Standard library types -------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("String/Mirror") {
do {
var output = ""
dump("", to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}", to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("String.UTF8View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
var output = ""
dump("\u{61}\u{304b}\u{3099}".utf8, to: &output)
let expected =
"▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" +
" - 97\n" +
" - 227\n" +
" - 129\n" +
" - 139\n" +
" - 227\n" +
" - 130\n" +
" - 153\n"
expectEqual(expected, output)
}
mirrors.test("String.UTF16View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, to: &output)
let expected =
"▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - 97\n" +
" - 12363\n" +
" - 12441\n" +
" - 55357\n" +
" - 56357\n"
expectEqual(expected, output)
}
mirrors.test("String.UnicodeScalarView/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, to: &output)
let expected =
"▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - \"\u{61}\"\n" +
" - \"\\u{304B}\"\n" +
" - \"\\u{3099}\"\n" +
" - \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
mirrors.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: Character = "\u{304b}\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{304b}\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: Character = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("UnicodeScalar") {
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{304B}\"\n"
expectEqual(expected, output)
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("Bool") {
do {
var output = ""
dump(false, to: &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, to: &output)
let expected =
"- true\n"
expectEqual(expected, output)
}
}
// FIXME: these tests should cover Float80.
// FIXME: these tests should be automatically generated from the list of
// available floating point types.
mirrors.test("Float") {
do {
var output = ""
dump(Float.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Float = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
mirrors.test("Double") {
do {
var output = ""
dump(Double.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Double = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
mirrors.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("DictionaryIterator/Mirror") {
let d: [MinimalHashableValue : OpaqueValue<Int>] =
[ MinimalHashableValue(0) : OpaqueValue(0) ]
var output = ""
dump(d.makeIterator(), to: &output)
let expected =
"- Swift.Dictionary<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>.Iterator\n"
expectEqual(expected, output)
}
mirrors.test("SetIterator/Mirror") {
let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)]
var output = ""
dump(s.makeIterator(), to: &output)
let expected =
"- Swift.Set<StdlibUnittest.MinimalHashableValue>.Iterator\n"
expectEqual(expected, output)
}
//===--- Regressions ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// A struct type and class type whose NominalTypeDescriptor.FieldNames
// data is exactly eight bytes long. FieldNames data of exactly
// 4 or 8 or 16 bytes was once miscompiled on arm64.
struct EightByteFieldNamesStruct {
let abcdef = 42
}
class EightByteFieldNamesClass {
let abcdef = 42
}
mirrors.test("FieldNamesBug") {
do {
let expected =
"▿ Mirror.EightByteFieldNamesStruct\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesStruct(), to: &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ Mirror.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), to: &output)
expectEqual(expected, output)
}
}
mirrors.test("MirrorMirror") {
var object = 1
var mirror = Mirror(reflecting: object)
var mirrorMirror = Mirror(reflecting: mirror)
expectEqual(0, mirrorMirror.children.count)
}
mirrors.test("OpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
let pointer: OpaquePointer? = nil
let mirror = Mirror(reflecting: pointer)
expectEqual(0, mirror.children.count)
}
struct a<b> {
enum c{}
}
class d {}
struct e<f> {
var constraints: [Int: a<f>.c] = [:]
}
mirrors.test("GenericNestedTypeField") {
let x = e<d>()
expectTrue(type(of: Mirror(reflecting: x).children.first!.value)
== [Int: a<d>.c].self)
}
extension OtherOuter {
struct Inner {}
}
extension OtherOuterGeneric {
struct Inner<U> {}
}
mirrors.test("SymbolicReferenceInsideType") {
let s = OtherStruct(a: OtherOuter.Inner(),
b: OtherOuterGeneric<Int>.Inner<String>())
var output = ""
dump(s, to: &output)
let expected =
"▿ Mirror.OtherStruct\n" +
" - a: Mirror.OtherOuter.Inner\n" +
" - b: Mirror.OtherOuterGeneric<Swift.Int>.Inner<Swift.String>\n"
expectEqual(expected, output)
}
runAllTests()
| apache-2.0 | 43d66e6377a7b9df9df300f36c85bfff | 25.151279 | 139 | 0.612378 | 3.913767 | false | false | false | false |
practicalswift/swift | test/IDE/complete_pound_decl.swift | 10 | 1870 | // Testing #if condition does not disturb code completion
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_IF_MEMATTR | %FileCheck %s -check-prefix=ATTR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_IF_MEMBER | %FileCheck %s -check-prefix=MEMBER
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_ELSE_MEMBER | %FileCheck %s -check-prefix=MEMBER
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_ELSE_MEMATTR | %FileCheck %s -check-prefix=ATTR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_IF_GBLATTR | %FileCheck %s -check-prefix=ATTR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_IF_GBLNAME | %FileCheck %s -check-prefix=GLOBAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_ELIF_GBLNAME | %FileCheck %s -check-prefix=GLOBAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=POUND_ELIF_GBLATTR | %FileCheck %s -check-prefix=ATTR
// MEMBER: Begin completions
// MEMBER: override func foo() {|}; name=foo()
// MEMBER: End completions
// ATTR: Begin completions
// ATTR: available[#Func Attribute#]; name=available
// ATTR: End completions
// GLOBAL: Begin completions
// GLOBAL: Foo[#Foo#]; name=Foo
// GLOBAL: End completions
class Foo {
func foo() {}
}
class Bar : Foo {
#if true
@#^POUND_IF_MEMATTR^#
func f1() {}
#^POUND_IF_MEMBER^#
#else
#^POUND_ELSE_MEMBER^#
@#^POUND_ELSE_MEMATTR^#
func f1() {}
#endif
}
#if true
@#^POUND_IF_GBLATTR^#
func bar() {}
#^POUND_IF_GBLNAME^#
#elseif false
#^POUND_ELIF_GBLNAME^#
@#^POUND_ELIF_GBLATTR^#
func bar() {}
#endif
| apache-2.0 | 6f57e31951fb15879cbaa408715bb9fb | 34.283019 | 146 | 0.716043 | 3.229706 | false | true | false | false |
27629678/RxDemo | RxSwift.playground/Pages/ErrorHandling.xcplaygroundpage/Contents.swift | 1 | 2040 | //: [Previous Chapter: Combining](@previous)
import RxSwift
import Foundation
let disposeBag = DisposeBag()
let error = NSError(domain: "playground",
code: 404,
userInfo: ["key" : "description"])
//:
run("Catch") {
var count = 1
let sequenceThatErrors =
Observable<String>.create { observer in
observer.onNext("🍎")
observer.onNext("🍐")
observer.onNext("🍊")
if count == 1 {
observer.onError(error)
print("Error encountered")
count += 1
}
observer.onNext("🐶")
observer.onNext("🐱")
observer.onNext("🐭")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.catchError({ (error) -> Observable<String> in
return Observable.of("error")
})
// .catchErrorJustReturn("error")
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
//:
run("Retry") {
var count = 1
let sequenceThatErrors =
Observable<String>.create { observer in
observer.onNext("🍎")
observer.onNext("🍐")
observer.onNext("🍊")
if count == 1 {
observer.onError(error)
print("Error encountered")
count += 1
}
observer.onNext("🐶")
observer.onNext("🐱")
observer.onNext("🐭")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.retry()
// .retry(2)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
//:>注意Retry与Catch同时使用有副作用,比如,不可以多次Retry;同时要与Try、Catch的作用区分开
| mit | a564baefc76fc60860052f635271f354 | 23.871795 | 59 | 0.493299 | 5.091864 | false | false | false | false |
leyamcir/StarWars | StarWars/StarWarsUniverse.swift | 1 | 2214 | //
// StarWarsUniverse.swift
// StarWars
//
// Created by Alicia Daza on 23/06/16.
// Copyright © 2016 Alicia Daza. All rights reserved.
//
import UIKit
class StarWarsUniverse {
//MARK: Utility types
typealias StarWarsArray = [StarWarsCharacter]
typealias StarWarsDictionary = [StarWarsAffiliation: StarWarsArray]
//MARK: - Properties
var dict : StarWarsDictionary = StarWarsDictionary()
// Option with makeEmptyAffiliations static
//var dict : StarWarsDictionary
init (characteres chars: StarWarsArray) {
// Create empty dictionary
dict = makeEmptyAffiliations()
// Option with makeEmptyAffiliations static
//dict = StarWarsUniverse.makeEmptyAffiliations()
// Iterate array and assign depending on affiliation
for each in chars {
dict[each.affiliation]?.append(each)
}
}
var affiliationCount : Int {
get {
// Get affiliations count
return dict.count
}
}
func characterCount(forAffiliation affiliation: StarWarsAffiliation) -> Int {
// Get characters for this affiliation
// Mode 1: safer
guard let count = dict[affiliation]?.count else {
return 0
}
return count
// Mode 2: by force
//return (dict[affiliation]?.count)!
// Make sure in all affiliations are, at least an empty array
// Otherwise, app will crash
}
func character(atIndex index: Int, forAffiliation affiliation: StarWarsAffiliation) -> StarWarsCharacter {
// Character at index position in affiliation
let chars = dict[affiliation]!
let char = chars[index]
return char
}
func affiliationName(affiliation: StarWarsAffiliation) -> String {
return affiliation.rawValue
}
// MARK: Utils
func makeEmptyAffiliations() -> StarWarsDictionary {
var d = StarWarsDictionary()
d[.rebelAlliance] = StarWarsArray()
d[.galacticEmpire] = StarWarsArray()
d[.firstOrder] = StarWarsArray()
d[.jabbaCriminalEmpire] = StarWarsArray()
d[.unknown] = StarWarsArray()
return d
}
}
| gpl-3.0 | 7e4e0c7910fbef74ba6b40fb70e93cf4 | 25.345238 | 110 | 0.633077 | 4.973034 | false | false | false | false |
cvasilak/aerogear-ios-http | AeroGearHttp/JsonResponseSerializer.swift | 1 | 2319 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
A response deserializer to JSON objects.
*/
public class JsonResponseSerializer : ResponseSerializer {
public func response(data: NSData) -> (AnyObject?) {
return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)
}
public func validateResponse(response: NSURLResponse!, data: NSData, error: NSErrorPointer) -> Bool {
let httpResponse = response as NSHTTPURLResponse
if !(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
var userInfo = [
NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode),
NetworkingOperationFailingURLResponseErrorKey: response]
if (error != nil) {
error.memory = NSError(domain: HttpResponseSerializationErrorDomain, code: httpResponse.statusCode, userInfo: userInfo)
}
return false
}
// validate JSON
if (nil == NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)) {
let userInfo = [
NSLocalizedDescriptionKey: "Invalid response received, can't parse JSON" as NSString,
NetworkingOperationFailingURLResponseErrorKey: response]
if (error != nil) {
error.memory = NSError(domain: HttpResponseSerializationErrorDomain, code: NSURLErrorBadServerResponse, userInfo: userInfo)
}
return false;
}
return true
}
public init() {
}
} | apache-2.0 | da808b035b1b32cf2f189f04937ab933 | 36.419355 | 139 | 0.665373 | 5.587952 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/EditTextContentViewController.swift | 1 | 3640 | //
// EditTextContentViewController.swift
// ATests
//
// Created by Radu Costea on 29/05/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
class EditTextContentViewController: EditContentController, ContentProviderDelegate {
var content:ParseTextContent?
var text: String?
var contentProvider: TextProviderViewController!
override func getContent() -> PFObject? { return content }
@IBOutlet var textView: UILabel!
@IBOutlet var errorView: UIView!
var isLoading: Bool = false
var needsRefresh: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
contentProvider = TextProviderViewController.textProvider(nil)
contentProvider.delegate = self
if needsRefresh {
refresh()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadText()
let contentValid = true;//content?.isValid() ?? false
errorView.hidden = contentValid
textView.hidden = !contentValid
}
func loadText() {
guard isLoading == false else {
return
}
isLoading = true
needsRefresh = false
content?.fetchIfNeededInBackgroundWithBlock({ (c, error) in
print("loaded: \(c), error: \(error)")
if let txt = (c as? ParseTextContent)?.text {
self.text = txt
guard (self.isViewLoaded() && self.view?.window != nil) else {
self.needsRefresh = true
return
}
self.refresh()
}
})
}
func refresh() -> Void {
if let txt = self.text {
UIView.animateWithDuration(0.3, animations: {
self.errorView.hidden = txt.length > 0
self.contentProvider.loadWith(txt)
self.textView.text = txt
self.isLoading = false
})
}
self.needsRefresh = false
}
override func loadWith(content: PFObject?) {
if let txt = content as? ParseTextContent {
self.content = txt
loadText()
}
}
/// MARK: -
/// MARK: Class
override static var storyboardName: String { return "EditQuestionStoryboard" }
override static var storyboardId: String { return "editText" }
/// MARK: -
/// MARK: Actions
@IBAction func didTapOnContent(sender: AnyObject?) {
startEditing()
}
override func startEditing() {
if editingEnabled {
presentViewController(self.contentProvider, animated: true, completion: nil)
}
}
/// MARK: -
/// MARK: Conten Provider Delegate
func contentProvider<Provider: ContentProvider>(provider: Provider, finishedLoadingWith content: Provider.ContentType?) -> Void {
if let currentProvider = provider as? TextProviderViewController,
let txt = content as? String {
textView.text = txt
self.content?.text = txt
currentProvider.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
self.errorView.hidden = self.content?.isValid() ?? false
}
}
}
extension EditContentFabric {
class func textController(text:ParseTextContent?) -> EditTextContentViewController? {
return EditTextContentViewController.editController(text) as? EditTextContentViewController
}
}
| mit | 61434a1c278c08c2cd2a23ee1334875b | 29.325 | 133 | 0.596592 | 5.375185 | false | false | false | false |
jpaffrath/mpd-ios | mpd-ios/ViewControllerHome.swift | 1 | 8879 | //
// ViewControllerHome.swift
// mpd-ios
//
// Created by Julius Paffrath on 14.12.16.
// Copyright © 2016 Julius Paffrath. All rights reserved.
//
import UIKit
import SwiftSocket
import Toast_Swift
class ViewControllerHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let TAG_LABEL_SONGNAME: Int = 100
private let TAG_LABEL_SONGARTIST: Int = 101
private let COLOR_BLUE = UIColor.init(colorLiteralRed: Float(55.0/255), green: Float(111.0/255), blue: Float(165.0/255), alpha: 1)
private let TOAST_DURATION = 1.0
private let buttonImagePlay = UIImage(named: "play")
private let buttonImagePlayDisabled = UIImage(named: "play_disabled")
private let buttonImagePause = UIImage(named: "pause")
private let buttonImagePauseDisabled = UIImage(named: "pause_disabled")
private let buttonImageStop = UIImage(named: "stop")
private let buttonImageStopDisabled = UIImage(named: "stop_disabled")
private let buttonImageNext = UIImage(named: "next")
private let buttonImageNextDisabled = UIImage(named: "next_disabled")
private let buttonImagePrevious = UIImage(named: "previous")
private let buttonImagePreviousDisabled = UIImage(named: "previous_disabled")
private var currentPlaylist: [MPDSong] = []
private var mpdState: MPDStatus.MPDState = MPDStatus.MPDState.stop
private var updateTimer: Timer? = nil
private var currentSong: MPDSong? = nil
@IBOutlet weak var buttonPlay: UIButton!
@IBOutlet weak var buttonNext: UIButton!
@IBOutlet weak var buttonPrevious: UIButton!
@IBOutlet weak var tableViewSongs: UITableView!
@IBOutlet weak var labelCurrentSong: UILabel!
// MARK: Init
override func viewDidAppear(_ animated: Bool) {
if Settings.sharedInstance.getServer() == "" {
self.showSettingsViewController()
}
else {
self.initUpdateTimer()
}
}
override func viewWillDisappear(_ animated: Bool) {
self.updateTimer?.invalidate()
}
override func viewDidLoad() {
self.buttonNext.setImage(self.buttonImageNextDisabled, for: UIControlState.disabled)
self.buttonPrevious.setImage(self.buttonImagePreviousDisabled, for: UIControlState.disabled)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(ViewControllerHome.clearPlaylist))
}
private func initUpdateTimer() {
if #available(iOS 10.0, *) {
self.updateTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer: Timer) in
self.loadState()
})
} else {
}
}
// IBActions
@IBAction func play(_ sender: Any) {
self.disableButtons()
if self.mpdState == .play {
self.buttonPlay.setImage(self.buttonImagePlayDisabled, for: UIControlState.disabled)
MPD.sharedInstance.pause {
self.buttonPlay.setImage(self.buttonImagePlay, for: UIControlState.normal)
self.mpdState = .pause
self.enableButtons()
}
}
else {
self.buttonPlay.setImage(self.buttonImagePauseDisabled, for: UIControlState.disabled)
MPD.sharedInstance.resume {
self.buttonPlay.setImage(self.buttonImagePause, for: UIControlState.normal)
self.mpdState = .play
self.enableButtons()
}
}
}
@IBAction func next(_ sender: Any) {
self.disableButtons()
MPD.sharedInstance.playNextSong { (song: MPDSong?) in
self.enableButtons()
self.buttonPlay.setImage(self.buttonImagePause, for: UIControlState.normal)
self.loadCurrentSong(song: song)
}
}
@IBAction func previous(_ sender: Any) {
self.disableButtons()
MPD.sharedInstance.playPreviousSong { (song: MPDSong?) in
self.enableButtons()
self.buttonPlay.setImage(self.buttonImagePause, for: UIControlState.normal)
self.loadCurrentSong(song: song)
}
}
// MARK: Private Methods
private func showSettingsViewController() {
let alertController = UIAlertController(title: "Settings", message: "Please enter your server connection", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (alertAction: UIAlertAction) in
let textFieldServer = alertController.textFields![0] as UITextField
let textFieldPort = alertController.textFields![1] as UITextField
let settings: Settings = Settings.sharedInstance
settings.setServer(server: textFieldServer.text!)
settings.setPort(port: textFieldPort.text!)
self.loadState()
}))
alertController.addTextField { (textField: UITextField) in
textField.placeholder = "Server"
textField.keyboardType = UIKeyboardType.URL
}
alertController.addTextField { (textField: UITextField) in
textField.placeholder = "Port"
textField.keyboardType = UIKeyboardType.numbersAndPunctuation
}
present(alertController, animated: true, completion: nil)
}
private func loadState() {
MPD.sharedInstance.getStatus { (status: MPDStatus?) in
if status != nil {
self.mpdState = status!.state
switch self.mpdState {
case .play:
self.buttonPlay.setImage(UIImage(named: "pause"), for: UIControlState.normal)
break
case .pause:
self.buttonPlay.setImage(UIImage(named: "play"), for: UIControlState.normal)
break
case .stop:
self.buttonPlay.setImage(UIImage(named: "play"), for: UIControlState.normal)
break
}
}
MPD.sharedInstance.getCurrentPlaylist { (songs: [MPDSong]) in
MPD.sharedInstance.getCurrentSong { (song: MPDSong?) in
if self.currentPlaylist != songs || self.currentPlaylist.isEmpty {
self.currentPlaylist = songs
self.tableViewSongs.reloadData()
}
self.loadCurrentSong(song: song)
}
}
}
}
private func enableButtons() {
self.buttonPlay.isEnabled = true
self.buttonNext.isEnabled = true
self.buttonPrevious.isEnabled = true
}
private func disableButtons() {
self.buttonPlay.isEnabled = false
self.buttonNext.isEnabled = false
self.buttonPrevious.isEnabled = false
}
private func loadCurrentSong(song: MPDSong?) {
if let title = song?.title, let artist = song?.artist {
if self.currentSong != song {
self.currentSong = song
self.labelCurrentSong.text = "\(title) - \(artist)"
self.scrollToSong(song: song)
}
}
else {
self.labelCurrentSong.text = "No current song"
}
}
func clearPlaylist() {
MPD.sharedInstance.clearCurrentPlaylist {
self.view.makeToast("Current playlist is cleared", duration: self.TOAST_DURATION, position: .center)
}
}
private func scrollToSong(song: MPDSong?) {
if song != nil {
if let index = self.currentPlaylist.index(of: song!) {
let indexPath = IndexPath(row: index, section: 0)
self.tableViewSongs.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
// MARK: TableView Delegates
func numberOfSections(in tableView: UITableView) -> Int {
if self.currentPlaylist.count > 0 {
self.tableViewSongs.separatorStyle = UITableViewCellSeparatorStyle.singleLine
self.tableViewSongs.backgroundView = nil
return 1
}
else {
let size = self.tableViewSongs.bounds.size
let labelMsg = UILabel.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height)))
labelMsg.text = "Empty playlist"
labelMsg.textColor = self.COLOR_BLUE
labelMsg.numberOfLines = 0
labelMsg.textAlignment = NSTextAlignment.center
labelMsg.font = UIFont.init(name: "Avenir", size: 20)
labelMsg.sizeToFit()
self.tableViewSongs.backgroundView = labelMsg
self.tableViewSongs.separatorStyle = UITableViewCellSeparatorStyle.none
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.currentPlaylist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let labelSongname: UILabel = cell.viewWithTag(self.TAG_LABEL_SONGNAME) as! UILabel
labelSongname.text = String(self.currentPlaylist[indexPath.row].title)
let labelArtist: UILabel = cell.viewWithTag(self.TAG_LABEL_SONGARTIST) as! UILabel
labelArtist.text = self.currentPlaylist[indexPath.row].artist
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Current Playlist"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
MPD.sharedInstance.play(nr: indexPath.row) {
self.tableViewSongs.deselectRow(at: indexPath, animated: true)
self.loadState()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
MPD.sharedInstance.delete(nr: indexPath.row, handler: {
})
}
}
}
| gpl-3.0 | 8afd602ed912877500abe9ac7e8dd0ce | 29.613793 | 154 | 0.729444 | 3.881941 | false | false | false | false |
austinzheng/swift | stdlib/public/core/StringUnicodeScalarView.swift | 2 | 14987 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of Unicode scalar values.
///
/// You can access a string's view of Unicode scalar values by using its
/// `unicodeScalars` property. Unicode scalar values are the 21-bit codes
/// that are the basic unit of Unicode. Each scalar value is represented by
/// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.unicodeScalars {
/// print(v.value)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 128144
///
/// Some characters that are visible in a string are made up of more than one
/// Unicode scalar value. In that case, a string's `unicodeScalars` view
/// contains more elements than the string itself.
///
/// let flag = "🇵🇷"
/// for c in flag {
/// print(c)
/// }
/// // 🇵🇷
///
/// for v in flag.unicodeScalars {
/// print(v.value)
/// }
/// // 127477
/// // 127479
///
/// You can convert a `String.UnicodeScalarView` instance back into a string
/// using the `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) {
/// let asciiPrefix = String(favemoji.unicodeScalars[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
@_fixed_layout
public struct UnicodeScalarView {
@usableFromInline
internal var _guts: _StringGuts
@inlinable @inline(__always)
internal init(_ _guts: _StringGuts) {
self._guts = _guts
_invariantCheck()
}
}
}
extension String.UnicodeScalarView {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
// TODO: Assert start/end are scalar aligned
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UnicodeScalarView: BidirectionalCollection {
public typealias Index = String.Index
/// The position of the first Unicode scalar value if the string is
/// nonempty.
///
/// If the string is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// Returns the next consecutive location after `i`.
///
/// - Precondition: The next location exists.
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
_internalInvariant(i < endIndex)
// TODO(String performance): isASCII fast-path
if _fastPath(_guts.isFastUTF8) {
let len = _guts.fastUTF8ScalarLength(startingAt: i.encodedOffset)
return i.encoded(offsetBy: len)
}
return _foreignIndex(after: i)
}
/// Returns the previous consecutive location before `i`.
///
/// - Precondition: The previous location exists.
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
precondition(i.encodedOffset > 0)
// TODO(String performance): isASCII fast-path
if _fastPath(_guts.isFastUTF8) {
let len = _guts.withFastUTF8 { utf8 -> Int in
return _utf8ScalarLength(utf8, endingAt: i.encodedOffset)
}
_internalInvariant(len <= 4, "invalid UTF8")
return i.encoded(offsetBy: -len)
}
return _foreignIndex(before: i)
}
/// Accesses the Unicode scalar value at the given position.
///
/// The following example searches a string's Unicode scalars view for a
/// capital letter and then prints the character and Unicode scalar value
/// at the found index:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) {
/// print("First capital letter: \(greeting.unicodeScalars[i])")
/// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)")
/// }
/// // Prints "First capital letter: H"
/// // Prints "Unicode scalar value: 72"
///
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
@inlinable
public subscript(position: Index) -> Unicode.Scalar {
@inline(__always) get {
String(_guts)._boundsCheck(position)
let i = _guts.scalarAlign(position)
return _guts.errorCorrectedScalar(startingAt: i.encodedOffset).0
}
}
}
extension String.UnicodeScalarView {
@_fixed_layout
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _guts: _StringGuts
@usableFromInline
internal var _position: Int = 0
@usableFromInline
internal var _end: Int
@inlinable
internal init(_ guts: _StringGuts) {
self._end = guts.count
self._guts = guts
}
@inlinable
@inline(__always)
public mutating func next() -> Unicode.Scalar? {
guard _fastPath(_position < _end) else { return nil }
let (result, len) = _guts.errorCorrectedScalar(startingAt: _position)
_position &+= len
return result
}
}
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_guts)
}
}
extension String.UnicodeScalarView: CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(_guts) }
}
}
extension String.UnicodeScalarView: CustomDebugStringConvertible {
public var debugDescription: String {
return "StringUnicodeScalarView(\(self.description.debugDescription))"
}
}
extension String {
/// Creates a string corresponding to the given collection of Unicode
/// scalars.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `unicodeScalars` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") {
/// let adjective = String(picnicGuest.unicodeScalars[..<i])
/// print(adjective)
/// }
/// // Prints "Deserving"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.unicodeScalars` view.
///
/// - Parameter unicodeScalars: A collection of Unicode scalar values.
@inlinable @inline(__always)
public init(_ unicodeScalars: UnicodeScalarView) {
self.init(unicodeScalars._guts)
}
/// The index type for a string's `unicodeScalars` view.
public typealias UnicodeScalarIndex = UnicodeScalarView.Index
/// The string's value represented as a collection of Unicode scalar values.
@inlinable
public var unicodeScalars: UnicodeScalarView {
@inline(__always) get { return UnicodeScalarView(_guts) }
@inline(__always) set { _guts = newValue._guts }
}
}
extension String.UnicodeScalarView : RangeReplaceableCollection {
/// Creates an empty view instance.
@inlinable @inline(__always)
public init() {
self.init(_StringGuts())
}
/// Reserves enough space in the view's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because a Unicode scalar value can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding to a Unicode scalar view after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*), where *n* is the capacity being reserved.
public mutating func reserveCapacity(_ n: Int) {
self._guts.reserveCapacity(n)
}
/// Appends the given Unicode scalar to the view.
///
/// - Parameter c: The character to append to the string.
public mutating func append(_ c: Unicode.Scalar) {
self._guts.append(String(c)._guts)
}
/// Appends the Unicode scalar values in the given sequence to the view.
///
/// - Parameter newElements: A sequence of Unicode scalar values.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting view.
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Unicode.Scalar {
// TODO(String performance): Skip extra String allocation
let scalars = String(decoding: newElements.map { $0.value }, as: UTF32.self)
self = (String(self._guts) + scalars).unicodeScalars
}
/// Replaces the elements within the specified bounds with the given Unicode
/// scalar values.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - bounds: The range of elements to replace. The bounds of the range
/// must be valid indices of the view.
/// - newElements: The new Unicode scalar values to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the view and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes elements at the end of the string, the complexity is O(*n*),
/// where *n* is equal to `bounds.count`.
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Unicode.Scalar {
// TODO(String performance): Skip extra String and Array allocation
let utf8Replacement = newElements.flatMap { String($0).utf8 }
let replacement = utf8Replacement.withUnsafeBufferPointer {
return String._uncheckedFromUTF8($0)
}
var copy = String(_guts)
copy.replaceSubrange(bounds, with: replacement)
self = copy.unicodeScalars
}
}
// Index conversions
extension String.UnicodeScalarIndex {
/// Creates an index in the given Unicode scalars view that corresponds
/// exactly to the specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `unicodeScalars` view:
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)!
///
/// print(String(cafe.unicodeScalars[..<scalarIndex]))
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `unicodeScalars`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair results in `nil`.
///
/// - Parameters:
/// - sourcePosition: A position in the `utf16` view of a string.
/// `utf16Index` must be an element of
/// `String(unicodeScalars).utf16.indices`.
/// - unicodeScalars: The `UnicodeScalarView` in which to find the new
/// position.
public init?(
_ sourcePosition: String.Index,
within unicodeScalars: String.UnicodeScalarView
) {
guard unicodeScalars._guts.isOnUnicodeScalarBoundary(sourcePosition) else {
return nil
}
self = sourcePosition
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.unicodeScalars.firstIndex(of: "🍵")
/// let j = i.samePosition(in: cafe)!
/// print(cafe[j...])
/// // Prints "🍵"
///
/// - Parameter characters: The string to use for the index conversion.
/// This index must be a valid index of at least one view of `characters`.
/// - Returns: The position in `characters` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `characters`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
public func samePosition(in characters: String) -> String.Index? {
return String.Index(self, within: characters)
}
}
// Reflection
extension String.UnicodeScalarView : CustomReflectable {
/// Returns a mirror that reflects the Unicode scalars view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.unicodeScalars[
/// someString.unicodeScalars.startIndex
/// ..< someString.unicodeScalars.endIndex]
///
/// was deduced to be of type `String.UnicodeScalarView`. Provide a
/// more-specific Swift-3-only `subscript` overload that continues to produce
/// `String.UnicodeScalarView`.
extension String.UnicodeScalarView {
public typealias SubSequence = Substring.UnicodeScalarView
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence {
return String.UnicodeScalarView.SubSequence(self, _bounds: r)
}
}
// Foreign string Support
extension String.UnicodeScalarView {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_internalInvariant(_guts.isForeign)
let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: i)
let len = _isLeadingSurrogate(cu) ? 2 : 1
return i.encoded(offsetBy: len)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_internalInvariant(_guts.isForeign)
let priorIdx = i.priorEncoded
let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: priorIdx)
let len = _isTrailingSurrogate(cu) ? 2 : 1
return i.encoded(offsetBy: -len)
}
}
| apache-2.0 | 432aac32084aab606497ae77007d5f39 | 33.298165 | 85 | 0.653671 | 4.32822 | false | false | false | false |
kemalenver/SwiftHackerRank | Security/Functions.playground/Pages/Security Function Inverses.xcplaygroundpage/Contents.swift | 1 | 370 |
var inputs = ["3", "2 3 1"]
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
var n = Int(readLine()!)!
var arr = readLine()!.characters.split(separator: " ").map{Int(String($0))!}
for i in 1...n+1 {
for j in 0..<n {
if arr[j] == i {
print(j+1)
}
}
} | mit | 78105c1a334ff6521e836a0c992d4da3 | 14.458333 | 76 | 0.467568 | 3.245614 | false | false | false | false |
PrashantMangukiya/SwiftAnimation | SwiftAnimation/SwiftAnimation/MoveObjectAutoViewController.swift | 1 | 4630 | //
// MoveObjectAutoViewController.swift
// SwiftAnimation
//
// Created by Prashant on 16/09/15.
// Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class MoveObjectAutoViewController: UIViewController {
// start and end x position
var startX : CGFloat = 0
var endX : CGFloat = 0
// start and end y position
var startY : CGFloat = 0
var endY : CGFloat = 0
// object widh and height
var objectWidth : CGFloat = 100.0
var objectHeight : CGFloat = 100.0
// object to animate
var animationObject : UIImageView!
// outlet - bottom toolbar
@IBOutlet var bottomToolbar: UIToolbar!
// outlet and action - play button
@IBOutlet var playButton: UIBarButtonItem!
@IBAction func playButtonAction(sender: UIBarButtonItem) {
// play animation
self.playAnimation()
// disable play button
self.playButton.enabled = false
// enable stop button
self.stopButton.enabled = true
}
// outlet and action - stop button
@IBOutlet var stopButton: UIBarButtonItem!
@IBAction func stopButtonAction(sender: UIBarButtonItem) {
// stop animation
self.stopAnimation()
// enable play button
self.playButton.enabled = true
// disable stop button
self.stopButton.enabled = false
}
// MARK - View functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// enable play button
self.playButton.enabled = true
// disable stop button
self.stopButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
// calculate start/end postion based on screen size.
self.setDimension()
// setup animation object on the screen
self.setUpObject()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - utility function
// calculate start/end postion based on screen size.
private func setDimension() -> Void {
// set start, end X postion
self.startX = self.view.frame.width/2 - self.objectWidth/2
self.endX = self.startX
// set start. end Y postion
self.startY = self.navigationController!.navigationBar.frame.maxY + 10
self.endY = self.bottomToolbar.frame.minY - self.objectHeight - 10
}
// setup animation object on the screen
private func setUpObject() -> Void {
// create image view
self.animationObject = UIImageView()
// set image
self.animationObject.image = UIImage(named: "Soccer-Ball")
// set frame
self.animationObject.frame = CGRect(x: self.startX, y: self.startY, width: self.objectWidth, height: self.objectHeight)
// add object into view
self.view.addSubview(self.animationObject)
}
// play animation
private func playAnimation()-> Void {
// animation duration
let animationDuration : NSTimeInterval = 1.0
// set any delay before start animation
let animationDelay : NSTimeInterval = 0.0
// set animation options
let animationOptions : UIViewAnimationOptions = [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.Autoreverse, UIViewAnimationOptions.Repeat]
// animate the object
UIView.animateWithDuration(animationDuration, delay: animationDelay, options: animationOptions,
animations: { () -> Void in
// set end position for animation object
self.animationObject.frame = CGRect(x: self.endX, y: self.endY, width: self.objectWidth, height: self.objectHeight)
},
completion: { (isDone: Bool) -> Void in
// at completion of animaton, set object at default position
self.animationObject.frame = CGRect(x: self.startX, y: self.startY, width: self.objectWidth, height: self.objectHeight)
})
}
// stop the currently runing animation
private func stopAnimation() -> Void {
// remove all animation from object
self.animationObject.layer.removeAllAnimations()
}
}
| mit | 2d50d5a7bb8b2807abaa970dbe180e71 | 28.119497 | 162 | 0.601512 | 5.309633 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil | AppcidCocoaUtil/ACDFormSheetViewController.swift | 1 | 6489 | //
// ACDFormSheetViewController.swift
// ACD
//
// Created by Jaeyoung Choi on 2015. 11. 17..
// Copyright © 2015년 Appcid. All rights reserved.
//
#if os(iOS)
import UIKit
enum ACDFormSheetViewControllerAnimation {
case none
case popupCenter
}
class ACDFromSheetView: UIView {
override var intrinsicContentSize : CGSize {
return CGSize(width: 100, height: 50)
}
}
protocol ACDFormSheetViewControllerDelegate: class {
func closed()
}
open class ACDFormSheetViewController: UIViewController, ACDOverlay {
var isFirstViewWillAppear = true
var statusBarHidden = false
let contentView = ACDFromSheetView()
let contentViewPadding: CGFloat = 24
var centerConstraint: CenterConstraints!
var dismissTapGesture: UITapGestureRecognizer!
var dismissWhenTapDimmingView = true {
didSet {
invalidateDismissTapBehavior()
}
}
let dimmingView = UIView()
var animation = ACDFormSheetViewControllerAnimation.popupCenter
weak var delegate: ACDFormSheetViewControllerDelegate?
lazy var parallaxMotionEffect: UIMotionEffect = {
let value = 15
let xAxis = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
xAxis.minimumRelativeValue = value
xAxis.maximumRelativeValue = -value
let yAxis = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
yAxis.minimumRelativeValue = value
yAxis.maximumRelativeValue = -value
let group = UIMotionEffectGroup()
group.motionEffects = [xAxis, yAxis]
return group
}()
var parallaxEnabled = true {
didSet {
invalidateParallax()
}
}
func initSetup() {
modalPresentationStyle = .custom
dismissTapGesture = UITapGestureRecognizer(target: self, action: #selector(ACDFormSheetViewController.tap(_:)))
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
deinit {
print("deinit ACDFormSheetViewController")
}
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
dimmingView.backgroundColor = UIColor(white: 0, alpha: 0.45)
view.addSubview(dimmingView)
dimmingView.fillToSuperview()
contentView.backgroundColor = UIColor.white
contentView.layer.cornerRadius = 4
contentView.clipsToBounds = true
view.addSubview(contentView)
centerConstraint = contentView.centerToSuperview()
NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .lessThanOrEqual, toItem: view, attribute: .width, multiplier: 1, constant: -(contentViewPadding * 2)).isActive = true
NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 226).isActive = true
NSLayoutConstraint(item: contentView, attribute: .height, relatedBy: .lessThanOrEqual, toItem: view, attribute: .height, multiplier: 1, constant: -(contentViewPadding * 2)).isActive = true
invalidateDismissTapBehavior()
invalidateParallax()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isFirstViewWillAppear {
isFirstViewWillAppear = false
if animation == .popupCenter {
contentView.alpha = 0
contentView.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .beginFromCurrentState, animations: { () -> Void in
self.contentView.alpha = 0.9
self.contentView.transform = CGAffineTransform(scaleX: 1.01, y: 1.01)
}, completion: { (flag) -> Void in
if flag {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: { () -> Void in
self.contentView.alpha = 1
self.contentView.transform = CGAffineTransform.identity
}, completion: nil)
}
})
}
}
}
override open var prefersStatusBarHidden : Bool {
return statusBarHidden
}
func invalidateDismissTapBehavior() {
if dismissWhenTapDimmingView {
dimmingView.addGestureRecognizer(dismissTapGesture)
} else {
dimmingView.removeGestureRecognizer(dismissTapGesture)
}
}
func tap(_ gesture: UITapGestureRecognizer) {
guard gesture === dismissTapGesture && dismissWhenTapDimmingView == true && gesture.state == .recognized else {
return
}
close(nil)
}
func close(_ sender: AnyObject?) {
dismiss(animated: true) {
if let delegate = self.delegate {
delegate.closed()
}
}
}
func refreshContentViewConstraints(_ constraints: [NSLayoutConstraint]) {
NSLayoutConstraint.deactivate(contentView.constraints)
NSLayoutConstraint.activate(constraints)
}
func invalidateParallax() {
if parallaxEnabled {
contentView.addMotionEffect(parallaxMotionEffect)
} else {
for motionEffect in contentView.motionEffects {
contentView.removeMotionEffect(motionEffect)
}
}
}
/*
// 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.
}
*/
}
#endif
| mit | d3bec0b8606eaa810830cdb09ff2cb26 | 32.43299 | 196 | 0.623651 | 5.581756 | false | false | false | false |
cnstoll/Snowman | Snowman/Snowman WatchKit Extension/WKInterfaceDevice+Extensions.swift | 1 | 1513 | //
// WKInterfaceDevice+Extensions.swift
// Snowman WatchKit Extension
//
// Created by Conrad Stoll on 1/2/19.
// Copyright © 2019 Conrad Stoll. All rights reserved.
//
import WatchKit
extension WKInterfaceDevice {
enum WatchResolution : String {
case Watch38mm, Watch40mm, Watch42mm, Watch44mm, Unknown
}
class func currentResolution() -> WatchResolution {
let watch38mmRect = CGRect(x: 0, y: 0, width: 136, height: 170)
let watch42mmRect = CGRect(x: 0, y: 0, width: 156, height: 195)
let watch40mmRect = CGRect(x: 0, y: 0, width: 162, height: 197)
let watch44mmRect = CGRect(x: 0, y: 0, width: 184, height: 224)
let currentBounds = current().screenBounds
switch currentBounds {
case watch38mmRect:
return .Watch38mm
case watch40mmRect:
return .Watch40mm
case watch42mmRect:
return .Watch42mm
case watch44mmRect:
return .Watch44mm
default:
return .Unknown
}
}
class func drawingSize() -> CGSize {
switch currentResolution() {
case .Watch38mm:
return CGSize(width: 134, height: 150)
case .Watch40mm:
return CGSize(width: 150, height: 168)
case .Watch44mm:
return CGSize(width: 170, height: 192)
case .Unknown: fallthrough
case .Watch42mm:
return CGSize(width: 154, height: 174)
}
}
}
| apache-2.0 | ebc0f1d49a413f5c0a861a2cad681f8b | 28.076923 | 71 | 0.587963 | 4.153846 | false | false | false | false |
Raiden9000/Sonarus | SegmentViewController.swift | 1 | 3162 | //
// SegmentViewController.swift
// Sonarus
//
// Created by Christopher Arciniega on 6/7/17.
// Copyright © 2017 HQZenithLabs. All rights reserved.
//
import Foundation
//View controller that switches between chat view and music queue view
class SegmentViewController:UIViewController{
private var chatView:ChatViewController!
private var musicQueueView:SongQueueController!
private var chatHidden:Bool = true
override func viewDidLoad() {
chatView = ChatViewController()
musicQueueView = SongQueueController()
musicQueueView.view.translatesAutoresizingMaskIntoConstraints = false
chatView.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(musicQueueView.view)
view.addSubview(chatView.view)
NSLayoutConstraint.activate([
musicQueueView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
musicQueueView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
musicQueueView.view.topAnchor.constraint(equalTo: view.topAnchor),
musicQueueView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
//musicQueueView.view.heightAnchor.constraint(equalTo: view.heightAnchor),
chatView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
chatView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
chatView.view.topAnchor.constraint(equalTo: view.topAnchor),
chatView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
//chatView.view.heightAnchor.constraint(equalTo: view.heightAnchor)
])
chatView.view.isHidden = true
}
func showChat(){
/* Useful for when views have same parent controller. Not this case, but left here for when needed.
chatView.view.frame = musicQueueView.view.frame
musicQueueView.willMove(toParentViewController: nil)
self.addChildViewController(chatView)
self.transition(from: musicQueueView, to: chatView, duration: 0.6, options: .transitionCrossDissolve, animations: {}, completion: {(finished:Bool) in
self.musicQueueView.removeFromParentViewController()
self.chatView.didMove(toParentViewController: self)
})
*/
chatHidden = false
chatView.view.isHidden = false
musicQueueView.view.isHidden = true
view.layoutIfNeeded()
}
func showMusicQueue(){
/*
musicQueueView.view.frame = chatView.view.frame
chatView.willMove(toParentViewController: nil)
self.addChildViewController(musicQueueView)
self.transition(from: chatView, to: musicQueueView, duration: 0.6, options: .transitionCrossDissolve, animations: {}, completion: {(finished:Bool) in
self.chatView.removeFromParentViewController()
self.musicQueueView.didMove(toParentViewController: self)
})
*/
chatHidden = true
chatView.view.isHidden = true
musicQueueView.view.isHidden = false
}
}
| mit | 8fe7ea6004cb1667b132bc0116944cf0 | 42.902778 | 157 | 0.686175 | 5.403419 | false | false | false | false |
TardisCXX/TCPageView | TCPageViewProject/TCPageView/TCPageViewFlowLayout.swift | 1 | 2902 | //
// TCPageViewFlowLayout.swift
// TCPageViewProject
//
// Created by tardis_cxx on 2017-5-16.
// Copyright © 2017年 tardis_cxx. All rights reserved.
//
import UIKit
class TCPageViewFlowLayout: UICollectionViewFlowLayout {
/// 设置列数
var cols = 4
/// 设置行数
var rows = 2
fileprivate lazy var cellAttributes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
/// 页数
fileprivate var pageCount = 0
}
extension TCPageViewFlowLayout {
override func prepare() {
super.prepare()
guard let collectionView = collectionView else {
return
}
let sectionCount = collectionView.numberOfSections
let itemW: CGFloat = (collectionView.bounds.width - sectionInset.left - sectionInset.right - CGFloat((cols - 1)) * minimumInteritemSpacing) / CGFloat(cols)
let itemH: CGFloat = (collectionView.bounds.height - sectionInset.top - sectionInset.bottom - CGFloat((rows - 1)) * minimumLineSpacing) / CGFloat(rows)
var itemY: CGFloat = 0
var itemX: CGFloat = 0
// 累加页数
for sectionIndex in 0..<sectionCount {
let itemCount = collectionView.numberOfItems(inSection: sectionIndex)
for itemIndex in 0..<itemCount {
let indexPath = IndexPath(item: itemIndex, section: sectionIndex)
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
// item 所在页码
let pageIndex = itemIndex / (rows * cols)
// item 当前页码的索引
let pageItemIndex = itemIndex % (rows * cols)
// item 所在行
let rowIndex = pageItemIndex / cols
// item 所在列
let colIndex = pageItemIndex % cols
itemY = sectionInset.top + (itemH + minimumLineSpacing) * CGFloat(rowIndex)
itemX = CGFloat((pageCount + pageIndex)) * collectionView.bounds.width + sectionInset.left + (itemW + minimumInteritemSpacing) * CGFloat(colIndex)
attr.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
cellAttributes.append(attr)
}
// 计算当前组一共有多少页
pageCount += (itemCount - 1) / (cols * rows) + 1
}
}
}
extension TCPageViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return cellAttributes
}
}
extension TCPageViewFlowLayout {
override var collectionViewContentSize: CGSize {
return CGSize(width: CGFloat(pageCount) * collectionView!.bounds.width, height: 0)
}
}
| mit | dac4c54421c723929df37f35cf25339c | 32.117647 | 163 | 0.591829 | 5.331439 | false | false | false | false |
tomasharkema/HoelangTotTrein.iOS | Pods/Observable-Swift/Observable-Swift/Observable.swift | 9 | 1519 | //
// Observable.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 20/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
/// A struct representing information associated with value change event.
public struct ValueChange<T> {
public let oldValue: T
public let newValue: T
public init(_ o: T, _ n: T) {
oldValue = o
newValue = n
}
}
// Implemented as a struct in order to have desired value and mutability sementics.
/// A struct representing an observable value.
public struct Observable<T> : UnownableObservable {
public typealias ValueType = T
public /*internal(set)*/ var beforeChange = EventReference<ValueChange<T>>()
public /*internal(set)*/ var afterChange = EventReference<ValueChange<T>>()
public var value : T {
willSet { beforeChange.notify(ValueChange(value, newValue)) }
didSet { afterChange.notify(ValueChange(oldValue, value)) }
}
public mutating func unshare(#removeSubscriptions: Bool) {
if removeSubscriptions {
beforeChange = EventReference<ValueChange<T>>()
afterChange = EventReference<ValueChange<T>>()
} else {
beforeChange = EventReference<ValueChange<T>>(event: beforeChange.event)
beforeChange.event.unshare()
afterChange = EventReference<ValueChange<T>>(event: afterChange.event)
afterChange.event.unshare()
}
}
public init(_ v : T) {
value = v
}
}
| apache-2.0 | 9fd433b502753375c45afdc4b84f6fa3 | 29.877551 | 84 | 0.652346 | 4.584848 | false | false | false | false |
imfeemily/NPSegmentedControl | NPSegmentedControl/ViewController.swift | 1 | 1847 | //
// ViewController.swift
// NPSegmentedControl
//
// Created by Yvan Moté on 05/03/2015.
// Copyright (c) 2015 Neopixl. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var selector: NPSegmentedControl!
@IBOutlet weak var labelIndex: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var myElements = ["First","Second","Third","Fourth"]
selector.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1)
selector.cursor = UIImageView(image: UIImage(named: "tabindicator"))
selector.unselectedFont = UIFont(name: "HelveticaNeue-Light", size: 16)
selector.selectedFont = UIFont(name: "HelveticaNeue-Bold", size: 16)
selector.unselectedTextColor = UIColor(white: 1, alpha: 0.8)
selector.unselectedColor = UIColor(red: 10/255, green: 137/255, blue: 169/255, alpha: 0.8)
selector.selectedTextColor = UIColor(white: 1, alpha: 1)
selector.selectedColor = UIColor(red: 10/255, green: 137/255, blue: 169/255, alpha: 1)
selector.setItems(myElements)
labelIndex.text = "Index : \(selector.selectedIndex())"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTest(sender: AnyObject) {
selector.selectedColor = UIColor.redColor()
selector.unselectedFont = UIFont.systemFontOfSize(12)
selector.cursor = nil
}
//MARK: value changed on NPSelectorView
@IBAction func selectorValueChanged(sender: AnyObject) {
labelIndex.text = "Index : \(selector.selectedIndex())"
}
}
| apache-2.0 | 11145b3d01013f4436b0d470a4598001 | 34.5 | 98 | 0.662514 | 4.353774 | false | false | false | false |
samnm/material-components-ios | components/Buttons/examples/ButtonsDynamicTypeViewController.swift | 2 | 3239 | /*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialButtons
class ButtonsDynamicTypeViewController: UIViewController {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Buttons", "Buttons (DynamicType)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
@objc class func catalogIsPresentable() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.9, alpha:1.0)
let titleColor = UIColor.white
let backgroundColor = UIColor(white: 0.1, alpha: 1.0)
let flatButtonStatic = MDCRaisedButton()
flatButtonStatic.setTitleColor(titleColor, for: .normal)
flatButtonStatic.setBackgroundColor(backgroundColor, for: .normal)
flatButtonStatic.setTitle("Static", for: UIControlState())
flatButtonStatic.sizeToFit()
flatButtonStatic.translatesAutoresizingMaskIntoConstraints = false
flatButtonStatic.addTarget(self, action: #selector(tap), for: .touchUpInside)
view.addSubview(flatButtonStatic)
let flatButtonDynamic = MDCRaisedButton()
flatButtonDynamic.setTitleColor(titleColor, for: .normal)
flatButtonDynamic.setBackgroundColor(backgroundColor, for: .normal)
flatButtonDynamic.setTitle("Dynamic", for: UIControlState())
flatButtonDynamic.sizeToFit()
flatButtonDynamic.translatesAutoresizingMaskIntoConstraints = false
flatButtonDynamic.addTarget(self, action: #selector(tap), for: .touchUpInside)
flatButtonDynamic.mdc_adjustsFontForContentSizeCategory = true
view.addSubview(flatButtonDynamic)
let views = [
"flatStatic": flatButtonStatic,
"flatDynamic": flatButtonDynamic
]
centerView(view: flatButtonDynamic, onView: self.view)
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:[flatStatic]-40-[flatDynamic]",
options: .alignAllCenterX,
metrics: nil,
views: views))
}
// MARK: Private
func centerView(view: UIView, onView: UIView) {
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerX,
relatedBy: .equal,
toItem: onView,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0))
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerY,
relatedBy: .equal,
toItem: onView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
}
@objc func tap(_ sender: Any) {
print("\(type(of: sender)) was tapped.")
}
}
| apache-2.0 | b48500e38027c6c61c6f8d337e819a40 | 31.069307 | 89 | 0.70176 | 4.922492 | false | false | false | false |
lorentey/swift | benchmark/single-source/OpaqueConsumingUsers.swift | 22 | 2260 | //===--- OpaqueConsumingUsers.swift ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let OpaqueConsumingUsers = BenchmarkInfo(
name: "OpaqueConsumingUsers",
runFunction: run_OpaqueConsumingUsers,
tags: [.regression, .abstraction, .refcount],
setUpFunction: setup_OpaqueConsumingUsers,
legacyFactor: 20)
// This test exercises the ability of the optimizer to propagate the +1 from a
// consuming argument of a non-inlineable through multiple non-inlinable call
// frames.
//
// We are trying to simulate a user application that calls into a resilient
// setter or initialization. We want to be able to propagate the +1 from the
// setter through the app as far as we can.
class Klass {}
class ConsumingUser {
var _innerValue: Klass = Klass()
var value: Klass {
@inline(never) get {
return _innerValue
}
@inline(never) set {
_innerValue = newValue
}
}
}
var data: Klass? = nil
var user: ConsumingUser? = nil
func setup_OpaqueConsumingUsers() {
switch (data, user) {
case (let x?, let y?):
let _ = x
let _ = y
return
case (nil, nil):
data = Klass()
user = ConsumingUser()
default:
fatalError("Data and user should both be .none or .some")
}
}
@inline(never)
func callFrame1(_ data: Klass, _ user: ConsumingUser) {
callFrame2(data, user)
}
@inline(never)
func callFrame2(_ data: Klass, _ user: ConsumingUser) {
callFrame3(data, user)
}
@inline(never)
func callFrame3(_ data: Klass, _ user: ConsumingUser) {
callFrame4(data, user)
}
@inline(never)
func callFrame4(_ data: Klass, _ user: ConsumingUser) {
user.value = data
}
@inline(never)
public func run_OpaqueConsumingUsers(_ N: Int) {
let d = data.unsafelyUnwrapped
let u = user.unsafelyUnwrapped
for _ in 0..<N*10_000 {
callFrame4(d, u)
}
}
| apache-2.0 | 702096ec3b25a4924c545c5ecb18914d | 24.393258 | 80 | 0.656637 | 3.985891 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/TabBar/TabBarCoordinator.swift | 1 | 39859 | // File created from FlowTemplate
// $ createRootCoordinator.sh TabBar TabBar
/*
Copyright 2020 New Vector 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 CommonKit
@objcMembers
final class TabBarCoordinator: NSObject, TabBarCoordinatorType {
// MARK: - Properties
// MARK: Private
private let parameters: TabBarCoordinatorParameters
private let activityIndicatorPresenter: ActivityIndicatorPresenterType
private let indicatorPresenter: UserIndicatorTypePresenterProtocol
// Indicate if the Coordinator has started once
private var hasStartedOnce: Bool {
return self.masterTabBarController != nil
}
// TODO: Move MasterTabBarController navigation code here
// and if possible use a simple: `private let tabBarController: UITabBarController`
private var masterTabBarController: MasterTabBarController!
// TODO: Embed UINavigationController in each tab like recommended by Apple and remove these properties. UITabBarViewController shoud not be embed in a UINavigationController (https://github.com/vector-im/riot-ios/issues/3086).
private let navigationRouter: NavigationRouterType
private let masterNavigationController: UINavigationController
private var currentSpaceId: String?
private weak var versionCheckCoordinator: VersionCheckCoordinator?
private var currentMatrixSession: MXSession? {
return parameters.userSessionsService.mainUserSession?.matrixSession
}
private var isTabBarControllerTopMostController: Bool {
return self.navigationRouter.modules.last is MasterTabBarController
}
private var detailUserIndicatorPresenter: UserIndicatorTypePresenterProtocol {
guard let presenter = splitViewMasterPresentableDelegate?.detailUserIndicatorPresenter else {
MXLog.debug("[TabBarCoordinator]: Missing detaul user indicator presenter")
return UserIndicatorTypePresenter(presentingViewController: toPresentable())
}
return presenter
}
private var indicators = [UserIndicator]()
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: TabBarCoordinatorDelegate?
weak var splitViewMasterPresentableDelegate: SplitViewMasterPresentableDelegate?
// MARK: - Setup
init(parameters: TabBarCoordinatorParameters) {
self.parameters = parameters
let masterNavigationController = RiotNavigationController()
self.navigationRouter = NavigationRouter(navigationController: masterNavigationController)
self.masterNavigationController = masterNavigationController
self.activityIndicatorPresenter = ActivityIndicatorPresenter()
self.indicatorPresenter = UserIndicatorTypePresenter(presentingViewController: masterNavigationController)
}
// MARK: - Public methods
func start() {
self.start(with: nil)
}
func start(with spaceId: String?) {
// If start has been done once do not setup view controllers again
if self.hasStartedOnce == false {
let masterTabBarController = self.createMasterTabBarController()
masterTabBarController.masterTabBarDelegate = self
self.masterTabBarController = masterTabBarController
self.navigationRouter.setRootModule(masterTabBarController)
// Add existing Matrix sessions if any
for userSession in self.parameters.userSessionsService.userSessions {
self.addMatrixSessionToMasterTabBarController(userSession.matrixSession)
}
if BuildSettings.enableSideMenu {
self.setupSideMenuGestures()
}
self.registerUserSessionsServiceNotifications()
self.registerSessionChange()
self.updateMasterTabBarController(with: spaceId, forceReload: true)
} else {
self.updateMasterTabBarController(with: spaceId)
}
self.currentSpaceId = spaceId
}
func toPresentable() -> UIViewController {
return self.navigationRouter.toPresentable()
}
func releaseSelectedItems() {
self.masterTabBarController.releaseSelectedItem()
}
func popToHome(animated: Bool, completion: (() -> Void)?) {
// Force back to the main screen if this is not the one that is displayed
if masterTabBarController != masterNavigationController.visibleViewController {
// Listen to the masterNavigationController changes
// We need to be sure that masterTabBarController is back to the screen
let didPopToHome: (() -> Void) = {
// For unknown reason, the navigation bar is not restored correctly by [popToViewController:animated:]
// when a ViewController has hidden it (see MXKAttachmentsViewController).
// Patch: restore navigation bar by default here.
self.masterNavigationController.isNavigationBarHidden = false
// Release the current selected item (room/contact/...).
self.masterTabBarController.releaseSelectedItem()
// Select home tab
self.masterTabBarController.selectTab(at: .home)
completion?()
}
// If MasterTabBarController is not visible because there is a modal above it
// but still the top view controller of navigation controller
if self.isTabBarControllerTopMostController {
didPopToHome()
} else {
// Otherwise MasterTabBarController is not the top controller of the navigation controller
// Waiting for `self.navigationRouter` popping to MasterTabBarController
var token: NSObjectProtocol?
token = NotificationCenter.default.addObserver(forName: NavigationRouter.didPopModule, object: self.navigationRouter, queue: OperationQueue.main) { [weak self] (notification) in
guard let self = self else {
return
}
// If MasterTabBarController is now the top most controller in navigation controller stack call the completion
if self.isTabBarControllerTopMostController {
didPopToHome()
if let token = token {
NotificationCenter.default.removeObserver(token)
}
}
}
// Pop to root view controller
self.navigationRouter.popToRootModule(animated: animated)
}
} else {
// Tab bar controller is already visible
// Select the Home tab
masterTabBarController.selectTab(at: .home)
completion?()
}
}
// MARK: - SplitViewMasterPresentable
var selectedNavigationRouter: NavigationRouterType? {
return self.navigationRouter
}
// MARK: - Private methods
private func createMasterTabBarController() -> MasterTabBarController {
let tabBarController = MasterTabBarController()
if BuildSettings.enableSideMenu {
let sideMenuBarButtonItem: MXKBarButtonItem = MXKBarButtonItem(image: Asset.Images.sideMenuIcon.image, style: .plain) { [weak self] in
self?.showSideMenu()
}
sideMenuBarButtonItem.accessibilityLabel = VectorL10n.sideMenuRevealActionAccessibilityLabel
tabBarController.navigationItem.leftBarButtonItem = sideMenuBarButtonItem
} else {
let settingsBarButtonItem: MXKBarButtonItem = MXKBarButtonItem(image: Asset.Images.settingsIcon.image, style: .plain) { [weak self] in
self?.showSettings()
}
settingsBarButtonItem.accessibilityLabel = VectorL10n.settingsTitle
tabBarController.navigationItem.leftBarButtonItem = settingsBarButtonItem
}
let searchBarButtonItem: MXKBarButtonItem = MXKBarButtonItem(image: Asset.Images.searchIcon.image, style: .plain) { [weak self] in
self?.showUnifiedSearch()
}
searchBarButtonItem.accessibilityLabel = VectorL10n.searchDefaultPlaceholder
tabBarController.navigationItem.rightBarButtonItem = searchBarButtonItem
return tabBarController
}
private func createVersionCheckCoordinator(withRootViewController rootViewController: UIViewController, bannerPresentrer: BannerPresentationProtocol) -> VersionCheckCoordinator {
let versionCheckCoordinator = VersionCheckCoordinator(rootViewController: rootViewController,
bannerPresenter: bannerPresentrer,
themeService: ThemeService.shared())
return versionCheckCoordinator
}
private func createHomeViewController() -> HomeViewControllerWithBannerWrapperViewController {
let homeViewController: HomeViewController = HomeViewController.instantiate()
homeViewController.tabBarItem.tag = Int(TABBAR_HOME_INDEX)
homeViewController.tabBarItem.image = homeViewController.tabBarItem.image
homeViewController.accessibilityLabel = VectorL10n.titleHome
homeViewController.userIndicatorStore = UserIndicatorStore(presenter: indicatorPresenter)
let wrapperViewController = HomeViewControllerWithBannerWrapperViewController(viewController: homeViewController)
return wrapperViewController
}
private func createFavouritesViewController() -> FavouritesViewController {
let favouritesViewController: FavouritesViewController = FavouritesViewController.instantiate()
favouritesViewController.tabBarItem.tag = Int(TABBAR_FAVOURITES_INDEX)
favouritesViewController.accessibilityLabel = VectorL10n.titleFavourites
favouritesViewController.userIndicatorStore = UserIndicatorStore(presenter: indicatorPresenter)
return favouritesViewController
}
private func createPeopleViewController() -> PeopleViewController {
let peopleViewController: PeopleViewController = PeopleViewController.instantiate()
peopleViewController.tabBarItem.tag = Int(TABBAR_PEOPLE_INDEX)
peopleViewController.accessibilityLabel = VectorL10n.titlePeople
peopleViewController.userIndicatorStore = UserIndicatorStore(presenter: indicatorPresenter)
return peopleViewController
}
private func createRoomsViewController() -> RoomsViewController {
let roomsViewController: RoomsViewController = RoomsViewController.instantiate()
roomsViewController.tabBarItem.tag = Int(TABBAR_ROOMS_INDEX)
roomsViewController.accessibilityLabel = VectorL10n.titleRooms
roomsViewController.userIndicatorStore = UserIndicatorStore(presenter: indicatorPresenter)
return roomsViewController
}
private func createGroupsViewController() -> GroupsViewController {
let groupsViewController: GroupsViewController = GroupsViewController.instantiate()
groupsViewController.tabBarItem.tag = Int(TABBAR_GROUPS_INDEX)
groupsViewController.accessibilityLabel = VectorL10n.titleGroups
return groupsViewController
}
private func createUnifiedSearchController() -> UnifiedSearchViewController {
let viewController: UnifiedSearchViewController = UnifiedSearchViewController.instantiate()
viewController.loadViewIfNeeded()
for userSession in self.parameters.userSessionsService.userSessions {
viewController.addMatrixSession(userSession.matrixSession)
}
return viewController
}
private func createSettingsViewController() -> SettingsViewController {
let viewController: SettingsViewController = SettingsViewController.instantiate()
viewController.loadViewIfNeeded()
return viewController
}
private func setupSideMenuGestures() {
let gesture = self.parameters.appNavigator.sideMenu.addScreenEdgePanGesturesToPresent(to: masterTabBarController.view)
gesture.delegate = self
}
private func updateMasterTabBarController(with spaceId: String?, forceReload: Bool = false) {
guard forceReload || spaceId != self.currentSpaceId else { return }
self.updateTabControllers(for: self.masterTabBarController, showCommunities: spaceId == nil)
self.masterTabBarController.filterRooms(withParentId: spaceId, inMatrixSession: self.currentMatrixSession)
}
// TODO: Avoid to reinstantiate controllers everytime
private func updateTabControllers(for tabBarController: MasterTabBarController, showCommunities: Bool) {
var viewControllers: [UIViewController] = []
let homeViewController = self.createHomeViewController()
viewControllers.append(homeViewController)
if let existingVersionCheckCoordinator = self.versionCheckCoordinator {
self.remove(childCoordinator: existingVersionCheckCoordinator)
}
if let masterTabBarController = self.masterTabBarController {
let versionCheckCoordinator = self.createVersionCheckCoordinator(withRootViewController: masterTabBarController, bannerPresentrer: homeViewController)
versionCheckCoordinator.start()
self.add(childCoordinator: versionCheckCoordinator)
self.versionCheckCoordinator = versionCheckCoordinator
}
if RiotSettings.shared.homeScreenShowFavouritesTab {
let favouritesViewController = self.createFavouritesViewController()
viewControllers.append(favouritesViewController)
}
if RiotSettings.shared.homeScreenShowPeopleTab {
let peopleViewController = self.createPeopleViewController()
viewControllers.append(peopleViewController)
}
if RiotSettings.shared.homeScreenShowRoomsTab {
let roomsViewController = self.createRoomsViewController()
viewControllers.append(roomsViewController)
}
if RiotSettings.shared.homeScreenShowCommunitiesTab && !(self.currentMatrixSession?.groups().isEmpty ?? false) && showCommunities {
let groupsViewController = self.createGroupsViewController()
viewControllers.append(groupsViewController)
}
tabBarController.updateViewControllers(viewControllers)
}
// MARK: Navigation
private func showSideMenu() {
self.parameters.appNavigator.sideMenu.show(from: self.masterTabBarController, animated: true)
}
private func dismissSideMenu(animated: Bool) {
self.parameters.appNavigator.sideMenu.dismiss(animated: animated)
}
// FIXME: Should be displayed per tab.
private func showSettings() {
let viewController = self.createSettingsViewController()
self.navigationRouter.push(viewController, animated: true, popCompletion: nil)
}
// FIXME: Should be displayed per tab.
private func showUnifiedSearch() {
let viewController = self.createUnifiedSearchController()
self.navigationRouter.push(viewController, animated: true, popCompletion: nil)
}
// FIXME: Should be displayed from a tab.
private func showContactDetails(with contact: MXKContact, presentationParameters: ScreenPresentationParameters) {
let coordinatorParameters = ContactDetailsCoordinatorParameters(contact: contact)
let coordinator = ContactDetailsCoordinator(parameters: coordinatorParameters)
coordinator.start()
self.add(childCoordinator: coordinator)
self.showSplitViewDetails(with: coordinator, stackedOnSplitViewDetail: presentationParameters.stackAboveVisibleViews) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
// FIXME: Should be displayed from a tab.
private func showGroupDetails(with group: MXGroup, for matrixSession: MXSession, presentationParameters: ScreenPresentationParameters) {
let coordinatorParameters = GroupDetailsCoordinatorParameters(session: matrixSession, group: group)
let coordinator = GroupDetailsCoordinator(parameters: coordinatorParameters)
coordinator.start()
self.add(childCoordinator: coordinator)
self.showSplitViewDetails(with: coordinator, stackedOnSplitViewDetail: presentationParameters.stackAboveVisibleViews) { [weak self] in
self?.remove(childCoordinator: coordinator)
}
}
private func showRoom(withId roomId: String, eventId: String? = nil) {
guard let matrixSession = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
self.showRoom(with: roomId, eventId: eventId, matrixSession: matrixSession)
}
private func showRoom(withNavigationParameters roomNavigationParameters: RoomNavigationParameters, completion: (() -> Void)?) {
if let threadParameters = roomNavigationParameters.threadParameters, threadParameters.stackRoomScreen {
showRoomAndThread(with: roomNavigationParameters,
completion: completion)
} else {
let threadId = roomNavigationParameters.threadParameters?.threadId
let displayConfig: RoomDisplayConfiguration
if threadId != nil {
displayConfig = .forThreads
} else {
displayConfig = .default
}
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
session: roomNavigationParameters.mxSession,
parentSpaceId: self.currentSpaceId,
roomId: roomNavigationParameters.roomId,
eventId: roomNavigationParameters.eventId,
threadId: threadId,
showSettingsInitially: roomNavigationParameters.showSettingsInitially, displayConfiguration: displayConfig)
self.showRoom(with: roomCoordinatorParameters,
stackOnSplitViewDetail: roomNavigationParameters.presentationParameters.stackAboveVisibleViews,
completion: completion)
}
}
private func showRoom(with roomId: String, eventId: String?, matrixSession: MXSession, completion: (() -> Void)? = nil) {
// RoomCoordinator will be presented by the split view.
// As we don't know which navigation controller instance will be used,
// give the NavigationRouterStore instance and let it find the associated navigation controller
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
session: matrixSession,
parentSpaceId: self.currentSpaceId,
roomId: roomId,
eventId: eventId,
showSettingsInitially: false)
self.showRoom(with: roomCoordinatorParameters, completion: completion)
}
private func showRoomPreview(with previewData: RoomPreviewData) {
// RoomCoordinator will be presented by the split view
// We don't which navigation controller instance will be used
// Give the NavigationRouterStore instance and let it find the associated navigation controller if needed
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
parentSpaceId: self.currentSpaceId,
previewData: previewData)
self.showRoom(with: roomCoordinatorParameters)
}
private func showRoomPreview(withNavigationParameters roomPreviewNavigationParameters: RoomPreviewNavigationParameters, completion: (() -> Void)?) {
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
parentSpaceId: self.currentSpaceId,
previewData: roomPreviewNavigationParameters.previewData)
self.showRoom(with: roomCoordinatorParameters,
stackOnSplitViewDetail: roomPreviewNavigationParameters.presentationParameters.stackAboveVisibleViews,
completion: completion)
}
private func showRoom(with parameters: RoomCoordinatorParameters,
stackOnSplitViewDetail: Bool = false,
completion: (() -> Void)? = nil) {
// try to find the desired room screen in the stack
if let roomCoordinator = self.splitViewMasterPresentableDelegate?.detailModules.last(where: { presentable in
guard let roomCoordinator = presentable as? RoomCoordinatorProtocol else {
return false
}
return roomCoordinator.roomId == parameters.roomId
&& roomCoordinator.threadId == parameters.threadId
&& roomCoordinator.mxSession == parameters.session
}) as? RoomCoordinatorProtocol {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentable(self, wantsToPopTo: roomCoordinator)
// go to a specific event if provided
if let eventId = parameters.eventId {
roomCoordinator.start(withEventId: eventId, completion: completion)
} else {
completion?()
}
return
}
let coordinator = RoomCoordinator(parameters: parameters)
coordinator.delegate = self
coordinator.start(withCompletion: completion)
self.add(childCoordinator: coordinator)
self.showSplitViewDetails(with: coordinator, stackedOnSplitViewDetail: stackOnSplitViewDetail) { [weak self] in
// NOTE: The RoomDataSource releasing is handled in SplitViewCoordinator
self?.remove(childCoordinator: coordinator)
}
}
private func showRoomAndThread(with roomNavigationParameters: RoomNavigationParameters,
completion: (() -> Void)? = nil) {
self.activityIndicatorPresenter.presentActivityIndicator(on: toPresentable().view, animated: false)
let dispatchGroup = DispatchGroup()
// create room coordinator
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
session: roomNavigationParameters.mxSession,
parentSpaceId: self.currentSpaceId,
roomId: roomNavigationParameters.roomId,
eventId: nil,
threadId: nil,
showSettingsInitially: false)
dispatchGroup.enter()
let roomCoordinator = RoomCoordinator(parameters: roomCoordinatorParameters)
roomCoordinator.delegate = self
roomCoordinator.start {
dispatchGroup.leave()
}
self.add(childCoordinator: roomCoordinator)
// create thread coordinator
let threadCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
session: roomNavigationParameters.mxSession,
parentSpaceId: self.currentSpaceId,
roomId: roomNavigationParameters.roomId,
eventId: roomNavigationParameters.eventId,
threadId: roomNavigationParameters.threadParameters?.threadId,
showSettingsInitially: false,
displayConfiguration: .forThreads)
dispatchGroup.enter()
let threadCoordinator = RoomCoordinator(parameters: threadCoordinatorParameters)
threadCoordinator.delegate = self
threadCoordinator.start {
dispatchGroup.leave()
}
self.add(childCoordinator: threadCoordinator)
dispatchGroup.notify(queue: .main) { [weak self] in
guard let self = self else { return }
let modules: [NavigationModule] = [
NavigationModule(presentable: roomCoordinator, popCompletion: { [weak self] in
// NOTE: The RoomDataSource releasing is handled in SplitViewCoordinator
self?.remove(childCoordinator: roomCoordinator)
}),
NavigationModule(presentable: threadCoordinator, popCompletion: { [weak self] in
// NOTE: The RoomDataSource releasing is handled in SplitViewCoordinator
self?.remove(childCoordinator: threadCoordinator)
})
]
self.showSplitViewDetails(with: modules,
stack: roomNavigationParameters.presentationParameters.stackAboveVisibleViews)
self.activityIndicatorPresenter.removeCurrentActivityIndicator(animated: true)
}
}
// MARK: Split view
/// If the split view is collapsed (one column visible) it will push the Presentable on the primary navigation controller, otherwise it will show the Presentable as the secondary view of the split view.
private func replaceSplitViewDetails(with presentable: Presentable, popCompletion: (() -> Void)? = nil) {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentable(self, wantsToReplaceDetailWith: presentable, popCompletion: popCompletion)
}
/// If the split view is collapsed (one column visible) it will push the Presentable on the primary navigation controller, otherwise it will show the Presentable as the secondary view of the split view on top of existing views.
private func stackSplitViewDetails(with presentable: Presentable, popCompletion: (() -> Void)? = nil) {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentable(self, wantsToStack: presentable, popCompletion: popCompletion)
}
private func showSplitViewDetails(with presentable: Presentable, stackedOnSplitViewDetail: Bool, popCompletion: (() -> Void)? = nil) {
if stackedOnSplitViewDetail {
self.stackSplitViewDetails(with: presentable, popCompletion: popCompletion)
} else {
self.replaceSplitViewDetails(with: presentable, popCompletion: popCompletion)
}
}
private func showSplitViewDetails(with modules: [NavigationModule], stack: Bool) {
if stack {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentable(self, wantsToStack: modules)
} else {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentable(self, wantsToReplaceDetailsWith: modules)
}
}
private func resetSplitViewDetails() {
self.splitViewMasterPresentableDelegate?.splitViewMasterPresentableWantsToResetDetail(self)
}
// MARK: UserSessions management
private func registerUserSessionsServiceNotifications() {
// Listen only notifications from the current UserSessionsService instance
let userSessionService = self.parameters.userSessionsService
NotificationCenter.default.addObserver(self, selector: #selector(userSessionsServiceDidAddUserSession(_:)), name: UserSessionsService.didAddUserSession, object: userSessionService)
NotificationCenter.default.addObserver(self, selector: #selector(userSessionsServiceWillRemoveUserSession(_:)), name: UserSessionsService.willRemoveUserSession, object: userSessionService)
}
@objc private func userSessionsServiceDidAddUserSession(_ notification: Notification) {
guard let userSession = notification.userInfo?[UserSessionsService.NotificationUserInfoKey.userSession] as? UserSession else {
return
}
self.addMatrixSessionToMasterTabBarController(userSession.matrixSession)
if let matrixSession = self.currentMatrixSession, matrixSession.groups().isEmpty {
self.masterTabBarController.removeTab(at: .groups)
}
}
@objc private func userSessionsServiceWillRemoveUserSession(_ notification: Notification) {
guard let userSession = notification.userInfo?[UserSessionsService.NotificationUserInfoKey.userSession] as? UserSession else {
return
}
self.removeMatrixSessionFromMasterTabBarController(userSession.matrixSession)
}
// TODO: Remove Matrix session handling from the view controller
private func addMatrixSessionToMasterTabBarController(_ matrixSession: MXSession) {
MXLog.debug("[TabBarCoordinator] masterTabBarController.addMatrixSession")
self.masterTabBarController.addMatrixSession(matrixSession)
}
// TODO: Remove Matrix session handling from the view controller
private func removeMatrixSessionFromMasterTabBarController(_ matrixSession: MXSession) {
MXLog.debug("[TabBarCoordinator] masterTabBarController.removeMatrixSession")
self.masterTabBarController.removeMatrixSession(matrixSession)
}
private func registerSessionChange() {
NotificationCenter.default.addObserver(self, selector: #selector(sessionDidSync(_:)), name: NSNotification.Name.mxSessionDidSync, object: nil)
}
@objc private func sessionDidSync(_ notification: Notification) {
if self.currentMatrixSession?.groups().isEmpty ?? true {
self.masterTabBarController.removeTab(at: .groups)
}
if let session = notification.object as? MXSession {
showCoachMessageIfNeeded(with: session)
}
}
// MARK: Coach Message
private var windowOverlay: WindowOverlayPresenter?
func showCoachMessageIfNeeded(with session: MXSession) {
if !RiotSettings.shared.slideMenuRoomsCoachMessageHasBeenDisplayed {
let isAuthenticated = MXKAccountManager.shared().activeAccounts.first != nil || MXKAccountManager.shared().accounts.first?.isSoftLogout == false
if isAuthenticated, let spaceService = session.spaceService, masterTabBarController.presentedViewController == nil, navigationRouter.modules.count == 1 {
if spaceService.isInitialised && !spaceService.rootSpaceSummaries.isEmpty {
RiotSettings.shared.slideMenuRoomsCoachMessageHasBeenDisplayed = true
windowOverlay = WindowOverlayPresenter()
let coachMarkView = CoachMarkView.instantiate(
text: VectorL10n.sideMenuCoachMessage,
from: CoachMarkView.TopLeftPosition,
markPosition: .topLeft)
windowOverlay?.show(coachMarkView, duration: 4.0)
}
}
}
}
}
// MARK: - MasterTabBarControllerDelegate
extension TabBarCoordinator: MasterTabBarControllerDelegate {
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, didSelectRoomWith roomNavigationParameters: RoomNavigationParameters!, completion: (() -> Void)!) {
self.showRoom(withNavigationParameters: roomNavigationParameters, completion: completion)
}
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, didSelectRoomPreviewWith roomPreviewScreenParameters: RoomPreviewNavigationParameters!, completion: (() -> Void)!) {
self.showRoomPreview(withNavigationParameters: roomPreviewScreenParameters, completion: completion)
}
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, didSelect contact: MXKContact!, with presentationParameters: ScreenPresentationParameters!) {
self.showContactDetails(with: contact, presentationParameters: presentationParameters)
}
func masterTabBarControllerDidCompleteAuthentication(_ masterTabBarController: MasterTabBarController!) {
self.delegate?.tabBarCoordinatorDidCompleteAuthentication(self)
}
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, didSelectRoomWithId roomId: String!, andEventId eventId: String!, inMatrixSession matrixSession: MXSession!, completion: (() -> Void)!) {
self.showRoom(with: roomId, eventId: eventId, matrixSession: matrixSession, completion: completion)
}
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, didSelect group: MXGroup!, inMatrixSession matrixSession: MXSession!, presentationParameters: ScreenPresentationParameters!) {
self.showGroupDetails(with: group, for: matrixSession, presentationParameters: presentationParameters)
}
func masterTabBarController(_ masterTabBarController: MasterTabBarController!, needsSideMenuIconWithNotification displayNotification: Bool) {
let image = displayNotification ? Asset.Images.sideMenuNotifIcon.image : Asset.Images.sideMenuIcon.image
let sideMenuBarButtonItem: MXKBarButtonItem = MXKBarButtonItem(image: image, style: .plain) { [weak self] in
self?.showSideMenu()
}
sideMenuBarButtonItem.accessibilityLabel = VectorL10n.sideMenuRevealActionAccessibilityLabel
self.masterTabBarController.navigationItem.leftBarButtonItem = sideMenuBarButtonItem
}
}
// MARK: - RoomCoordinatorDelegate
extension TabBarCoordinator: RoomCoordinatorDelegate {
func roomCoordinatorDidDismissInteractively(_ coordinator: RoomCoordinatorProtocol) {
self.remove(childCoordinator: coordinator)
}
func roomCoordinatorDidLeaveRoom(_ coordinator: RoomCoordinatorProtocol) {
// For the moment when a room is left, reset the split detail with placeholder
self.resetSplitViewDetails()
indicatorPresenter
.present(.success(label: VectorL10n.roomParticipantsLeaveSuccess))
.store(in: &indicators)
}
func roomCoordinatorDidCancelRoomPreview(_ coordinator: RoomCoordinatorProtocol) {
self.navigationRouter.popModule(animated: true)
}
func roomCoordinator(_ coordinator: RoomCoordinatorProtocol, didSelectRoomWithId roomId: String, eventId: String?) {
self.showRoom(withId: roomId, eventId: eventId)
}
func roomCoordinator(_ coordinator: RoomCoordinatorProtocol, didReplaceRoomWithReplacementId roomId: String) {
guard let matrixSession = self.parameters.userSessionsService.mainUserSession?.matrixSession else {
return
}
let roomCoordinatorParameters = RoomCoordinatorParameters(navigationRouterStore: NavigationRouterStore.shared,
userIndicatorPresenter: detailUserIndicatorPresenter,
session: matrixSession,
parentSpaceId: self.currentSpaceId,
roomId: roomId,
eventId: nil,
showSettingsInitially: true)
self.showRoom(with: roomCoordinatorParameters,
stackOnSplitViewDetail: false)
}
}
// MARK: - UIGestureRecognizerDelegate
/**
Prevent the side menu gesture from clashing with other gestures like the home screen horizontal scroll views.
Also make sure that it doesn't cancel out UINavigationController backwards swiping
*/
extension TabBarCoordinator: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer.isKind(of: UIScreenEdgePanGestureRecognizer.self) {
return false
} else {
return true
}
}
}
| apache-2.0 | ab5c3b95e8e5fa671fe6cb48f2ec04e0 | 49.200252 | 231 | 0.654005 | 7.039739 | false | false | false | false |
jefflovejapan/CIFilterKit | CIFilterKit/HalftoneEffectFilters.swift | 1 | 2649 | //
// HalftoneEffectFilters.swift
// CIFilterKit
//
// Created by Jeffrey Blagdon on 5/28/15.
// Copyright (c) 2015 Jeffrey Blagdon. All rights reserved.
//
import Foundation
/**
- parameter options: An instance of `CircularScreenOptions`
- returns: A closure of type `Filter`
*/
public func CircularScreen(options: CircularScreenOptions) -> Filter {
return { image in
let parameters = [
kCIInputImageKey: image,
kCIInputCenterKey: options.inputCenter.vector(),
kCIInputWidthKey: options.inputWidth,
kCIInputSharpnessKey: options.inputSharpness
]
let filter = CIFilter(name: FilterName.CircularScreen.rawValue, withInputParameters: parameters)
return filter?.outputImage
}
}
/**
- parameter options: An instance of `DotScreenOptions`
- returns: A closure of type `Filter`
*/
public func DotScreen(options: DotScreenOptions) -> Filter {
return { image in
let parameters = [
kCIInputImageKey: image,
kCIInputCenterKey: options.inputCenter.vector(),
kCIInputAngleKey: options.inputAngle,
kCIInputWidthKey: options.inputWidth,
kCIInputSharpnessKey: options.inputSharpness
]
let filter = CIFilter(name: FilterName.DotScreen.rawValue, withInputParameters: parameters)
return filter?.outputImage
}
}
/**
- parameter options: An instance of `HatchedScreenOptions`
- returns: A closure of type `Filter`
*/
public func HatchedScreen(options: HatchedScreenOptions) -> Filter {
return { image in
let parameters = [
kCIInputImageKey: image,
kCIInputCenterKey: options.inputCenter.vector(),
kCIInputAngleKey: options.inputAngle,
kCIInputWidthKey: options.inputWidth,
kCIInputSharpnessKey: options.inputSharpness
]
let filter = CIFilter(name: FilterName.HatchedScreen.rawValue, withInputParameters: parameters)
return filter?.outputImage
}
}
/**
- parameter options: An instance of `LineScreenOptions`
- returns: A closure of type `Filter`
*/
public func LineScreen(options: LineScreenOptions) -> Filter {
return { image in
let parameters = [
kCIInputImageKey: image,
kCIInputCenterKey: options.inputCenter.vector(),
kCIInputAngleKey: options.inputAngle,
kCIInputWidthKey: options.inputWidth,
kCIInputSharpnessKey: options.inputSharpness
]
let filter = CIFilter(name: FilterName.LineScreen.rawValue, withInputParameters: parameters)
return filter?.outputImage
}
} | mit | 5f752650b866d4db9f4459fea9602f34 | 30.547619 | 104 | 0.676104 | 4.979323 | false | false | false | false |
MaxKramer/SwiftLuhn | Example/SwiftLuhn/ViewController.swift | 1 | 1318 | //
// ViewController.swift
// SwiftLuhn
//
// Created by Max Kramer on 03/29/2016.
// Copyright (c) 2016 Max Kramer. All rights reserved.
//
import UIKit
import SwiftLuhn
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var cardTextField: UITextField!
@IBOutlet weak var validityLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
cardTextField.text = "378282246310005"
updateLabel(cardTextField.text!.isValidCardNumber())
// Do any additional setup after loading the view, typically from a nib.
}
func updateLabel(_ isValid: Bool) {
if isValid {
validityLabel.text = "VALID"
validityLabel.textColor = UIColor.green
}
else {
validityLabel.text = "INVALID"
validityLabel.textColor = UIColor.red
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let updatedString = text.replacingCharacters(in: range, with: string)
let isValid = updatedString.isValidCardNumber()
updateLabel(isValid)
return true
}
}
| mit | e3a4181f3218250196e3f2750fd6d248 | 27.042553 | 129 | 0.628983 | 4.973585 | false | false | false | false |
bryancmiller/rockandmarty | Text Adventure/Text Adventure/TextViewController.swift | 1 | 4030 | //
// TextViewController.swift
// Text Adventure
//
// Created by Bryan Miller on 5/1/17.
// Copyright © 2017 Bryan Miller. All rights reserved.
//
import UIKit
let kTextButtonWidth: CGFloat = 237.0
let kTextButtonHeight: CGFloat = 47.0
let kLeftTextMargin: CGFloat = 12.0
let kRightTextMargin: CGFloat = 12.0
let kNavBarToFirst: CGFloat = 38.0
let kFirstToSecond: CGFloat = 24.0
let kSecondToThird: CGFloat = 24.0
let kThirdToFourth: CGFloat = 24.0
let kFourthToBegin: CGFloat = 24.0
class TextViewController: UIViewController {
@IBOutlet weak var firstTextLabel: UILabel!
@IBOutlet weak var secondTextLabel: UILabel!
@IBOutlet weak var thirdTextLabel: UILabel!
@IBOutlet weak var fourthTextLabel: UILabel!
@IBOutlet weak var beginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if let navigationBar = navigationController?.navigationBar {
self.navigationItem.title = "Prelude"
navigationBar.setCustomStyle()
}
beginButton.layer.cornerRadius = 5
beginButton.clipsToBounds = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenSize = self.view.bounds
let width = screenSize.width
let height = screenSize.height
let adjustedSize = CGSize(width: width - (kLeftTextMargin + kRightTextMargin), height: height)
if let navigationBar = navigationController?.navigationBar {
let navBarHeight = navigationBar.getHeight()
let goodFirstSize = firstTextLabel.sizeThatFits(adjustedSize)
firstTextLabel.frame = CGRect(x: kLeftTextMargin,
y: navBarHeight + CGFloat.convertHeight(h: kNavBarToFirst, screenSize: screenSize),
width: adjustedSize.width,
height: goodFirstSize.height)
let goodSecondSize = secondTextLabel.sizeThatFits(adjustedSize)
secondTextLabel.frame = CGRect(x: kLeftTextMargin,
y: firstTextLabel.frame.maxY + CGFloat.convertHeight(h: kFirstToSecond, screenSize: screenSize),
width: adjustedSize.width,
height: goodSecondSize.height)
let goodThirdSize = thirdTextLabel.sizeThatFits(adjustedSize)
thirdTextLabel.frame = CGRect(x: kLeftTextMargin,
y: secondTextLabel.frame.maxY + CGFloat.convertHeight(h: kSecondToThird, screenSize: screenSize),
width: adjustedSize.width,
height: goodThirdSize.height)
let goodFourthSize = fourthTextLabel.sizeThatFits(adjustedSize)
fourthTextLabel.frame = CGRect(x: kLeftTextMargin,
y: thirdTextLabel.frame.maxY + CGFloat.convertHeight(h: kThirdToFourth, screenSize: screenSize),
width: adjustedSize.width,
height: goodFourthSize.height)
let newPossibleButtonWidth = self.view.bounds.width * 0.7
let buttonWidth = (kTextButtonWidth <= newPossibleButtonWidth) ? kTextButtonWidth : newPossibleButtonWidth
beginButton.frame = CGRect(x: width/2 - buttonWidth/2,
y: fourthTextLabel.frame.maxY + CGFloat.convertHeight(h: kFourthToBegin, screenSize: screenSize),
width: buttonWidth,
height: kTextButtonHeight)
}
}
}
| apache-2.0 | 664ad23fb39de53833625314d01d6c0a | 40.96875 | 140 | 0.596674 | 5.45935 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift | 1 | 3763 | //
// Take.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// count version
final class TakeCountSink<O: ObserverType>: Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = TakeCount<E>
private let _parent: Parent
private var _remaining: Int
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_remaining = parent._count
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case let .next(value):
if _remaining > 0 {
_remaining -= 1
forwardOn(.next(value))
if _remaining == 0 {
forwardOn(.completed)
dispose()
}
}
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
}
final class TakeCount<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
_source = source
_count = count
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
// time version
final class TakeTimeSink<ElementType, O: ObserverType>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType where O.E == ElementType {
typealias Parent = TakeTime<ElementType>
typealias E = ElementType
fileprivate let _parent: Parent
let _lock = RecursiveLock()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case let .next(value):
forwardOn(.next(value))
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
func tick() {
_lock.lock(); defer { _lock.unlock() }
forwardOn(.completed)
dispose()
}
func run() -> Disposable {
let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) {
self.tick()
return Disposables.create()
}
let disposeSubscription = _parent._source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
final class TakeTime<Element>: Producer<Element> {
typealias TimeInterval = RxTimeInterval
fileprivate let _source: Observable<Element>
fileprivate let _duration: TimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) {
_source = source
_scheduler = scheduler
_duration = duration
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | d106dcb7ae94d76215f4c8fa48d06f88 | 25.680851 | 144 | 0.594631 | 4.587805 | false | false | false | false |
ngageoint/mage-ios | Mage/NumberBadge.swift | 1 | 2376 | //
// NumberBadge.swift
// MAGE
//
// Created by Daniel Barela on 5/11/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import UIKit
class NumberBadge: UIView {
var labelWidth: NSLayoutConstraint?
var labelHeight: NSLayoutConstraint?
var didSetupConstraints = false
var badgeTintColor: UIColor = .systemRed
var textColor: UIColor = .white
var showsZero: Bool = false
var _number: Int = 0
var number: Int {
get {
return _number
}
set {
_number = newValue
updateLabel()
}
}
let label = UILabel.newAutoLayout()
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
init(number: Int, showsZero: Bool = false, tintColor: UIColor = .systemRed, textColor: UIColor = .white) {
super.init(frame: CGRect.zero);
self.configureForAutoLayout();
addSubview(label)
self.badgeTintColor = tintColor
self.showsZero = showsZero
self.number = number
}
func updateLabel() {
label.text = String(describing:number)
label.isHidden = !showsZero && number == 0
label.clipsToBounds = true
label.backgroundColor = badgeTintColor
label.textColor = textColor
label.textAlignment = .center
label.accessibilityLabel = "Badge \(label.text ?? "")"
setNeedsUpdateConstraints()
}
override func updateConstraints() {
let fontSize = label.font.pointSize
let textSize = (label.text as? NSString)?.size(withAttributes: [.font : label.font ?? .systemFont(ofSize: 10)]) ?? .zero
if !didSetupConstraints {
self.label.autoPinEdgesToSuperviewEdges()
self.labelWidth = label.autoSetDimension(.width, toSize: 0)
self.labelHeight = label.autoSetDimension(.height, toSize: 0)
}
didSetupConstraints = true
self.labelHeight?.constant = (0.4 * fontSize) + textSize.height
self.labelWidth?.constant = number <= 9 ? (self.labelHeight?.constant ?? 0) : textSize.width + fontSize
label.layer.cornerRadius = (self.labelHeight?.constant ?? 0.0) / 2.0
super.updateConstraints()
}
}
| apache-2.0 | c410a5fef04723271e568672da7f1a14 | 29.844156 | 128 | 0.613474 | 4.876797 | false | false | false | false |
michals92/iOS_skautIS | skautIS/Request.swift | 1 | 5907 | //
// Request.swift
// skautIS
//
// Copyright (c) 2015, Michal Simik
// All rights reserved.
//
import UIKit
import IJReachability
import SystemConfiguration
import SWXMLHash
class Request: NSObject, NSURLConnectionDelegate{
//variables
var answerString : String?
var request: String?
var urlString : String?
var storage = Storage()
var mutableData:NSMutableData = NSMutableData.alloc()
var currentElementName:NSString = ""
//initialization method
init(request: String, urlString: NSString) {
self.request = request
self.urlString = urlString as String
}
/**
Get answer of web service.
@param viewController sender VC
@return string of web service
*/
func getAnswer(viewController : UIViewController) -> String{
//check for internet connection
if !isConnectedToNetwork() {
var alertTitle = "Nic nenalezeno"
var message = "Problém s připojením."
var okText = "Rozumím"
let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okButton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okButton)
viewController.presentViewController(alert, animated: true, completion: nil)
return ""
} else {
//test login to skautis
var isLogged:Bool = refreshLogin()
//if is user logged, return string, else return nil
if isLogged == true {
answerString = returnString(request!, urlString2: urlString!)
return answerString!
} else {
println("Jsi odhlášen")
var login = storage.loader("login")
let urlPath: String = "http://test-is.skaut.cz/Login/LogOut.aspx?AppID=05149177-a1c4-4ba6-85e4-24840386efc4&Token=\(login)"
var url: NSURL = NSURL(string: urlPath)!
let request = NSURLRequest(URL: url)
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
var vc = viewController.storyboard!.instantiateViewControllerWithIdentifier("loginVC") as! LoginVC
viewController.presentViewController(vc, animated: true, completion: nil)
return ""
}
}
}
/**
Find out if device is connected to internet
@return is connected
*/
func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
/**
Login Refresh.
@return if is user logged
*/
func refreshLogin() -> Bool {
var login = storage.loader("login")
var urlString = "http://test-is.skaut.cz/JunakWebservice/UserManagement.asmx"
var loginUpdateRefresh = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><LoginUpdateRefresh xmlns=\"https://is.skaut.cz/\"><loginUpdateRefreshInput><ID>\(login)</ID></loginUpdateRefreshInput></LoginUpdateRefresh></soap:Body></soap:Envelope>"
var result = returnString(loginUpdateRefresh, urlString2: urlString)
var xml = SWXMLHash.parse(result)
if (xml["soap:Envelope"]["soap:Body"]["LoginUpdateRefreshResponse"]["LoginUpdateRefreshResult"]["DateLogout"]){
//println(xml["soap:Envelope"]["soap:Body"]["LoginUpdateRefreshResponse"]["LoginUpdateRefreshResult"]["DateLogout"].element!.text!)
return true
} else {
return false
}
}
/**
Get string of web service answer.
@param request2 string of XML request
@param urlString2 string of web address
@return string of web service
*/
func returnString(request2: String,urlString2: String) -> String {
var url = NSURL(string: urlString2)
var theRequest = NSMutableURLRequest(URL: url!)
var msgLength = String(count(request2))
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = request2.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var error: NSErrorPointer = nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(theRequest, returningResponse: response, error:nil)!
var err: NSError
var answer = NSString(data: dataVal, encoding: NSUTF8StringEncoding) as? String
return answer!
}
}
| bsd-3-clause | 10b4877575703b0ecbe7412854856d9a | 35.88125 | 431 | 0.622437 | 4.905237 | false | false | false | false |
solium/swift-react-native-hybrid | ios/SwiftReactNativeHybrid/NativeModules/NativeModuleJavaScriptCallback.swift | 1 | 1226 | //
// NativeModuleJavaScriptCallback.swift
// SwiftReactNativeHybrid
//
// Created by Jeremy Gale on 2017-06-13.
// Copyright © 2017 Solium Capital Inc. All rights reserved.
//
import Foundation
import React
@objc(NativeModuleJavaScriptCallback)
class NativeModuleJavaScriptCallback: NSObject {
// This key must match the value used in JavaScript
static let swiftButtonEnabledKey = "swiftButtonEnabled"
func toggleSwiftButtonEnabled( _ callback: @escaping RCTResponseSenderBlock) {
// You won't be on the main thread when called from JavaScript
DispatchQueue.main.async {
guard let tabBarController = UIApplication.shared.keyWindow?.rootViewController as? TabBarController,
let firstViewController = tabBarController.viewControllers?.first as? FirstViewController else {
return
}
let newEnabledState = !firstViewController.incrementButton.isEnabled
firstViewController.incrementButton.isEnabled = newEnabledState
let callbackInfo = [NativeModuleJavaScriptCallback.swiftButtonEnabledKey: newEnabledState]
callback([callbackInfo])
}
}
}
| mit | 6abfe236d83d368bae0954ec5341947c | 36.121212 | 113 | 0.699592 | 5.518018 | false | false | false | false |
dcutting/song | Tests/SongTests/Interpreter/ContextTests.swift | 1 | 2898 | import XCTest
@testable import Song
class ContextTests: XCTestCase {
func test_isEqual_empty_returnsTrue() {
let left = Context()
let right = Context()
XCTAssertTrue(Song.isEqual(lhsContext: left, rhsContext: right))
}
func test_isEqual_simple_same_returnsTrue() {
let left: Context = ["a": .string("hi"), "b": .yes]
let right: Context = ["a": .string("hi"), "b": .yes]
XCTAssertTrue(Song.isEqual(lhsContext: left, rhsContext: right))
}
func test_isEqual_simple_different_returnsFalse() {
let left: Context = ["a": .string("hi")]
let right: Context = ["a": .string("bye")]
XCTAssertFalse(Song.isEqual(lhsContext: left, rhsContext: right))
}
func test_isEqual_simple_differentKeys_returnsFalse() {
let left: Context = ["a": .int(4)]
let right: Context = ["b": .int(4)]
XCTAssertFalse(Song.isEqual(lhsContext: left, rhsContext: right))
}
func test_call_contextsAreNotDynamicallyScoped() {
let foo = Function(name: "foo", patterns: [], when: .yes, body: .name("n"))
let bar = Function(name: "bar", patterns: [.name("n")], when: .yes, body: .call("foo", []))
let context = try! declareSubfunctions([foo, bar])
let call = Expression.call("bar", [.int(5)])
XCTAssertThrowsError(try call.evaluate(context: context))
}
func test_scopeCall_tailCallHasLexicalScope() {
let foo = Function(name: "foo", patterns: [], when: .yes, body: .name("n"))
let context = try! declareSubfunctions([foo])
let scope = Expression.scope([.assign(variable: .name("n"), value: .int(5)), .call("foo", [])])
XCTAssertThrowsError(try scope.evaluate(context: extend(context: rootContext, with: context)))
}
func test_scopeCall_middleCallHasLexicalScope() {
let foo = Function(name: "foo", patterns: [], when: .yes, body: .name("n"))
let context = try! declareSubfunctions([foo])
let scope = Expression.scope([.assign(variable: .name("n"), value: .int(5)), .call("foo", []), .yes])
XCTAssertThrowsError(try scope.evaluate(context: extend(context: rootContext, with: context)))
}
func test_call_globalsDefinedLaterAreAccessible() {
assertNoThrow {
let foo = Function(name: "foo", patterns: [], when: .yes, body: .name("n"))
var context = try declareSubfunctions([foo])
context = extendContext(context: context, name: "n", value: .int(5))
let call = Expression.call("foo", [])
XCTAssertEqual(Expression.int(5), try call.evaluate(context: context))
}
}
func test_describeContext() {
let context: Context = ["foo": .int(5), "bar": .yes]
let actual = describeContext(context)
let expected = "bar: Yes, foo: 5"
XCTAssertEqual(expected, actual)
}
}
| mit | 091e7cd45ce770bd10d2028c9717c826 | 41.617647 | 109 | 0.610076 | 3.889933 | false | true | false | false |
nethergrim/xpolo | XPolo/Pods/BFKit-Swift/Sources/BFKit/Apple/UIKit/UILabelExtension.swift | 1 | 4535 | //
// UILabelExtension.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. 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 Foundation
import UIKit
// MARK: - UILabel extension
/// This extesion adds some useful functions to UILabel.
public extension UILabel {
// MARK: - Functions
/// Create an UILabel with the given parameters.
///
/// - Parameters:
/// - frame: Label frame.
/// - text: Label text.
/// - font: Label font.
/// - color: Label text color.
/// - alignment: Label text alignment.
/// - lines: Label text lines.
/// - shadowColor: Label text shadow color.
public convenience init(frame: CGRect, text: String, font: UIFont, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clear) {
self.init(frame: frame)
self.font = font
self.text = text
self.backgroundColor = UIColor.clear
self.textColor = color
self.textAlignment = alignment
self.numberOfLines = lines
self.shadowColor = shadowColor
}
/// Create an UILabel with the given parameters.
///
/// - Parameters:
/// - frame: Label frame.
/// - text: Label text.
/// - font: Label font name.
/// - size: Label font size.
/// - color: Label text color.
/// - alignment: Label text alignment.
/// - lines: Label text lines.
/// - shadowColor: Label text shadow color.
public convenience init(frame: CGRect, text: String, font: FontName, fontSize: CGFloat, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clear) {
self.init(frame: frame)
self.font = UIFont(fontName: font, size: fontSize)
self.text = text
self.backgroundColor = UIColor.clear
self.textColor = color
self.textAlignment = alignment
self.numberOfLines = lines
self.shadowColor = shadowColor
}
/// Calculates height based on text, width and font.
///
/// - Returns: Returns calculated height.
public func calculateHeight() -> CGFloat {
let text: String = self.text!
return UIFont.calculateHeight(width: self.frame.size.width, font: self.font, text: text)
}
/// Sets a custom font from a character at an index to character at another index.
///
/// - Parameters:
/// - font: New font to be setted.
/// - fromIndex: The start index.
/// - toIndex: The end index.
public func setFont(_ font: UIFont, fromIndex: Int, toIndex: Int) {
guard let text = self.text else {
return
}
self.attributedText = text.attributedString.font(font, range: NSRange(location: fromIndex, length: toIndex - fromIndex))
}
/// Sets a custom font from a character at an index to character at another index.
///
/// - Parameters:
/// - font: New font to be setted.
/// - fontSize: New font size.
/// - fromIndex: The start index.
/// - toIndex: The end index.
public func setFont(_ font: FontName, fontSize: CGFloat, fromIndex: Int, toIndex: Int) {
guard let text = self.text else {
return
}
self.attributedText = text.attributedString.font(UIFont(fontName: font, size: fontSize), range: NSRange(location: fromIndex, length: toIndex - fromIndex))
}
}
| gpl-3.0 | 9fbb1ead3151a10f1f192033a337d567 | 38.434783 | 187 | 0.646748 | 4.38588 | false | false | false | false |
dduan/swift | test/Constraints/associated_self_types.swift | 1 | 1189 | // RUN: %target-parse-verify-swift
protocol MyIteratorProtocol {
associatedtype Element
func next() -> Element?
}
protocol MySequence {
associatedtype Iterator : MyIteratorProtocol
}
protocol MyCollection : MySequence {
var startIndex: Iterator { get }
}
protocol P : MyCollection {
init()
}
postfix operator ~>> {}
postfix func ~>> <_Self : MySequence, A : P where _Self.Iterator.Element == A.Iterator.Element>(_:_Self) -> A {
return A()
}
protocol _ExtendedSequence : MySequence {
postfix func ~>> <A : P where Self.Iterator.Element == A.Iterator.Element>(s: Self) -> A
}
struct MyRangeIterator<T> : MyIteratorProtocol {
func next() -> T? { return nil }
}
struct MyRange<T> : _ExtendedSequence {
typealias Element = T
typealias Iterator = MyRangeIterator<T>
}
protocol Q : MySequence {
func f<QS : MySequence where QS.Iterator.Element == Self.Iterator.Element>(x: QS)
}
struct No<NT> : MyIteratorProtocol {
func next() -> NT? {
return .none
}
}
class X<XT> : Q {
typealias Iterator = No<XT>
func f<SX : MySequence where SX.Iterator.Element == X.Iterator.Element>(x: SX) {
}
func makeIterator() -> No<XT> {
return No<XT>()
}
}
| apache-2.0 | c875cfbf2c26b546e6040402d30584c3 | 19.859649 | 111 | 0.668629 | 3.52819 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGeneratorTests/XcodeProjectGeneratorTests.swift | 1 | 25389 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TulsiGenerator
class XcodeProjectGeneratorTests: XCTestCase {
static let outputFolderPath = "/dev/null/project"
static let projectName = "ProjectName"
let outputFolderURL = URL(fileURLWithPath: XcodeProjectGeneratorTests.outputFolderPath)
let xcodeProjectPath
= "\(XcodeProjectGeneratorTests.outputFolderPath)/\(XcodeProjectGeneratorTests.projectName).xcodeproj"
let workspaceRoot = URL(fileURLWithPath: "/workspace")
let testTulsiVersion = "9.99.999.9999"
let buildTargetLabels = ["//test:MainTarget", "//test/path/to/target:target"].map({
BuildLabel($0)
})
let pathFilters = Set<String>(["test", "additional"])
let additionalFilePaths = ["additional/File1", "additional/File2"]
let bazelURL = TulsiParameter(
value: URL(fileURLWithPath: "/test/dir/testBazel"),
source: .explicitlyProvided)
let resourceURLs = XcodeProjectGenerator.ResourceSourcePathURLs(
buildScript: URL(fileURLWithPath: "/scripts/Build"),
resignerScript: URL(fileURLWithPath: "/scripts/Resigner"),
cleanScript: URL(fileURLWithPath: "/scripts/Clean"),
extraBuildScripts: [URL(fileURLWithPath: "/scripts/Logging")],
iOSUIRunnerEntitlements: URL(
fileURLWithPath: "/generatedProjectResources/iOSXCTRunner.entitlements"),
macOSUIRunnerEntitlements: URL(
fileURLWithPath: "/generatedProjectResources/macOSXCTRunner.entitlements"),
stubInfoPlist: URL(fileURLWithPath: "/generatedProjectResources/StubInfoPlist.plist"),
stubIOSAppExInfoPlistTemplate: URL(
fileURLWithPath: "/generatedProjectResources/stubIOSAppExInfoPlist.plist"),
stubWatchOS2InfoPlist: URL(
fileURLWithPath: "/generatedProjectResources/StubWatchOS2InfoPlist.plist"),
stubWatchOS2AppExInfoPlist: URL(
fileURLWithPath: "/generatedProjectResources/StubWatchOS2AppExInfoPlist.plist"),
stubClang: URL(fileURLWithPath: "/generatedProjectResources/stub_clang"),
stubSwiftc: URL(fileURLWithPath: "/generatedProjectResources/stub_swiftc"),
stubLd: URL(fileURLWithPath: "/generatedProjectResources/stub_ld"),
bazelWorkspaceFile: URL(fileURLWithPath: "/WORKSPACE"),
tulsiPackageFiles: [URL(fileURLWithPath: "/tulsi/tulsi_aspects.bzl")])
var config: TulsiGeneratorConfig! = nil
var mockLocalizedMessageLogger: MockLocalizedMessageLogger! = nil
var mockFileManager: MockFileManager! = nil
var mockExtractor: MockWorkspaceInfoExtractor! = nil
var generator: XcodeProjectGenerator! = nil
var writtenFiles = Set<String>()
override func setUp() {
super.setUp()
mockLocalizedMessageLogger = MockLocalizedMessageLogger()
mockFileManager = MockFileManager()
mockExtractor = MockWorkspaceInfoExtractor()
writtenFiles.removeAll()
}
func testSuccessfulGeneration() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.pbxproj"))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings"))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/project.xcworkspace/xcuserdata/USER.xcuserdatad/WorkspaceSettings.xcsettings"
))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/xcshareddata/xcschemes/test-path-to-target-target.xcscheme"))
XCTAssert(
writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-MainTarget.xcscheme")
)
let supportScriptsURL = mockFileManager.homeDirectoryForCurrentUser.appendingPathComponent(
"Library/Application Support/Tulsi/Scripts", isDirectory: true)
XCTAssert(mockFileManager.directoryOperations.contains(supportScriptsURL.path))
let cacheReaderURL = supportScriptsURL.appendingPathComponent(
"bazel_cache_reader",
isDirectory: false)
XCTAssertFalse(mockFileManager.copyOperations.keys.contains(cacheReaderURL.path))
let xcp = "\(xcodeProjectPath)/xcuserdata/USER.xcuserdatad/xcschemes/xcschememanagement.plist"
XCTAssert(!mockFileManager.attributesMap.isEmpty)
mockFileManager.attributesMap.forEach { (path, attrs) in
XCTAssertNotNil(attrs[.modificationDate])
}
XCTAssert(mockFileManager.writeOperations.keys.contains(xcp))
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testSuccessfulGenerationWithBazelCacheReader() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
let options = TulsiOptionSet()
options[.UseBazelCacheReader].projectValue = "YES"
prepareGenerator(ruleEntries, options: options)
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
let cacheReaderURL = mockFileManager.homeDirectoryForCurrentUser.appendingPathComponent(
"Library/Application Support/Tulsi/Scripts/bazel_cache_reader", isDirectory: false)
XCTAssert(mockFileManager.copyOperations.keys.contains(cacheReaderURL.path))
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testExtensionPlistGeneration() {
@discardableResult
func addRule(
_ labelName: String,
type: String,
attributes: [String: AnyObject] = [:],
weakDependencies: Set<BuildLabel>? = nil,
extensions: Set<BuildLabel>? = nil,
extensionType: String? = nil,
productType: PBXTarget.ProductType? = nil
) -> BuildLabel {
let label = BuildLabel(labelName)
mockExtractor.labelToRuleEntry[label] = Swift.type(of: self).makeRuleEntry(
label,
type: type,
attributes: attributes,
weakDependencies: weakDependencies,
extensions: extensions,
productType: productType,
extensionType: extensionType)
return label
}
let test1 = addRule(
"//test:ExtFoo", type: "ios_extension", extensionType: "com.apple.extension-foo",
productType: .AppExtension)
let test2 = addRule(
"//test:ExtBar", type: "ios_extension", extensionType: "com.apple.extension-bar",
productType: .AppExtension)
addRule(
"//test:Application", type: "ios_application", extensions: [test1, test2],
productType: .Application)
prepareGenerator(mockExtractor.labelToRuleEntry)
func assertPlist(withData data: Data, equalTo value: NSDictionary) {
let content = try! PropertyListSerialization.propertyList(
from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil)
as! NSDictionary
XCTAssertEqual(content, value)
}
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(
mockFileManager.writeOperations.keys.contains(
"\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtFoo.plist"))
assertPlist(
withData: mockFileManager.writeOperations[
"\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtFoo.plist"]!,
equalTo: ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.extension-foo"]])
XCTAssert(
mockFileManager.writeOperations.keys.contains(
"\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtBar.plist"))
assertPlist(
withData: mockFileManager.writeOperations[
"\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtBar.plist"]!,
equalTo: ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.extension-bar"]])
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testUnresolvedLabelsThrows() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
mockExtractor.labelToRuleEntry = [:]
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
XCTFail("Generation succeeded unexpectedly")
} catch XcodeProjectGenerator.ProjectGeneratorError.labelResolutionFailed(let missingLabels) {
for label in buildTargetLabels {
XCTAssert(missingLabels.contains(label), "Expected missing label \(label) not found")
}
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testInvalidPathThrows() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
let invalidOutputFolderString = "/dev/null/bazel-build"
let invalidOutputFolderURL = URL(fileURLWithPath: invalidOutputFolderString)
do {
_ = try generator.generateXcodeProjectInFolder(invalidOutputFolderURL)
XCTFail("Generation succeeded unexpectedly")
} catch XcodeProjectGenerator.ProjectGeneratorError.invalidXcodeProjectPath(
let pathFound,
let reason)
{
// Expected failure on path with a /bazel-* directory.
XCTAssertEqual(pathFound, invalidOutputFolderString)
XCTAssertEqual(reason, "a Bazel generated temp directory (\"/bazel-\")")
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testTestSuiteSchemeGenerationWithSkylarkUnitTest() {
checkTestSuiteSchemeGeneration(
"ios_unit_test",
testProductType: .UnitTest,
testHostAttributeName: "test_host")
}
func testTestSuiteSchemeGenerationWithSkylarkUITest() {
checkTestSuiteSchemeGeneration(
"ios_ui_test",
testProductType: .UIUnitTest,
testHostAttributeName: "test_host")
}
func checkTestSuiteSchemeGeneration(
_ testRuleType: String,
testProductType: PBXTarget.ProductType,
testHostAttributeName: String
) {
@discardableResult
func addRule(
_ labelName: String,
type: String,
attributes: [String: AnyObject] = [:],
weakDependencies: Set<BuildLabel>? = nil,
productType: PBXTarget.ProductType? = nil
) -> BuildLabel {
let label = BuildLabel(labelName)
mockExtractor.labelToRuleEntry[label] = Swift.type(of: self).makeRuleEntry(
label,
type: type,
attributes: attributes,
weakDependencies: weakDependencies,
productType: productType)
return label
}
let app = addRule("//test:Application", type: "ios_application", productType: .Application)
let test1 = addRule(
"//test:TestOne",
type: testRuleType,
attributes: [testHostAttributeName: app.value as AnyObject],
productType: testProductType)
let test2 = addRule(
"//test:TestTwo",
type: testRuleType,
attributes: [testHostAttributeName: app.value as AnyObject],
productType: testProductType)
addRule("//test:UnusedTest", type: testRuleType, productType: testProductType)
addRule("//test:TestSuite", type: "test_suite", weakDependencies: Set([test1, test2]))
prepareGenerator(mockExtractor.labelToRuleEntry)
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.pbxproj"))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings"))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/project.xcworkspace/xcuserdata/USER.xcuserdatad/WorkspaceSettings.xcsettings"
))
XCTAssert(
writtenFiles.contains(
"\(xcodeProjectPath)/xcshareddata/xcschemes/test-Application.xcscheme"))
XCTAssert(
writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-TestOne.xcscheme"))
XCTAssert(
writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-TestTwo.xcscheme"))
XCTAssert(
writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-UnusedTest.xcscheme")
)
XCTAssert(
writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/TestSuite_Suite.xcscheme")
)
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testProjectSDKROOT() {
func validate(_ types: [(String, String)], _ expectedSDKROOT: String?, line: UInt = #line) {
let rules = types.map { tuple in
// Both the platform and osDeploymentTarget must be set in order to create a valid
// deploymentTarget for the RuleEntry.
XcodeProjectGeneratorTests.makeRuleEntry(
BuildLabel(tuple.0), type: tuple.0, platformType: tuple.1,
osDeploymentTarget: "this_must_not_be_nil")
}
let sdkroot = XcodeProjectGenerator.projectSDKROOT(rules)
XCTAssertEqual(sdkroot, expectedSDKROOT, line: line)
}
let iosAppTuple = ("ios_application", "ios")
let tvExtensionTuple = ("tvos_extension", "tvos")
validate([iosAppTuple], "iphoneos")
validate([iosAppTuple, iosAppTuple], "iphoneos")
validate([iosAppTuple, tvExtensionTuple], nil)
validate([tvExtensionTuple], "appletvos")
}
// MARK: - Private methods
private static func labelToRuleEntryMapForLabels(_ labels: [BuildLabel]) -> [BuildLabel:
RuleEntry]
{
var ret = [BuildLabel: RuleEntry]()
for label in labels {
ret[label] = makeRuleEntry(label, type: "ios_application", productType: .Application)
}
return ret
}
private static func makeRuleEntry(
_ label: BuildLabel,
type: String,
attributes: [String: AnyObject] = [:],
artifacts: [BazelFileInfo] = [],
sourceFiles: [BazelFileInfo] = [],
nonARCSourceFiles: [BazelFileInfo] = [],
dependencies: Set<BuildLabel> = Set(),
secondaryArtifacts: [BazelFileInfo] = [],
weakDependencies: Set<BuildLabel>? = nil,
buildFilePath: String? = nil,
objcDefines: [String]? = nil,
swiftDefines: [String]? = nil,
includePaths: [RuleEntry.IncludePath]? = nil,
extensions: Set<BuildLabel>? = nil,
productType: PBXTarget.ProductType? = nil,
extensionType: String? = nil,
platformType: String? = nil,
osDeploymentTarget: String? = nil
) -> RuleEntry {
return RuleEntry(
label: label,
type: type,
attributes: attributes,
artifacts: artifacts,
sourceFiles: sourceFiles,
nonARCSourceFiles: nonARCSourceFiles,
dependencies: dependencies,
secondaryArtifacts: secondaryArtifacts,
weakDependencies: weakDependencies,
extensions: extensions,
productType: productType,
platformType: platformType,
osDeploymentTarget: osDeploymentTarget,
buildFilePath: buildFilePath,
objcDefines: objcDefines,
swiftDefines: swiftDefines,
includePaths: includePaths,
extensionType: extensionType)
}
private func prepareGenerator(_ ruleEntries: [BuildLabel: RuleEntry], options: TulsiOptionSet = TulsiOptionSet()) {
// To avoid creating ~/Library folders and changing UserDefaults during CI testing.
config = TulsiGeneratorConfig(
projectName: XcodeProjectGeneratorTests.projectName,
buildTargetLabels: Array(ruleEntries.keys),
pathFilters: pathFilters,
additionalFilePaths: additionalFilePaths,
options: options,
bazelURL: bazelURL)
let projectURL = URL(fileURLWithPath: xcodeProjectPath, isDirectory: true)
mockFileManager.allowedDirectoryCreates.insert(projectURL.path)
let tulsiExecRoot = projectURL.appendingPathComponent(PBXTargetGenerator.TulsiExecutionRootSymlinkPath)
mockFileManager.allowedDirectoryCreates.insert(tulsiExecRoot.path)
let tulsiLegacyExecRoot = projectURL.appendingPathComponent(PBXTargetGenerator.TulsiExecutionRootSymlinkLegacyPath)
mockFileManager.allowedDirectoryCreates.insert(tulsiLegacyExecRoot.path)
let tulsiOutputBase = projectURL.appendingPathComponent(PBXTargetGenerator.TulsiOutputBaseSymlinkPath)
mockFileManager.allowedDirectoryCreates.insert(tulsiOutputBase.path)
let bazelCacheReaderURL = mockFileManager.homeDirectoryForCurrentUser.appendingPathComponent(
"Library/Application Support/Tulsi/Scripts", isDirectory: true)
mockFileManager.allowedDirectoryCreates.insert(bazelCacheReaderURL.path)
let xcshareddata = projectURL.appendingPathComponent("project.xcworkspace/xcshareddata")
mockFileManager.allowedDirectoryCreates.insert(xcshareddata.path)
let xcuserdata = projectURL.appendingPathComponent(
"project.xcworkspace/xcuserdata/USER.xcuserdatad")
mockFileManager.allowedDirectoryCreates.insert(xcuserdata.path)
let xcschemes = projectURL.appendingPathComponent("xcshareddata/xcschemes")
mockFileManager.allowedDirectoryCreates.insert(xcschemes.path)
let userXcschemes = projectURL.appendingPathComponent("xcuserdata/USER.xcuserdatad/xcschemes")
mockFileManager.allowedDirectoryCreates.insert(userXcschemes.path)
let scripts = projectURL.appendingPathComponent(".tulsi/Scripts")
mockFileManager.allowedDirectoryCreates.insert(scripts.path)
let utils = projectURL.appendingPathComponent(".tulsi/Utils")
mockFileManager.allowedDirectoryCreates.insert(utils.path)
let resources = projectURL.appendingPathComponent(".tulsi/Resources")
mockFileManager.allowedDirectoryCreates.insert(resources.path)
let tulsiBazelRoot = projectURL.appendingPathComponent(".tulsi/Bazel")
mockFileManager.allowedDirectoryCreates.insert(tulsiBazelRoot.path)
let tulsiBazelPackage = projectURL.appendingPathComponent(".tulsi/Bazel/tulsi")
mockFileManager.allowedDirectoryCreates.insert(tulsiBazelPackage.path)
let mockTemplate = ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.intents-service"]]
let templateData = try! PropertyListSerialization.data(
fromPropertyList: mockTemplate, format: .xml, options: 0)
mockFileManager.mockContent[resourceURLs.stubIOSAppExInfoPlistTemplate.path] = templateData
mockExtractor.labelToRuleEntry = ruleEntries
generator = XcodeProjectGenerator(
workspaceRootURL: workspaceRoot,
config: config,
localizedMessageLogger: mockLocalizedMessageLogger,
workspaceInfoExtractor: mockExtractor,
resourceURLs: resourceURLs,
tulsiVersion: testTulsiVersion,
fileManager: mockFileManager,
pbxTargetGeneratorType: MockPBXTargetGenerator.self)
generator.redactSymlinksToBazelOutput = true
generator.suppressModifyingUserDefaults = true
generator.suppressGeneratingBuildSettings = true
generator.writeDataHandler = { (url, _) in
self.writtenFiles.insert(url.path)
}
generator.usernameFetcher = { "USER" }
}
}
class MockFileManager: FileManager {
var filesThatExist = Set<String>()
var allowedDirectoryCreates = Set<String>()
var directoryOperations = [String]()
var copyOperations = [String: String]()
var writeOperations = [String: Data]()
var removeOperations = [String]()
var mockContent = [String: Data]()
var attributesMap = [String: [FileAttributeKey: Any]]()
override open var homeDirectoryForCurrentUser: URL {
return URL(fileURLWithPath: "/Users/__MOCK_USER__", isDirectory: true)
}
override func fileExists(atPath path: String) -> Bool {
return filesThatExist.contains(path)
}
override func createDirectory(
at url: URL,
withIntermediateDirectories createIntermediates: Bool,
attributes: [FileAttributeKey: Any]?
) throws {
guard !allowedDirectoryCreates.contains(url.path) else {
directoryOperations.append(url.path)
if let attributes = attributes {
self.setAttributes(attributes, path: url.path)
}
return
}
throw NSError(
domain: "MockFileManager: Directory creation disallowed",
code: 0,
userInfo: nil)
}
override func createDirectory(
atPath path: String,
withIntermediateDirectories createIntermediates: Bool,
attributes: [FileAttributeKey: Any]?
) throws {
guard !allowedDirectoryCreates.contains(path) else {
directoryOperations.append(path)
if let attributes = attributes {
self.setAttributes(attributes, path: path)
}
return
}
throw NSError(
domain: "MockFileManager: Directory creation disallowed",
code: 0,
userInfo: nil)
}
override func removeItem(at URL: URL) throws {
removeOperations.append(URL.path)
}
override func removeItem(atPath path: String) throws {
removeOperations.append(path)
}
override func copyItem(at srcURL: URL, to dstURL: URL) throws {
copyOperations[dstURL.path] = srcURL.path
}
override func copyItem(atPath srcPath: String, toPath dstPath: String) throws {
copyOperations[dstPath] = srcPath
}
override func contents(atPath path: String) -> Data? {
return mockContent[path]
}
override func createFile(
atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey: Any]? = nil
) -> Bool {
if writeOperations.keys.contains(path) {
fatalError("Attempting to overwrite an existing file at \(path)")
}
writeOperations[path] = data
if let attr = attr {
self.setAttributes(attr, path: path)
}
return true
}
fileprivate func setAttributes(_ attributes: [FileAttributeKey: Any], path: String) {
var currentAttributes = attributesMap[path] ?? [FileAttributeKey: Any]()
attributes.forEach { (k, v) in
currentAttributes[k] = v
}
attributesMap[path] = currentAttributes
}
override func setAttributes(_ attributes: [FileAttributeKey: Any], ofItemAtPath path: String)
throws
{
self.setAttributes(attributes, path: path)
}
}
final class MockPBXTargetGenerator: PBXTargetGeneratorProtocol {
var project: PBXProject
static func getRunTestTargetBuildConfigPrefix() -> String {
return "TestRunner__"
}
static func workingDirectoryForPBXGroup(_ group: PBXGroup) -> String {
return ""
}
static func mainGroupForOutputFolder(_ outputFolderURL: URL, workspaceRootURL: URL) -> PBXGroup {
return PBXGroup(
name: "mainGroup",
path: "/A/Test/Path",
sourceTree: .Absolute,
parent: nil)
}
required init(
bazelPath: String,
bazelBinPath: String,
project: PBXProject,
buildScriptPath: String,
resignerScriptPath: String,
stubInfoPlistPaths: StubInfoPlistPaths,
stubBinaryPaths: StubBinaryPaths,
tulsiVersion: String,
options: TulsiOptionSet,
localizedMessageLogger: LocalizedMessageLogger,
workspaceRootURL: URL,
suppressCompilerDefines: Bool
) {
self.project = project
}
func generateFileReferencesForFilePaths(_ paths: [String], pathFilters: Set<String>?) {
}
func registerRuleEntryForIndexer(
_ ruleEntry: RuleEntry,
ruleEntryMap: RuleEntryMap,
pathFilters: Set<String>,
processedEntries: inout [RuleEntry: (NSOrderedSet)]
) {
}
func generateIndexerTargets() -> [String: PBXTarget] {
return [:]
}
func generateBazelCleanTarget(
_ scriptPath: String, workingDirectory: String,
startupOptions: [String]
) {
}
func generateTopLevelBuildConfigurations(_ buildSettingOverrides: [String: String]) {
}
func generateBuildTargetsForRuleEntries(
_ ruleEntries: Set<RuleEntry>,
ruleEntryMap: RuleEntryMap,
pathFilters: Set<String>?
) throws -> [BuildLabel: PBXNativeTarget] {
// This works as this file only tests native targets that don't have multiple configurations.
let namedRuleEntries = ruleEntries.map { (e: RuleEntry) -> (String, RuleEntry) in
return (e.label.asFullPBXTargetName!, e)
}
var targetsByLabel = [BuildLabel: PBXNativeTarget]()
var testTargetLinkages = [(PBXTarget, BuildLabel)]()
for (name, entry) in namedRuleEntries {
let target = project.createNativeTarget(
name,
deploymentTarget: entry.deploymentTarget,
targetType: entry.pbxTargetType!)
targetsByLabel[entry.label] = target
if let hostLabelString = entry.attributes[.test_host] as? String {
let hostLabel = BuildLabel(hostLabelString)
testTargetLinkages.append((target, hostLabel))
}
}
for (testTarget, testHostLabel) in testTargetLinkages {
let hostTarget = project.targetByName(testHostLabel.asFullPBXTargetName!) as! PBXNativeTarget
project.linkTestTarget(testTarget, toHostTarget: hostTarget)
}
return targetsByLabel
}
}
| apache-2.0 | 5b8fcc214319ac79be638bb2751808f7 | 36.725111 | 119 | 0.724054 | 5.007692 | false | true | false | false |
abreis/swift-gissumo | tools/floatingCarDataXML2TSV/src/lib/SWXMLHash.swift | 5 | 27064 | //
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// 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.
// swiftlint exceptions:
// - Disabled file_length because there are a number of users that still pull the
// source down as is and it makes pulling the code into a project easier.
// swiftlint:disable file_length
import Foundation
let rootElementName = "SWXMLHash_Root_Element"
/// Parser options
public class SWXMLHashOptions {
internal init() {}
/// determines whether to parse the XML with lazy parsing or not
public var shouldProcessLazily = false
/// determines whether to parse XML namespaces or not (forwards to
/// `XMLParser.shouldProcessNamespaces`)
public var shouldProcessNamespaces = false
}
/// Simple XML parser
public class SWXMLHash {
let options: SWXMLHashOptions
private init(_ options: SWXMLHashOptions = SWXMLHashOptions()) {
self.options = options
}
/**
Method to configure how parsing works.
- parameters:
- configAction: a block that passes in an `SWXMLHashOptions` object with
options to be set
- returns: an `SWXMLHash` instance
*/
class public func config(_ configAction: (SWXMLHashOptions) -> Void) -> SWXMLHash {
let opts = SWXMLHashOptions()
configAction(opts)
return SWXMLHash(opts)
}
/**
Begins parsing the passed in XML string.
- parameters:
- xml: an XML string. __Note__ that this is not a URL but a
string containing XML.
- returns: an `XMLIndexer` instance that can be iterated over
*/
public func parse(_ xml: String) -> XMLIndexer {
return parse(xml.data(using: String.Encoding.utf8)!)
}
/**
Begins parsing the passed in XML string.
- parameters:
- data: a `Data` instance containing XML
- returns: an `XMLIndexer` instance that can be iterated over
*/
public func parse(_ data: Data) -> XMLIndexer {
let parser: SimpleXmlParser = options.shouldProcessLazily
? LazyXMLParser(options)
: FullXMLParser(options)
return parser.parse(data)
}
/**
Method to parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(_ xml: String) -> XMLIndexer {
return SWXMLHash().parse(xml)
}
/**
Method to parse XML passed in as a Data instance.
- parameter data: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(_ data: Data) -> XMLIndexer {
return SWXMLHash().parse(data)
}
/**
Method to lazily parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(_ xml: String) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(xml)
}
/**
Method to lazily parse XML passed in as a Data instance.
- parameter data: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func lazy(_ data: Data) -> XMLIndexer {
return config { conf in conf.shouldProcessLazily = true }.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(_ item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func drop() {
let _ = pop()
}
mutating func removeAll() {
items.removeAll(keepingCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
protocol SimpleXmlParser {
init(_ options: SWXMLHashOptions)
func parse(_ data: Data) -> XMLIndexer
}
#if os(Linux)
extension XMLParserDelegate {
func parserDidStartDocument(_ parser: Foundation.XMLParser) { }
func parserDidEndDocument(_ parser: Foundation.XMLParser) { }
func parser(_ parser: Foundation.XMLParser,
foundNotationDeclarationWithName name: String,
publicID: String?,
systemID: String?) { }
func parser(_ parser: Foundation.XMLParser,
foundUnparsedEntityDeclarationWithName name: String,
publicID: String?,
systemID: String?,
notationName: String?) { }
func parser(_ parser: Foundation.XMLParser,
foundAttributeDeclarationWithName attributeName: String,
forElement elementName: String,
type: String?,
defaultValue: String?) { }
func parser(_ parser: Foundation.XMLParser,
foundElementDeclarationWithName elementName: String,
model: String) { }
func parser(_ parser: Foundation.XMLParser,
foundInternalEntityDeclarationWithName name: String,
value: String?) { }
func parser(_ parser: Foundation.XMLParser,
foundExternalEntityDeclarationWithName name: String,
publicID: String?,
systemID: String?) { }
func parser(_ parser: Foundation.XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String]) { }
func parser(_ parser: Foundation.XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) { }
func parser(_ parser: Foundation.XMLParser,
didStartMappingPrefix prefix: String,
toURI namespaceURI: String) { }
func parser(_ parser: Foundation.XMLParser, didEndMappingPrefix prefix: String) { }
func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) { }
func parser(_ parser: Foundation.XMLParser,
foundIgnorableWhitespace whitespaceString: String) { }
func parser(_ parser: Foundation.XMLParser,
foundProcessingInstructionWithTarget target: String,
data: String?) { }
func parser(_ parser: Foundation.XMLParser, foundComment comment: String) { }
func parser(_ parser: Foundation.XMLParser, foundCDATA CDATABlock: Data) { }
func parser(_ parser: Foundation.XMLParser,
resolveExternalEntityName name: String,
systemID: String?) -> Data? { return nil }
func parser(_ parser: Foundation.XMLParser, parseErrorOccurred parseError: NSError) { }
func parser(_ parser: Foundation.XMLParser,
validationErrorOccurred validationError: NSError) { }
}
#endif
/// The implementation of XMLParserDelegate and where the lazy parsing actually happens.
class LazyXMLParser: NSObject, SimpleXmlParser, XMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: Data?
var ops: [IndexOp] = []
let options: SWXMLHashOptions
func parse(_ data: Data) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(_ ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary,
// but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = Foundation.XMLParser(data: data!)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
_ = parser.parse()
}
func parser(_ parser: Foundation.XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String]) {
elementStack.push(elementName)
if !onMatch() {
return
}
#if os(Linux)
let attributeNSDict = NSDictionary(
objects: attributeDict.values.flatMap({ $0 as? AnyObject }),
forKeys: attributeDict.keys.map({ NSString(string: $0) as NSObject })
)
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeNSDict)
#else
let currentNode = parentStack
.top()
.addElement(elementName, withAttributes: attributeDict as NSDictionary)
#endif
parentStack.push(currentNode)
}
func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) {
if !onMatch() {
return
}
let current = parentStack.top()
current.addText(string)
}
func parser(_ parser: Foundation.XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) {
let match = onMatch()
elementStack.drop()
if match {
parentStack.drop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return elementStack.items.starts(with: ops.map { $0.key })
} else {
return ops.map { $0.key }.starts(with: elementStack.items)
}
}
}
/// The implementation of XMLParserDelegate and where the parsing actually happens.
class FullXMLParser: NSObject, SimpleXmlParser, XMLParserDelegate {
required init(_ options: SWXMLHashOptions) {
self.options = options
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
let options: SWXMLHashOptions
func parse(_ data: Data) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary,
// but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = Foundation.XMLParser(data: data)
parser.shouldProcessNamespaces = options.shouldProcessNamespaces
parser.delegate = self
_ = parser.parse()
return XMLIndexer(root)
}
func parser(_ parser: Foundation.XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String]) {
#if os(Linux)
let attributeNSDict = NSDictionary(
objects: attributeDict.values.flatMap({ $0 as? AnyObject }),
forKeys: attributeDict.keys.map({ NSString(string: $0) as NSObject })
)
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeNSDict)
#else
let currentNode = parentStack
.top()
.addElement(elementName, withAttributes: attributeDict as NSDictionary)
#endif
parentStack.push(currentNode)
}
func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) {
let current = parentStack.top()
current.addText(string)
}
func parser(_ parser: Foundation.XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) {
parentStack.drop()
}
}
/// Represents an indexed operation against a lazily parsed `XMLIndexer`
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
/// Represents a collection of `IndexOp` instances. Provides a means of iterating them
/// to find a match in a lazily parsed `XMLIndexer` instance.
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepingCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Error type that is thrown when an indexing or parsing operation fails.
public enum IndexingError: Error {
case Attribute(attr: String)
case AttributeValue(attr: String, value: String)
case Key(key: String)
case Index(idx: Int)
case Init(instance: AnyObject)
case Error
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer: Sequence {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case XMLError(IndexingError)
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }).flatMap({ $0 }) {
for elem in elem.xmlChildren {
list.append(XMLIndexer(elem))
}
}
return list
}
/**
Allows for element lookup by matching attribute values.
- parameters:
- attr: should the name of the attribute to match on
- value: should be the value of the attribute to match on
- throws: an XMLIndexer.XMLError if an element with the specified attribute isn't found
- returns: instance of XMLIndexer
*/
public func withAttr(_ attr: String, _ value: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
let match = opStream.findElements()
return try match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({$0.attribute(by: attr)?.text == value}).first {
return .Element(elem)
}
throw IndexingError.AttributeValue(attr: attr, value: value)
case .Element(let elem):
if elem.attribute(by: attr)?.text == value {
return .Element(elem)
}
throw IndexingError.AttributeValue(attr: attr, value: value)
default:
throw IndexingError.Attribute(attr: attr)
}
}
/**
Initializes the XMLIndexer
- parameter _: should be an instance of XMLElement, but supports other values for error handling
- throws: an Error if the object passed in isn't an XMLElement or LaxyXMLParser
*/
public init(_ rawObject: AnyObject) throws {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
throw IndexingError.Init(instance: rawObject)
}
}
/**
Initializes the XMLIndexer
- parameter _: an instance of XMLElement
*/
public init(_ elem: XMLElement) {
self = .Element(elem)
}
init(_ stream: LazyXMLParser) {
self = .Stream(IndexOps(parser: stream))
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
- throws: Throws an XMLIndexingError.Key if no element was found
*/
public func byKey(_ key: String) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.xmlChildren.filter({ $0.name == key })
if !match.isEmpty {
if match.count == 1 {
return .Element(match[0])
} else {
return .List(match)
}
}
fallthrough
default:
throw IndexingError.Key(key: key)
}
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by
*/
public subscript(key: String) -> XMLIndexer {
do {
return try self.byKey(key)
} catch let error as IndexingError {
return .XMLError(error)
} catch {
return .XMLError(IndexingError.Key(key: key))
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
- parameter index: The 0-based index to index by
- throws: XMLIndexer.XMLError if the index isn't found
- returns: instance of XMLIndexer to match the element (or elements) found by index
*/
public func byIndex(_ index: Int) throws -> XMLIndexer {
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .XMLError(IndexingError.Index(idx: index))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
fallthrough
default:
return .XMLError(IndexingError.Index(idx: index))
}
}
/**
Find an XML element by index
- parameter index: The 0-based index to index by
- returns: instance of XMLIndexer to match the element (or elements) found by index
*/
public subscript(index: Int) -> XMLIndexer {
do {
return try byIndex(index)
} catch let error as IndexingError {
return .XMLError(error)
} catch {
return .XMLError(IndexingError.Index(idx: index))
}
}
typealias GeneratorType = XMLIndexer
/**
Method to iterate (for-in) over the `all` collection
- returns: an array of `XMLIndexer` instances
*/
public func makeIterator() -> IndexingIterator<[XMLIndexer]> {
return all.makeIterator()
}
}
/// XMLIndexer extensions
/*
extension XMLIndexer: Boolean {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
switch self {
case .XMLError:
return false
default:
return true
}
}
}
*/
extension XMLIndexer: CustomStringConvertible {
/// The XML representation of the XMLIndexer at the current level
public var description: String {
switch self {
case .List(let list):
return list.map { $0.description }.joined(separator: "")
case .Element(let elem):
if elem.name == rootElementName {
return elem.children.map { $0.description }.joined(separator: "")
}
return elem.description
default:
return ""
}
}
}
extension IndexingError: CustomStringConvertible {
/// The description for the `IndexingError`.
public var description: String {
switch self {
case .Attribute(let attr):
return "XML Attribute Error: Missing attribute [\"\(attr)\"]"
case .AttributeValue(let attr, let value):
return "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"
case .Key(let key):
return "XML Element Error: Incorrect key [\"\(key)\"]"
case .Index(let index):
return "XML Element Error: Incorrect index [\"\(index)\"]"
case .Init(let instance):
return "XML Indexer Error: initialization with Object [\"\(instance)\"]"
case .Error:
return "Unknown Error"
}
}
}
/// Models content for an XML doc, whether it is text or XML
public protocol XMLContent: CustomStringConvertible { }
/// Models a text element
public class TextElement: XMLContent {
/// The underlying text value
public let text: String
init(text: String) {
self.text = text
}
}
public struct XMLAttribute {
public let name: String
public let text: String
init(name: String, text: String) {
self.name = name
self.text = text
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement: XMLContent {
/// The name of the element
public let name: String
// swiftlint:disable line_length
/// The attributes of the element
@available(*, deprecated, message: "See `allAttributes` instead, which introduces the XMLAttribute type over a simple String type")
public var attributes: [String:String] {
var attrMap = [String: String]()
for (name, attr) in allAttributes {
attrMap[name] = attr.text
}
return attrMap
}
// swiftlint:enable line_length
/// All attributes
public var allAttributes = [String: XMLAttribute]()
public func attribute(by name: String) -> XMLAttribute? {
return allAttributes[name]
}
/// The inner text of the element, if it exists
public var text: String? {
return children
.map({ $0 as? TextElement })
.flatMap({ $0 })
.reduce("", { $0 + $1.text })
}
/// All child elements (text or XML)
public var children = [XMLContent]()
var count: Int = 0
var index: Int
var xmlChildren: [XMLElement] {
return children.map { $0 as? XMLElement }.flatMap { $0 }
}
/**
Initialize an XMLElement instance
- parameters:
- name: The name of the element to be initialized
- index: The index of the element to be initialized
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameters:
- name: The name of the new element to be added
- withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(_ name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count += 1
children.append(element)
for (keyAny, valueAny) in attributes {
if let key = keyAny as? String,
let value = valueAny as? String {
element.allAttributes[key] = XMLAttribute(name: key, text: value)
}
}
return element
}
func addText(_ text: String) {
let elem = TextElement(text: text)
children.append(elem)
}
}
extension TextElement: CustomStringConvertible {
/// The text value for a `TextElement` instance.
public var description: String {
return text
}
}
extension XMLAttribute: CustomStringConvertible {
/// The textual representation of an `XMLAttribute` instance.
public var description: String {
return "\(name)=\"\(text)\""
}
}
extension XMLElement: CustomStringConvertible {
/// The tag, attributes and content for a `XMLElement` instance (<elem id="foo">content</elem>)
public var description: String {
var attributesString = allAttributes.map { $0.1.description }.joined(separator: " ")
if !attributesString.isEmpty {
attributesString = " " + attributesString
}
if !children.isEmpty {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joined(separator: "")
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
} else {
return "<\(name)\(attributesString)/>"
}
}
}
// Workaround for "'XMLElement' is ambiguous for type lookup in this context" error on macOS.
//
// On macOS, `XMLElement` is defined in Foundation.
// So, the code referencing `XMLElement` generates above error.
// Following code allow to using `SWXMLhash.XMLElement` in client codes.
extension SWXMLHash {
public typealias XMLElement = SWXMLHashXMLElement
}
public typealias SWXMLHashXMLElement = XMLElement
| mit | f2f01415f9d86cc35694512681c258ca | 30.108046 | 135 | 0.612289 | 4.893148 | false | false | false | false |
KinoAndWorld/DailyMood | DailyMood/Controller/MoodChoseVC.swift | 1 | 2813 | //
// MoodChoseVC.swift
// DailyMood
//
// Created by kino on 14-7-15.
// Copyright (c) 2014年 kino. All rights reserved.
//
import UIKit
class MoodChoseVC: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate{
@IBOutlet var moodCollectionView: UICollectionView
typealias moodBeSelectBlock = (Mood,CGRect)->Void
var moodFinishBlock:moodBeSelectBlock? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// self.moodCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
moodCollectionView.registerNib(UINib(nibName: "MoodCell", bundle: nil), forCellWithReuseIdentifier: "MoodCell")
moodCollectionView.backgroundColor = UIColor.clearColor()
moodCollectionView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma 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.
}
*/
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int{
return 12
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MoodCell", forIndexPath: indexPath) as MoodCell
// cell.contentView.backgroundColor = UIColor.
cell.configCellByModel(Mood.moodByIndex(indexPath.row))
return cell
}
func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
let cell:MoodCell = collectionView.cellForItemAtIndexPath(indexPath) as MoodCell
var cellFrame = cell.frame
// cellFrame = collectionView.convertRect(cell.frame, fromView: cell)
cellFrame = CGRect(origin: CGPoint(x: cell.left + collectionView.left,
y: cell.top + collectionView.top),
size: cell.frame.size)
moodFinishBlock?(Mood.moodByIndex(indexPath.row),cellFrame)
}
}
| mit | cf7c65832b9f94f83988fe580da7b7c6 | 37.506849 | 132 | 0.690502 | 5.522593 | false | false | false | false |
YevhenHerasymenko/SwiftGroup1 | Lecture_5_functions.playground/Contents.swift | 1 | 2042 | //: Playground - noun: a place where people can play
import UIKit
struct User {
let name: String
static func testUsers() -> [User] {
return [User(name: "Ostap"), User(name: "Andrew")]
}
static func userNamesString(users: [User]) -> String {
var string = ""
for user in users {
string = string + user.name
string += " ,"
}
return string
}
}
//let instance = User(name: "Someone")
//User.printHello(5, name: "test")
let testUsers = User.testUsers()
let names = User.userNamesString(testUsers)
names
let test = User(name: "test")
func doOk() {
print("ok")
}
func returnOptional(shouldReturn: Bool?) -> String? {
if shouldReturn == true {
return "ok"
} else {
return nil
}
}
//
returnOptional(true)
returnOptional(false)
returnOptional(nil)
func printNumbers(limit: Int = 10, endString: String? = nil) -> Int {
for i in 0..<limit {
if i > 0 && (i % 10 == 0) {
continue
}
print(i)
}
if let string = endString {
print(string)
}
return limit - 1
}
let limit: Int = 10
let result = printNumbers(endString: "test")
class Car {
let price: Float?
init?(carPrice: Float) {
if carPrice < 0 {
return nil
}
self.price = carPrice
}
}
var cars: [Car] = []
if let car = Car(carPrice: -1) {
cars.append(car)
}
if let car = Car(carPrice: 200) {
cars.append(car)
}
//cars.append(car)
func filterCars(cars: [Car], byPrice price: Float) -> [Car] {
var filteredCars: [Car] = []
for dog in cars {
if dog.price <= price {
filteredCars.append(dog)
}
}
return filteredCars
}
filterCars(cars, byPrice: 250)
let numbers: [Int?] = [1, 2, 3, nil, 4, 5]
var nonOptNumbers: [Int] = []
for number in numbers {
if let number = number {
nonOptNumbers.append(number)
}
}
nonOptNumbers
let nonOptNumbers1 = numbers.flatMap{$0}
nonOptNumbers1
//numbers.append(1)
| apache-2.0 | ec637bc80bd80d751eebcb802cec02f3 | 17.396396 | 69 | 0.572968 | 3.392027 | false | true | false | false |
daltoniam/Starscream | Tests/MockServer.swift | 1 | 3932 | //
// MockServer.swift
// Starscream
//
// Created by Dalton Cherry on 1/29/19.
// Copyright © 2019 Vluxe. All rights reserved.
//
import Foundation
@testable import Starscream
public class MockConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate {
let transport: MockTransport
private let httpHandler = FoundationHTTPServerHandler()
private let framer = WSFramer(isServer: true)
private let frameHandler = FrameCollector()
private var didUpgrade = false
public var onEvent: ((ConnectionEvent) -> Void)?
fileprivate weak var delegate: ConnectionDelegate?
init(transport: MockTransport) {
self.transport = transport
httpHandler.register(delegate: self)
framer.register(delegate: self)
frameHandler.delegate = self
}
func add(data: Data) {
if !didUpgrade {
httpHandler.parse(data: data)
} else {
framer.add(data: data)
}
}
public func write(data: Data, opcode: FrameOpCode) {
let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false)
transport.received(data: wsData)
}
/// MARK: - HTTPServerDelegate
public func didReceive(event: HTTPEvent) {
switch event {
case .success(let headers):
didUpgrade = true
//TODO: add headers and key check?
let response = httpHandler.createResponse(headers: [:])
transport.received(data: response)
delegate?.didReceive(event: .connected(self, headers))
onEvent?(.connected(headers))
case .failure(let error):
onEvent?(.error(error))
}
}
/// MARK: - FrameCollectorDelegate
public func frameProcessed(event: FrameEvent) {
switch event {
case .frame(let frame):
frameHandler.add(frame: frame)
case .error(let error):
onEvent?(.error(error))
}
}
public func didForm(event: FrameCollector.Event) {
switch event {
case .text(let string):
delegate?.didReceive(event: .text(self, string))
onEvent?(.text(string))
case .binary(let data):
delegate?.didReceive(event: .binary(self, data))
onEvent?(.binary(data))
case .pong(let data):
delegate?.didReceive(event: .pong(self, data))
onEvent?(.pong(data))
case .ping(let data):
delegate?.didReceive(event: .ping(self, data))
onEvent?(.ping(data))
case .closed(let reason, let code):
delegate?.didReceive(event: .disconnected(self, reason, code))
onEvent?(.disconnected(reason, code))
case .error(let error):
onEvent?(.error(error))
}
}
public func decompress(data: Data, isFinal: Bool) -> Data? {
return nil
}
}
public class MockServer: Server, ConnectionDelegate {
fileprivate var connections = [String: MockConnection]()
public var onEvent: ((ServerEvent) -> Void)?
public func start(address: String, port: UInt16) -> Error? {
return nil
}
public func connect(transport: MockTransport) {
let conn = MockConnection(transport: transport)
conn.delegate = self
connections[transport.uuid] = conn
}
public func disconnect(uuid: String) {
// guard let conn = connections[uuid] else {
// return
// }
//TODO: force disconnect
connections.removeValue(forKey: uuid)
}
public func write(data: Data, uuid: String) {
guard let conn = connections[uuid] else {
return
}
conn.add(data: data)
}
/// MARK: - MockConnectionDelegate
public func didReceive(event: ServerEvent) {
onEvent?(event)
}
}
| apache-2.0 | 3114b986d1390724414c97fddd707bf0 | 29.238462 | 104 | 0.597049 | 4.549769 | false | false | false | false |
ViacomInc/Router | Example/AppDelegate.swift | 1 | 4156 | ////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Viacom Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////
import UIKit
import Router
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let router = Router()
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let root = self.window?.rootViewController as! UINavigationController
router.bind("/route/one") { (req) -> Void in
let list: ViewController = storyboard.instantiateViewController(withIdentifier: "routeOneList") as! ViewController
list.debugText = req.route.route
root.pushViewController(list, animated: true)
}
router.bind("/route/one/:id") { (req) -> Void in
let list: ViewController = storyboard.instantiateViewController(withIdentifier: "routeOneList") as! ViewController
list.debugText = "deeplink from \(req.route.route)"
let detail: ViewController = storyboard.instantiateViewController(withIdentifier: "routeOneDetail") as! ViewController
detail.debugText = req.route.route
detail.id = req.param("id")!
root.pushViewController(list, animated: false)
root.pushViewController(detail, animated: true)
}
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:.
}
private func application(application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if let _ = router.match(url as URL) {
return true
}
return false
}
}
| apache-2.0 | d7cbae7ba8f0df272433171edceb6b00 | 48.47619 | 285 | 0.680462 | 5.526596 | false | false | false | false |
nubbel/swift-tensorflow | Xcode/Test/AppDelegate.swift | 1 | 2421 |
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var echoProvider : Echo_EchoProvider!
var insecureServer: Echo_EchoServer!
var secureServer: Echo_EchoServer!
var workerService: Tensorflow_Grpc_WorkerServiceService!
var inceptionService:Tensorflow_Serving_InceptionServiceService!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// instantiate our custom-written application handler
echoProvider = EchoProvider()
// create and start a server for handling insecure requests
insecureServer = Echo_EchoServer(address:"localhost:8081",
provider:echoProvider)
insecureServer.start()
// create and start a server for handling secure requests
let certificateURL = Bundle.main.url(forResource: "ssl", withExtension: "crt")!
let keyURL = Bundle.main.url(forResource: "ssl", withExtension: "key")!
secureServer = Echo_EchoServer(address:"localhost:8443",
certificateURL:certificateURL,
keyURL:keyURL,
provider:echoProvider)
secureServer.start()
testTensorflow()
}
func testTensorflow(){
/*
Requires Docker
# pull and start the prebuilt container, forward port 9000
docker run -it -p 9000:9000 tgowda/inception_serving_tika
# Inside the container, start tensorflow service
root@8311ea4e8074:/# /serving/server.sh
*/
var inceptionRequest = Tensorflow_Serving_InceptionRequest()
if let imagePath = Bundle.main.pathForImageResource("chicken.jpg"){
let url = URL.init(fileURLWithPath: imagePath)
if let data = try? Data.init(contentsOf: url){
inceptionRequest.jpegEncoded = data
}
}else{
print("FAILED to load image!")
return;
}
inceptionService = Tensorflow_Serving_InceptionServiceService(address: "0.0.0.0:9000")
let _ = try? inceptionService.classify(inceptionRequest, completion: { (response, result) in
print(response?.scores)
print("🐣",response?.classes )
})
}
}
| mit | 444b33c68db8d9560f298942be3b5218 | 28.487805 | 100 | 0.610422 | 5.101266 | false | false | false | false |
mpclarkson/vapor | Sources/Vapor/Log/Log.swift | 1 | 3274 | /**
Log messages to the console using
the static methods on this class.
*/
public class Log {
/**
LogLevel enumeration
*/
public enum Level: Equatable, CustomStringConvertible {
case Verbose, Debug, Info, Warning, Error, Fatal, Custom(String)
/*
Returns all standard log levels (i.e. except Custom)
returns - array of Log.Level
*/
public static var all: [Log.Level] {
return [.Verbose, .Debug, .Info, .Warning, .Error, .Fatal]
}
public var description: String {
switch self {
case Verbose: return "VERBOSE"
case Debug: return "DEBUG"
case Info: return "INFO"
case Warning: return "WARNING"
case Error: return "ERROR"
case Fatal: return "FATAL"
case Custom(let string): return "\(string.uppercased())"
}
}
}
/**
LogDriver. Default is the console logger.
This can be overriden with a custom logger.
*/
public static var driver: LogDriver = ConsoleLogger()
/**
Enabled log levels. Default is to log all levels. This
can be overridden.
*/
public static var enabledLevels: [Log.Level] = Log.Level.all
/**
Logs verbose messages if .Verbose is enabled
- parameter message: String to log
*/
public static func verbose(message: String) {
if Log.enabledLevels.contains(.Verbose) {
driver.log(.Verbose, message: message)
}
}
/**
Logs debug messages if .Debug is enabled
- parameter message: String to log
*/
public static func debug(message: String) {
if Log.enabledLevels.contains(.Debug) {
driver.log(.Debug, message: message)
}
}
/**
Logs info messages if .Info is enabled
- parameter message: String to log
*/
public static func info(message: String) {
if Log.enabledLevels.contains(.Info) {
driver.log(.Info, message: message)
}
}
/**
Logs warning messages if .Warning is enabled
- parameter message: String to log
*/
public static func warning(message: String) {
if Log.enabledLevels.contains(.Warning) {
driver.log(.Warning, message: message)
}
}
/**
Logs error messages if .Error is enabled
- parameter message: String to log
*/
public static func error(message: String) {
if Log.enabledLevels.contains(.Error) {
driver.log(.Error, message: message)
}
}
/**
Logs fatal messages if .Fatal is enabled
- parameter message: String to log
*/
public static func fatal(message: String) {
if Log.enabledLevels.contains(.Fatal) {
driver.log(.Fatal, message: message)
}
}
/**
Logs custom messages if .Always is enabled.
- parameter message: String to log
*/
public static func custom(message: String, label: String) {
driver.log(.Custom(label), message: message)
}
}
public func == (lhs: Log.Level, rhs: Log.Level) -> Bool {
return lhs.description == rhs.description
}
| mit | be901eb371b071e27e19415a8241057d | 25.192 | 72 | 0.573305 | 4.643972 | false | false | false | false |
sora0077/AppleMusicKit | Sources/Request/FetchHistory.swift | 1 | 1798 | //
// FetchHistory.swift
// AppleMusicKit
//
// Created by 林 達也 on 2017/07/05.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
public struct GetHeavyRotationContent<
Song: SongDecodable,
Album: AlbumDecodable,
Artist: ArtistDecodable,
MusicVideo: MusicVideoDecodable,
Playlist: PlaylistDecodable,
Curator: CuratorDecodable,
AppleCurator: AppleCuratorDecodable,
Activity: ActivityDecodable,
Station: StationDecodable,
Storefront: StorefrontDecodable,
Genre: GenreDecodable,
Recommendation: RecommendationDecodable
>: PaginatorResourceRequest, InternalPaginatorRequest {
public typealias Resource = AnyResource<NoRelationships>
public var scope: AccessScope { return .user }
public let path: String
public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) }
public internal(set) var limit: Int?
public let offset: Int?
private let _parameters: [String: Any]
public init(language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) {
self.init(path: "/v1/me/history/heavy-rotation",
parameters: ["l": language?.languageTag, "limit": limit, "offset": offset].cleaned)
}
init(path: String, parameters: [String: Any]) {
self.path = path
_parameters = parameters
(limit, offset) = parsePaginatorParameters(parameters)
}
}
extension GetHeavyRotationContent {
public typealias AnyResource<R: Decodable> = AppleMusicKit.AnyResource<
Song,
Album,
Artist,
MusicVideo,
Playlist,
Curator,
AppleCurator,
Activity,
Station,
Storefront,
Genre,
Recommendation,
R>
}
| mit | ca90533f41cfe91323e5557298449ed6 | 27.854839 | 104 | 0.673002 | 4.321256 | false | false | false | false |
wjk930726/weibo | weiBo/weiBo/iPhone/Manager/NetworkManager.swift | 1 | 5726 | //
// NetworkTool.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/26.
// Copyright © 2016年 王靖凯. All rights reserved.
//
//
// NetworkManager.swift
// NetworkManager
//
// Created by 王靖凯 on 2017/11/16.
// Copyright © 2017年 王靖凯. All rights reserved.
//
import Alamofire
import Foundation
class NetworkManager {
private init() {}
static let shared = { () -> NetworkManager in
let instance = NetworkManager()
// instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
return instance
}()
}
struct NMError: Error {
enum ErrorKind {
case transformFailed
case uploadFailed
}
let kind: ErrorKind
}
extension Result {
// Note: rethrows 用于参数是一个会抛出异常的闭包的情况,该闭包的异常不会被捕获,会被再次抛出,所以可以直接使用 try,而不用 do-try-catch
/// U 可能为 Optional
func map<U>(transform: (_: Value) throws -> U) rethrows -> Result<U> {
switch self {
case let .failure(error):
return .failure(error)
case let .success(value):
return .success(try transform(value))
}
}
/// 若 transform 的返回值为 nil 则作为异常处理
func flatMap<U>(transform: (_: Value) throws -> U?) rethrows -> Result<U> {
switch self {
case let .failure(error):
return .failure(error)
case let .success(value):
guard let transformedValue = try transform(value) else {
return .failure(NMError(kind: .transformFailed))
}
return .success(transformedValue)
}
}
/// 适用于 transform(value) 之后可能产生 error 的情况
func flatMap<U>(transform: (_: Value) throws -> Result<U>) rethrows -> Result<U> {
switch self {
case let .failure(error):
return .failure(error)
case let .success(value):
return try transform(value)
}
}
/// 处理错误,并向下传递
func mapError(transform: (_: Error) throws -> Error) rethrows -> Result<Value> {
switch self {
case let .failure(error):
return .failure(try transform(error))
case let .success(value):
return .success(value)
}
}
/// 处理数据(不再向下传递数据,作为数据流的终点)
func handleValue(handler: (_: Value) -> Void) {
switch self {
case .failure:
break
case let .success(value):
handler(value)
}
}
/// 处理错误(终点)
func handleError(handler: (_: Error) -> Void) {
switch self {
case let .failure(error):
handler(error)
case .success:
break
}
}
}
extension NetworkManager {
func parseResult(result: Result<Any>) -> Result<Any> {
return result
// .flatMap { $0 as? [String: Any] } //如有需要可做进一步处理
}
}
/// 显式地声明Request遵守Cancellable协议
protocol Cancellable {
func cancel()
}
// MARK: - Request本来就实现了cancel方法
extension Request: Cancellable {}
extension NetworkManager {
@discardableResult
func get(url: String,
parameters: [String: Any]? = nil,
networkCompletionHandler: @escaping (Result<Any>) -> Void
) -> Cancellable? {
return Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
networkCompletionHandler(self.parseResult(result: $0.result))
}
}
@discardableResult
func post(url: String,
parameters: [String: Any]? = nil,
networkCompletionHandler: @escaping (Result<Any>) -> Void
) -> Cancellable? {
return Alamofire.request(url, method: .post, parameters: parameters).responseJSON {
networkCompletionHandler(self.parseResult(result: $0.result))
}
}
func post(url: String,
parameters: [String: String]? = nil, // 字典值写死为String,如有需求再改吧
image: UIImage,
networkCompletionHandler: @escaping (Result<Any>) -> Void
) {
guard let urlConvertible = URL(string: url) else {
console.debug("传入上传的URL地址错误")
return
}
Alamofire.upload(multipartFormData: { multipartFormData in
let data = UIImageJPEGRepresentation(image, 1)
let imageName = String(describing: Date()) + ".png"
multipartFormData.append(data!, withName: imageName, mimeType: "application/octet-stream") // mimeType: "image/png"
if let param = parameters {
for (key, value) in param {
if let data = value.data(using: String.Encoding.utf8) {
multipartFormData.append(data, withName: key)
}
}
}
}, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, with: URLRequest(url: urlConvertible)) { encodingResult in
switch encodingResult {
case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
upload.responseJSON {
networkCompletionHandler(self.parseResult(result: $0.result))
}
case let .failure(error):
console.debug(error)
// 如果能抛出这个异常就更好了
// let err = NMError(kind: NMError.ErrorKind.uploadFailed)
// self.parseResult(result: err)
}
}
return
}
}
| mit | 455b0d455040f4e51503dcf7db143a26 | 28.103825 | 142 | 0.575854 | 4.401653 | false | false | false | false |
zhaobin19918183/zhaobinCode | HTK/HTK/HomeViewController/CarVIewController/BusTableViewController.swift | 1 | 18533 | //
// BusTableViewController.swift
// HTK
//
// Created by Zhao.bin on 16/6/3.
// Copyright © 2016年 赵斌. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class emailMenuItem: UIMenuItem{
var indexPath: IndexPath!
}
class BusTableViewController: UITableViewController,SectionHeaderViewDelegate{
let SectionHeaderViewIdentifier = "SectionHeaderViewIdentifier"
var plays:NSArray!
var sectionInfoArray:NSMutableArray!
var pinchedIndexPath:IndexPath!
var opensectionindex:Int!
var initialPinchHeight:CGFloat!
var playe:NSMutableArray?
var sectionHeaderView:SectionHeaderView!
//当缩放手势同时改变了所有单元格高度时使用uniformRowHeight
var uniformRowHeight: Int!
let DefaultRowHeight = 88
let HeaderHeight = 48
//MARK: 开始
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.isHidden = true
let nextItem=UIBarButtonItem(title:"Home",style:.plain,target:self,action:#selector(backHomeView))
self.navigationItem.leftBarButtonItem = nextItem
// 为表视图添加缩放手势识别
let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(BusTableViewController.handlePinch(_:)))
self.tableView.addGestureRecognizer(pinchRecognizer)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
// 设置Header的高度
self.tableView.sectionHeaderHeight = CGFloat(HeaderHeight)
// 分节信息数组在viewWillUnload方法中将被销毁,因此在这里设置Header的默认高度是可行的。如果您想要保留分节信息等内容,可以在指定初始化器当中设置初始值。
self.uniformRowHeight = DefaultRowHeight
self.opensectionindex = NSNotFound
let sectionHeaderNib: UINib = UINib(nibName: "SectionHeaderView", bundle: nil)
self.tableView.register(sectionHeaderNib, forHeaderFooterViewReuseIdentifier: SectionHeaderViewIdentifier)
plays = played()
}
func backHomeView()
{
self.navigationController!.popViewController(animated: true)
self.tabBarController?.tabBar.isHidden = false
}
override var canBecomeFirstResponder : Bool {
return true
}
//MARK:viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 检查分节信息数组是否已被创建,如果其已创建,则再检查节的数量是否仍然匹配当前节的数量。通常情况下,您需要保持分节信息与单元格、分节格同步u过您要允许在表视图中编辑信息,您需要在编辑操作中适当更新分节信息。
if self.sectionInfoArray == nil || self.sectionInfoArray.count != self.numberOfSections(in: self.tableView) {
//对于每个场次来说,需要为每个单元格设立一个一致的、包含默认高度的SectionInfo对象。
let infoArray = NSMutableArray()
for play in self.plays {
let sectionInfo = SectionInfo()
sectionInfo.play = play as! Play
sectionInfo.open = false
let defaultRowHeight = DefaultRowHeight
let countOfQuotations = sectionInfo.play.quotations.count
for i in 0...countOfQuotations {
sectionInfo.insertObject(defaultRowHeight, inRowHeightsAtIndex: i)
}
infoArray.add(sectionInfo)
}
self.sectionInfoArray = infoArray
}
}
//MARK:分组数量
override func numberOfSections(in tableView: UITableView) -> Int {
// 这个方法返回 tableview 有多少个section
return self.plays.count
}
// MARK: 单元格数量
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 这个方法返回对应的section有多少个元素,也就是多少行
let sectionInfo: SectionInfo = self.sectionInfoArray[section] as! SectionInfo
let numStoriesInSection = sectionInfo.play.quotations.count
let sectionOpen = sectionInfo.open!
return sectionOpen ? numStoriesInSection : 0
}
//MARK: 单元格样式
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 返回指定的row 的cell。这个地方是比较关键的地方,一般在这个地方来定制各种个性化的 cell元素。这里只是使用最简单最基本的cell 类型。其中有一个主标题 cell.textLabel 还有一个副标题cell.detailTextLabel, 还有一个 image在最前头 叫cell.imageView. 还可以设置右边的图标,通过cell.accessoryType 可以设置是饱满的向右的蓝色箭头,还是单薄的向右箭头,还是勾勾标记。
let QuoteCellIdentifier = "QuoteCellIdentifier"
let cell: QuoteCell = tableView.dequeueReusableCell(withIdentifier: QuoteCellIdentifier) as! QuoteCell
if cell.longPressRecognizer == nil {
let longPressRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(BusTableViewController.handleLongPress(_:)))
cell.longPressRecognizer = longPressRecognizer
}
cell.selectionStyle = UITableViewCellSelectionStyle.none
let play:Play = (self.sectionInfoArray[(indexPath as NSIndexPath).section] as! SectionInfo).play
cell.quotation = play.quotations[(indexPath as NSIndexPath).row] as! Quotation
cell.setTheQuotation(cell.quotation)
cell.setTheLongPressRecognizer(cell.longPressRecognizer)
return cell
}
//MARK:Header View
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// 返回指定的 section header 的view,如果没有,这个函数可以不返回view
let sectionHeaderView: SectionHeaderView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderViewIdentifier) as! SectionHeaderView
let sectionInfo: SectionInfo = self.sectionInfoArray[section] as! SectionInfo
sectionInfo.headerView = sectionHeaderView
sectionHeaderView.titleLabel.text = sectionInfo.play.name
sectionHeaderView.section = section
sectionHeaderView.delegate = self
return sectionHeaderView
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// 这个方法返回指定的 row 的高度
let sectionInfo: SectionInfo = self.sectionInfoArray[(indexPath as NSIndexPath).section] as! SectionInfo
return CGFloat(sectionInfo.objectInRowHeightsAtIndex((indexPath as NSIndexPath).row) as! NSNumber)
//又或者,返回单元格的行高
}
// _________________________________________________________________________
// SectionHeaderViewDelegate
func sectionHeaderView(_ sectionHeaderView: SectionHeaderView, sectionOpened: Int) {
let sectionInfo: SectionInfo = self.sectionInfoArray[sectionOpened] as! SectionInfo
sectionInfo.open = true
//创建一个包含单元格索引路径的数组来实现插入单元格的操作:这些路径对应当前节的每个单元格
let countOfRowsToInsert = sectionInfo.play.quotations.count
let indexPathsToInsert = NSMutableArray()
for i in 0 ..< countOfRowsToInsert {
indexPathsToInsert.add(IndexPath(row: i, section: sectionOpened))
}
// 创建一个包含单元格索引路径的数组来实现删除单元格的操作:这些路径对应之前打开的节的单元格
let indexPathsToDelete = NSMutableArray()
let previousOpenSectionIndex = self.opensectionindex
if previousOpenSectionIndex != NSNotFound {
let previousOpenSection: SectionInfo = self.sectionInfoArray[previousOpenSectionIndex!] as! SectionInfo
previousOpenSection.open = false
previousOpenSection.headerView.toggleOpenWithUserAction(false)
let countOfRowsToDelete = previousOpenSection.play.quotations.count
for i in 0 ..< countOfRowsToDelete {
indexPathsToDelete.add(IndexPath(row: i, section: previousOpenSectionIndex!))
}
}
// 设计动画,以便让表格的打开和关闭拥有一个流畅(很屌)的效果
var insertAnimation: UITableViewRowAnimation
var deleteAnimation: UITableViewRowAnimation
if previousOpenSectionIndex == NSNotFound || sectionOpened < previousOpenSectionIndex {
insertAnimation = UITableViewRowAnimation.top
deleteAnimation = UITableViewRowAnimation.bottom
}else{
insertAnimation = UITableViewRowAnimation.bottom
deleteAnimation = UITableViewRowAnimation.top
}
// 应用单元格的更新
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPathsToDelete as [AnyObject] as! [IndexPath] , with: deleteAnimation)
self.tableView.insertRows(at: indexPathsToInsert as [AnyObject] as! [IndexPath], with: insertAnimation)
self.opensectionindex = sectionOpened
self.tableView.endUpdates()
}
func sectionHeaderView(_ sectionHeaderView: SectionHeaderView, sectionClosed: Int) {
// 在表格关闭的时候,创建一个包含单元格索引路径的数组,接下来从表格中删除这些行
let sectionInfo: SectionInfo = self.sectionInfoArray[sectionClosed] as! SectionInfo
sectionInfo.open = false
let countOfRowsToDelete = self.tableView.numberOfRows(inSection: sectionClosed)
if countOfRowsToDelete > 0 {
let indexPathsToDelete = NSMutableArray()
for i in 0 ..< countOfRowsToDelete {
indexPathsToDelete.add(IndexPath(row: i, section: sectionClosed))
}
self.tableView.deleteRows(at: indexPathsToDelete as [AnyObject] as! [IndexPath], with: UITableViewRowAnimation.top)
}
self.opensectionindex = NSNotFound
}
// ____________________________________________________________________
//MARK: 缩放操作处理
func handlePinch(_ pinchRecognizer: UIPinchGestureRecognizer) {
// 有手势识别有很多状态来对应不同的动作:
// * 对于 Began 状态来说,是用缩放点的位置来找寻单元格的索引路径,并将索引路径与缩放操作进行绑定,同时在 pinchedIndexPath 中保留一个引用。接下来方法获取单元格的高度,然后存储其在缩放开始前的高度。最后,为缩放的单元格更新比例。
// * 对于 Changed 状态来说,是为缩放的单元格更新比例(由 pinchedIndexPath 支持)
// * 对于 Ended 或者 Canceled状态来说,是将 pinchedIndexPath 属性设置为 nil
NSLog("pinch Gesture")
if pinchRecognizer.state == UIGestureRecognizerState.began {
let pinchLocation = pinchRecognizer.location(in: self.tableView)
let newPinchedIndexPath = self.tableView.indexPathForRow(at: pinchLocation)
self.pinchedIndexPath = newPinchedIndexPath
let sectionInfo: SectionInfo = self.sectionInfoArray[(newPinchedIndexPath! as NSIndexPath).section] as! SectionInfo
self.initialPinchHeight = sectionInfo.objectInRowHeightsAtIndex((newPinchedIndexPath! as NSIndexPath).row) as! CGFloat
NSLog("pinch Gesture began")
// 也可以设置为 initialPinchHeight = uniformRowHeight
self.updateForPinchScale(pinchRecognizer.scale, indexPath: newPinchedIndexPath!)
}else {
if pinchRecognizer.state == UIGestureRecognizerState.changed {
self.updateForPinchScale(pinchRecognizer.scale, indexPath: self.pinchedIndexPath)
}else if pinchRecognizer.state == UIGestureRecognizerState.cancelled || pinchRecognizer.state == UIGestureRecognizerState.ended {
self.pinchedIndexPath = nil
}
}
}
func updateForPinchScale(_ scale: CGFloat, indexPath:IndexPath?) {
let section:NSInteger = (indexPath! as NSIndexPath).section
let row:NSInteger = (indexPath! as NSIndexPath).row
let found:NSInteger = NSNotFound
if (section != found) && (row != found) && indexPath != nil {
var newHeight:CGFloat!
if self.initialPinchHeight > CGFloat(DefaultRowHeight) {
newHeight = round(self.initialPinchHeight)
}else {
newHeight = round(CGFloat(DefaultRowHeight))
}
let sectionInfo: SectionInfo = self.sectionInfoArray[(indexPath! as NSIndexPath).section] as! SectionInfo
sectionInfo.replaceObjectInRowHeightsAtIndex((indexPath! as NSIndexPath).row, withObject: (newHeight))
// 也可以设置为 uniformRowHeight = newHeight
// 在单元格高度改变时关闭动画, 不然的话就会有迟滞的现象
let animationsEnabled: Bool = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
self.tableView.beginUpdates()
self.tableView.endUpdates()
UIView.setAnimationsEnabled(animationsEnabled)
}
}
// ________________________________________________________________________
//MARK: 处理长按手势
func handleLongPress(_ longPressRecognizer: UILongPressGestureRecognizer) {
// 对于长按手势来说,唯一的状态是Began
// 当长按手势被识别后,将会找寻按压点的单元格的索引路径
// 如果按压位置存在一个单元格,那么就会创建一个菜单并展示它
if longPressRecognizer.state == UIGestureRecognizerState.began {
let pressedIndexPath = self.tableView.indexPathForRow(at: longPressRecognizer.location(in: self.tableView))
if pressedIndexPath != nil && (pressedIndexPath as NSIndexPath?)?.row != NSNotFound && (pressedIndexPath as NSIndexPath?)?.section != NSNotFound {
self.becomeFirstResponder()
let title = Bundle.main.localizedString(forKey: "邮件", value: "", table: nil)
let menuItem: emailMenuItem = emailMenuItem(title: title, action: #selector(BusTableViewController.emailMenuButtonPressed(_:)))
menuItem.indexPath = pressedIndexPath
let menuController = UIMenuController.shared
menuController.menuItems = [menuItem]
var cellRect = self.tableView.rectForRow(at: pressedIndexPath!)
// 略微减少对象的长宽高(不要让其在单元格上方显示得太高)
cellRect.origin.y = cellRect.origin.y + 40.0
menuController.setTargetRect(cellRect, in: self.tableView)
menuController.setMenuVisible(true, animated: true)
}
}
}
func emailMenuButtonPressed(_ menuController: UIMenuController) {
let menuItem: emailMenuItem = UIMenuController.shared.menuItems![0] as! emailMenuItem
if menuItem.indexPath != nil {
self.resignFirstResponder()
self.sendEmailForEntryAtIndexPath(menuItem.indexPath)
}
}
func sendEmailForEntryAtIndexPath(_ indexPath: IndexPath) {
let play: Play = self.plays[(indexPath as NSIndexPath).section] as! Play
let quotation: Quotation = play.quotations[(indexPath as NSIndexPath).row] as! Quotation
// 在实际使用中,可以调用邮件的API来实现真正的发送邮件
print("用以下语录发送邮件: \(quotation.quotation)")
}
func played() -> NSArray {
if playe == nil {
let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentPath = documentPaths[0]
// print(documentPath)
let filePath1:String = documentPath + "/dataList.plist"
let listData = NSArray(contentsOfFile: filePath1)
let playName = listData!.object(at: 0) as! NSMutableArray
playe = NSMutableArray(capacity: playName.count)
for playDictionary in playName {
let play: Play! = Play()
play.name = (playDictionary as AnyObject).value(forKey: "name") as! String
let quotationDictionaries:NSArray = playDictionary["stationdes"] as! NSArray
let quotations = NSMutableArray(capacity: quotationDictionaries.count)
for quotationDictionary in quotationDictionaries {
let quotationDic:NSDictionary = quotationDictionary as! NSDictionary
let quotation: Quotation = Quotation()
quotation.setValuesForKeys(quotationDic as! [String : AnyObject])
quotations.add(quotation)
}
play.quotations = quotations
playe!.add(play)
}
}
return playe!
}
}
| gpl-3.0 | ea322df929404fdf8d02a4ad035c00b6 | 39.625917 | 236 | 0.634389 | 5.332478 | false | false | false | false |
Pluto-tv/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchViewModel.swift | 1 | 1456 | //
// SearchViewModel.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class SearchViewModel {
// outputs
let rows: Driver<[SearchResultViewModel]>
let subscriptions = DisposeBag()
// public methods
init(searchText: Driver<String>,
selectedResult: Driver<SearchResultViewModel>) {
let $: Dependencies = Dependencies.sharedDependencies
let wireframe = Dependencies.sharedDependencies.wireframe
let API = DefaultWikipediaAPI.sharedAPI
self.rows = searchText
.throttle(0.3, $.mainScheduler)
.distinctUntilChanged()
.map { query in
API.getSearchResults(query)
.retry(3)
.startWith([]) // clears results on new search term
.asDriver(onErrorJustReturn: [])
}
.switchLatest()
.map { results in
results.map {
SearchResultViewModel(
searchResult: $0
)
}
}
selectedResult
.driveNext { searchResult in
wireframe.openURL(searchResult.searchResult.URL)
}
.addDisposableTo(subscriptions)
}
} | mit | 23068cf2b2263f92b074eab652e8ca34 | 25.017857 | 71 | 0.54739 | 5.557252 | false | false | false | false |
NAHCS/UnityKit | UnityKit/GameScene.swift | 1 | 3395 | //
// GameScene.swift
// UnityKit
//
// Created by Jak Tiano on 1/8/17.
// Copyright © 2017 Creationism. All rights reserved.
//
import SpriteKit
import GameplayKit
/**
Provides the base for many features of UnityKit, like managing and updating entities, handling physics
events, and updating the `Time` class.
*/
open class GameScene: SKScene {
// MARK: - Scene Logic
/**
Sets up basic scene functionality. Must call `super.didMove(to: view)` from subclass.
- Parameter view: the `SKView` that was moved to.
*/
override open func didMove(to view: SKView) {
super.didMove(to: view)
self.physicsWorld.gravity = CGVector.zero
self.physicsWorld.contactDelegate = self
backgroundColor = SKColor.black
}
/**
Called once per frame. Updates timing information, and updates all registered entities.
- Parameter currentTime: the current time as a `TimeInterval`.
*/
override open func update(_ currentTime: TimeInterval) {
super.update(currentTime)
// update time
Time.time = currentTime
// update entities
for e in entities {
e.update(deltaTime: Time.deltaTime)
}
}
// MARK: - Entity Management
/// The `GameEntity` objects registered with this scene
public var entities = Set<GameEntity>()
/**
Adds the entity's node with the scene heirarchy, and inserts the entity into a set
of all registered `GameEntity` objects.
- Parameter entity: the `GameEntity` to add to the scene.
*/
public func addEntity(_ entity: GameEntity) {
addChild(entity.node)
entities.insert(entity)
}
/**
Removes the entity's node with the scene heirarchy, and removes the entity from the
set of all registered `GameEntity` objects.
- Parameter entity: the `GameEntity` to add to the scene.
*/
public func removeEntity(_ entity: GameEntity) {
entity.node.removeFromParent()
entities.remove(entity)
}
// TODO: - Touches: Spin this out into dedicated system.
public var touchOrigin: CGPoint?
public var currentTouch: CGPoint?
func touchDown(atPoint pos: CGPoint) {
touchOrigin = pos
currentTouch = pos
}
func touchMoved(toPoint pos: CGPoint) {
currentTouch = pos
}
func touchUp(atPoint pos: CGPoint) {
touchOrigin = nil
currentTouch = nil
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
}
// MARK: - SKPhysicsContactDelegate implementation
extension GameScene : SKPhysicsContactDelegate {
/**
Implementation of method from `SKPhysicsContactDelegate` prototcol. Passes information on to `PhysicsEvents` class.
*/
public func didBegin(_ contact: SKPhysicsContact) {
PhysicsEvents.contactBegan(contact)
}
/**
Implementation of method from `SKPhysicsContactDelegate` prototcol. Passes information on to `PhysicsEvents class.
*/
public func didEnd(_ contact: SKPhysicsContact) {
PhysicsEvents.contactEnded(contact)
}
}
| mit | 8fd1d18a1a747f67459bd3426539c826 | 24.712121 | 117 | 0.72363 | 3.787946 | false | false | false | false |
fleuverouge/File.io-client | FRFileIOClient/FilesBrowser/FilesBrowser.swift | 1 | 32807 | //
// FilesBrowser.swift
// FRFileIOClient
//
// Created by Do Thi Hong Ha on 3/31/16.
// Copyright © 2016 Fleuve Rouge. All rights reserved.
//
import UIKit
import FontAwesome_swift
import LocalAuthentication
import Locksmith
enum FBAction {
case Browse
case SelectFileToUpload
}
enum FBViewOption {
case Grid
case List
var cellIdentifier: String {
get {
switch self {
case .Grid:
return "FileCellGrid"
case .List:
return "FileCellList"
}
}
}
var title: String {
get {
let awesome : FontAwesome
switch self {
case .Grid:
awesome = .Th
case .List:
awesome = .ThList
}
return String.fontAwesomeIconWithName(awesome)
}
}
}
enum FBFileType {
case Image
case Video
case Audio
case Archive
case Text
case Code
case Excel
case Pdf
case Words
case PowerPoint
case Folder
case Other
static func typeFromExtention(extention: String?) -> FBFileType {
if extention == nil {
return .Other
}
switch extention!.lowercaseString {
case "":
return .Folder
case "png", "jpg", "jpeg", "tiff", "bmp":
return .Image
case "mov", "av", "mp4", "mpeg", "mpg", "mpg4", "3gp", "3g2":
return .Video
case "mp3", "m4a", "caf", "caff":
return .Audio
case "txt", ".rtf", "wav":
return .Text
case "xml", "html", "js", "php", "php3", "php4",
"c", "cpp", "cp", "c++", "h", "m", "mm", "cs",
"rb", "sh", "pl", "py", "applescript",
"java", "jav", "class":
return .Code
case "gtar", "tar", "gz", "gzip", "tgz", "zip", "rar":
return .Archive
case "doc", "docx":
return .Words
case "xls", "xlsx":
return .Excel
case "ppt", "pptx":
return .PowerPoint
case "pdf":
return .Pdf
default:
return .Other
}
}
func icon(color: UIColor, size: CGSize) -> UIImage {
var text : FontAwesome
switch self {
case .Image:
text = .FileImageO
case .Video:
text = .FileMovieO
case .Audio:
text = .FileAudioO
case .Archive:
text = .FileArchiveO
case .Text:
text = .FileTextO
case .Code:
text = .FileCodeO
case .Excel:
text = .FileExcelO
case .Pdf:
text = .FilePdfO
case .Words:
text = .FileWordO
case .PowerPoint:
text = .FilePowerpointO
case .Folder:
text = .FolderO
default:
text = .FileO
}
return UIImage.fontAwesomeIconWithName(text, textColor: color, size: size)
}
}
struct FBFile {
var name: String
var extention: String? {
return url.pathExtension
}
var type: FBFileType
var url: NSURL
var size: UInt64
var key: String?
init(fileUrl: NSURL) {
url = fileUrl
name = url.lastPathComponent ?? ""
var rsrc: AnyObject?
do {
try url.getResourceValue(&rsrc, forKey: NSURLIsDirectoryKey)
if let isDirectory = rsrc as? NSNumber where isDirectory == true {
type = .Folder
}
else {
type = FBFileType.typeFromExtention(url.pathExtension)
}
let attr: NSDictionary = try NSFileManager.defaultManager().attributesOfItemAtPath(url.path!)
size = attr.fileSize()
}
catch {
type = FBFileType.typeFromExtention(url.pathExtension)
size = 0
print("Generate file from URL: \(url)\n<ERROR> \(error)")
}
key = NSUserDefaults.standardUserDefaults().stringForKey(LocalKey.FileKey + name)
}
}
class FilesBrowser: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var viewOption = FBViewOption.Grid
var files = [FBFile]()
var imageSize = CGSizeZero
var cellReuseIdentifier = FBViewOption.Grid.cellIdentifier
var action = FBAction.Browse
var needAuthenticate = false
var locked = false {
didSet {
lockItem.title = String.fontAwesomeIconWithName(locked ? .Unlock : .Lock)
}
}
@IBOutlet weak var collectionView: UICollectionView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBOutlet weak var emptyView: UIStackView!
// private let menu = XXXRoundMenuButton()
@IBOutlet weak var menu: UIStackView!
private var lockItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
// Do any additional setup after loading the view.
let refreshControl = UIRefreshControl()
refreshControl.tintColor = ColorTemplate.Text
refreshControl.addTarget(self, action: #selector(FilesBrowser.loadFilesList(_:)), forControlEvents: .ValueChanged)
collectionView.addSubview(refreshControl)
collectionView.bounces = true
collectionView.alwaysBounceVertical = true
automaticallyAdjustsScrollViewInsets = false
collectionView.contentInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
let attributes = [NSFontAttributeName: UIFont.fontAwesomeOfSize(22)] as Dictionary!
let refreshItem = UIBarButtonItem(title: String.fontAwesomeIconWithName(.Refresh), style: .Plain, target: self, action: #selector(FilesBrowser.loadFilesList(_:)))
refreshItem.setTitleTextAttributes(attributes, forState: .Normal)
let styleItem = UIBarButtonItem(title: FBViewOption.List.title, style: .Plain, target: self, action: #selector(FilesBrowser.switchViewOption(_:)))
styleItem.setTitleTextAttributes(attributes, forState: .Normal)
lockItem = UIBarButtonItem(title: "", style: .Plain, target: self, action: #selector(FilesBrowser.didTapLockItem))
lockItem.setTitleTextAttributes(attributes, forState: .Normal)
navigationItem.rightBarButtonItems = [styleItem, refreshItem, lockItem]
view.backgroundColor = ColorTemplate.MainBackground
collectionView.backgroundColor = ColorTemplate.MainBackground
emptyView.backgroundColor = ColorTemplate.MainBackground
for subview in emptyView.subviews {
if let label = subview as? UILabel {
label.textColor = ColorTemplate.Text
}
else if let iv = subview as? UIImageView {
iv.image = UIImage.fontAwesomeIconWithName(.Inbox, textColor: ColorTemplate.Text, size: CGSizeMake(UIScreen.width / 4, UIScreen.width / 4))
}
}
let items : [FontAwesome] = [FontAwesome.ShareSquareO, FontAwesome.Upload, FontAwesome.Edit, FontAwesome.TrashO, .Hashtag]
for i in 101...105 {
if let button = menu.subviewWithTag(i) as? UIButton {
let item = items[i - 101]
button.titleLabel?.font = UIFont.fontAwesomeOfSize(20)
button.setTitle(String.fontAwesomeIconWithName(item), forState: .Normal)
button.setCornerRadius(22)
button.backgroundColor = ColorTemplate.MainTint
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
switch item {
case .ShareSquareO:
button.addTarget(self, action: #selector(FilesBrowser.didTapShare), forControlEvents: .TouchUpInside)
case .Upload:
button.addTarget(self, action: #selector(FilesBrowser.didTapUpload), forControlEvents: .TouchUpInside)
case .Edit:
button.addTarget(self, action: #selector(FilesBrowser.didTapRename), forControlEvents: .TouchUpInside)
case .TrashO:
button.addTarget(self, action: #selector(FilesBrowser.didTapDelete), forControlEvents: .TouchUpInside)
case .Hashtag:
button.addTarget(self, action: #selector(FilesBrowser.toggleMenu), forControlEvents: .TouchUpInside)
default:
break
}
}
}
for i in 101...104 {
menu.subviewWithTag(i)?.hidden = true
}
menu.hidden = true
updateItemSize()
locked = NSUserDefaults.standardUserDefaults().boolForKey("hasLoginKey")
if locked == true {
needAuthenticate = true
}
else {
loadFilesList(nil)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (needAuthenticate) {
authenticateUser(successHandler: {[weak self] in
self?.needAuthenticate = false
self?.loadFilesList(nil)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return files.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(viewOption.cellIdentifier, forIndexPath: indexPath) as! FileCell
let file = files[indexPath.item]
cell.fileNameLabel.text = file.name
cell.fileImageView.image = FBFileType.Other.icon(cell.fileImageView.tintColor, size: imageSize)
if (file.type == .Image) {
if let image = UIImage(contentsOfFile: file.url.path!) {
cell.fileImageView.image = image
}
else {
cell.fileImageView.image = imageForCell(cell, fileType: .Image)
}
}
else {
cell.fileImageView.image = imageForCell(cell, fileType: file.type)
}
if (file.size < 1000) {
cell.fileSizeLabel.text = "\(file.size) B"
}
else if (file.size < 1000000) {
cell.fileSizeLabel.text = String.localizedStringWithFormat("%.2f kB", Double(file.size)/1000)
}
else if (file.size < 1000000000) {
cell.fileSizeLabel.text = String.localizedStringWithFormat("%.2f MB", Double(file.size)/1000000)
}
else {
cell.fileSizeLabel.text = String.localizedStringWithFormat("%.2f GB", Double(file.size)/1000000000)
}
return cell
}
func imageForCell(cell: FileCell, fileType: FBFileType) -> UIImage {
return fileType.icon(cell.fileImageView.tintColor, size: imageSize)
}
func imageForCell(cell: FileCell, fileExtension: String?) -> UIImage {
return imageForCell(cell, fileType: FBFileType.typeFromExtention(fileExtension))
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if (action == .SelectFileToUpload) {
performUploadFile(files[indexPath.item])
}
else {
menu.hidden = false
}
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if (action == .Browse) {
if collectionView.visibleCells().count == 0 {
hideMenu()
menu.hidden = true
}
}
}
//MARK: -
func loadFilesList(sender: AnyObject?) {
guard needAuthenticate == false else {
authenticateUser(successHandler: {[weak self] in
self?.needAuthenticate = false
self?.loadFilesList(sender)
})
return
}
defer {
collectionView.hidden = files.count == 0
emptyView.hidden = !collectionView.hidden
}
if let rc = sender as? UIRefreshControl {
rc.endRefreshing()
}
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
do {
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
// print(files)
files = [FBFile]()
for fileURL in directoryContents {
try fileURL.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey)
files.append(FBFile(fileUrl: fileURL))
}
collectionView.reloadData()
} catch let error as NSError {
print(error.localizedDescription)
}
// if you want to filter the directory contents you can do like this:
// do {
// let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
// print(directoryUrls)
// let mp3Files = directoryUrls.filter{ $0.pathExtension == "mp3" }.map{ $0.lastPathComponent }
// print("MP3 FILES:\n" + mp3Files.description)
// } catch let error as NSError {
// print(error.localizedDescription)
// }
}
func switchViewOption(sender: UIBarButtonItem) {
switch viewOption {
case .Grid:
viewOption = .List
sender.title = String.fontAwesomeIconWithName(.Th)
case .List:
viewOption = .Grid
sender.title = String.fontAwesomeIconWithName(.ThList)
}
updateItemSize()
collectionView.reloadData()
}
func updateItemSize() {
let cellSize: CGSize
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
switch viewOption {
case .List:
let width = UIScreen.width - collectionView.contentInset.left - collectionView.contentInset.right - layout.sectionInset.left - layout.sectionInset.right
let height = min(120, 90 * UIScreen.scaleFactor)
cellSize = CGSize(width: round(width), height: round(height))
let imageHeight = height - 42
imageSize = CGSize(width: imageHeight, height: imageHeight)
case .Grid:
let width = min(150, 130 * UIScreen.scaleFactor)
let height = width/130 * 180
cellSize = CGSize(width: round(width), height: round(height))
let imageWidth = width * 0.7
imageSize = CGSize(width: imageWidth, height: imageWidth)
}
layout.itemSize = cellSize
}
func performUploadFile(file: FBFile) {
let uploadVC = UploadVC(file: file)
uploadVC.showInView(self)
}
// MARK: - Action
func didTapUpload() {
if let indexPath = collectionView.indexPathsForSelectedItems()?.first {
performUploadFile(files[indexPath.item])
}
}
func didTapShare() {
if let indexPath = collectionView.indexPathsForSelectedItems()?.first {
let file = files[indexPath.item]
var activityItems = [AnyObject]()
if let key = file.key {
activityItems.append(key)
}
var gotData = false
if (file.type == .Image) {
if let image = UIImage(contentsOfFile: file.url.path!) {
activityItems.append(image)
gotData = true
}
}
if (!gotData) {
if let data = NSData(contentsOfFile: file.url.path!) {
activityItems.append(data)
}
}
// let activityItems = [NSURL(string: fileUrl)!]
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
if let ppc = activityVC.popoverPresentationController {
ppc.sourceView = self.menu
}
self.presentViewController(activityVC, animated: true, completion: nil)
}
}
func didTapRename() {
if let indexPath = collectionView.indexPathsForSelectedItems()?.first {
let file = files[indexPath.item]
var inputTextField: UITextField?
let namePrompt = UIAlertController(title: "Rename file", message: "Please file name", preferredStyle: UIAlertControllerStyle.Alert)
namePrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
namePrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {[weak self] (action) -> Void in
if let itf = inputTextField,
let text = itf.text where text.characters.count != 0 {
var newFilename = text
if let ext = file.extention {
newFilename = text + "." + ext
}
let newPath = file.url.path!.stringByReplacingOccurrencesOfString(file.name, withString: "").stringByAppendingString(newFilename)
do {
try NSFileManager.defaultManager().moveItemAtPath(file.url.path!, toPath: newPath)
let urlStr = file.url.absoluteString.stringByReplacingOccurrencesOfString(file.name, withString: "").stringByAppendingString(newFilename)
if let url = NSURL(string: urlStr) {
self?.files[indexPath.item] = FBFile(fileUrl: url)
FRQueue.Main.execute(closure: {
self?.collectionView.reloadItemsAtIndexPaths([indexPath])
})
}
}
catch let error as NSError {
print("Rename file <ERROR> \(error)")
FRQueue.Main.execute(closure: {
self?.showError(error.localizedDescription)
})
}
}
}))
namePrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
var defaultFilename = file.name
if let ext = file.extention {
defaultFilename = file.name.stringByReplacingOccurrencesOfString("." + ext, withString: "")
}
textField.placeholder = defaultFilename
inputTextField = textField
})
namePrompt.view.setNeedsLayout()
presentViewController(namePrompt, animated: true, completion: nil)
}
}
func didTapDelete() {
if let indexPath = collectionView.indexPathsForSelectedItems()?.first {
let file = files[indexPath.item]
let alert = UIAlertController(title: "Delete file", message: "Do you want to delete file \(file.name)?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: { [weak self] (_) in
if NSFileManager.defaultManager().fileExistsAtPath(file.url.path!) {
do {
try NSFileManager.defaultManager().removeItemAtPath(file.url.path!)
print("Deleted file \(file.url.path!)")
if let me = self {
try synchronized(me, block: {
me.files.removeAtIndex(indexPath.item)
FRQueue.Main.execute(closure: {
me.collectionView.deleteItemsAtIndexPaths([indexPath])
})
})
}
}
catch let error as NSError {
print("<ERROR> \(error)")
FRQueue.Main.execute(closure: {
self?.showError(error.localizedDescription)
})
}
}
}))
presentViewController(alert, animated: true, completion: nil)
}
}
func showError(message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
private var isMenuShown = false
func toggleMenu() {
if (isMenuShown) {
hideMenu()
}
else {
showMenu()
}
}
func hideMenu() {
if (!isMenuShown) {
return
}
isMenuShown = false
hideButton(101)
}
func hideButton(tag: NSNumber) {
// print("hide button \(tag)")
let tagInt = tag.integerValue
if let button = self.menu.viewWithTag(tagInt) {
UIView.animateWithDuration(0.2, animations: {
button.hidden = true
})
}
if (tagInt < 104) {
performSelector(#selector(FilesBrowser.hideButton(_:)), withObject: NSNumber(integer: tagInt+1), afterDelay: 0.1)
}
}
func showMenu() {
if (isMenuShown) {
return
}
isMenuShown = true
showButton(104)
}
func showButton(tag: NSNumber) {
// print("show button \(tag)")
let tagInt = tag.integerValue
if let button = self.menu.viewWithTag(tagInt) {
UIView.animateWithDuration(0.2, animations: {
button.hidden = false
})
}
if (tagInt > 101) {
performSelector(#selector(FilesBrowser.showButton(_:)), withObject: NSNumber(integer: tagInt-1), afterDelay: 0.1)
}
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier.containsString("showImage") {
return false
}
if identifier.containsString("peekImage") {
if let cell = sender as? FileCell,
let idxPath = collectionView.indexPathForCell(cell)
where files[idxPath.item].type == .Image {
return true
}
return false
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier where identifier.containsString("peekImage"),
let cell = sender as? FileCell,
let idxPath = collectionView.indexPathForCell(cell)
where files[idxPath.item].type == .Image,
let iv = segue.destinationViewController.view.viewWithTag(101) as? UIImageView{
iv.image = cell.fileImageView.image
}
else {
super.prepareForSegue(segue, sender: sender)
}
}
//MARK: - Security
func didTapLockItem() {
if (locked) {
authenticateUser("Remove passcode", successHandler: { [weak self] in
do {
try Locksmith.deleteDataForUserAccount("FileBrowser")
NSUserDefaults.standardUserDefaults().removeObjectForKey("hasLoginKey")
NSUserDefaults.standardUserDefaults().synchronize()
self?.locked = false
}
catch (let error as NSError) {
print("Error: \(error.localizedDescription)")
self?.showError("An error occured. Please try again later!")
}
})
}
else {
showSetPasscodeAlert()
}
}
func authenticateUser(reasonString: String = "Authentication is needed to access your files.", successHandler: ()->()) {
// Get the local authentication context.
let context = LAContext()
// Declare a NSError variable.
var error: NSError?
// Set the reason string that will appear on the authentication alert.
// Check if the device can evaluate the policy.
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
[context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: {[weak self] (success: Bool, evalPolicyError: NSError?) -> Void in
if success {
successHandler()
}
else{
// If authentication failed then show a message to the console with a short description.
// In case that the error is a user fallback, then show the password alert view.
print(evalPolicyError?.localizedDescription)
let logError: String
switch LAError(rawValue: evalPolicyError!.code) {
case .Some(let error):
switch error {
case .UserCancel:
logError = "Authentication was cancelled by the user"
case .UserFallback:
logError = "User selected to enter custom password"
FRQueue.Main.execute(closure: {
self?.showPasswordAlert(successHandler: successHandler)
})
case .SystemCancel:
logError = "Authentication was cancelled by the system"
default:
logError = "Authentication failed"
FRQueue.Main.execute(closure: {
self?.showPasswordAlert(successHandler: successHandler)
})
}
default:
logError = "Unknown error"
FRQueue.Main.execute(closure: {
self?.showPasswordAlert(successHandler: successHandler)
})
}
print(logError)
}
})]
}
if let error = error {
print("<ERROR> " + error.localizedDescription)
let logError: String
switch LAError(rawValue: error.code) {
case .Some(let error):
switch error {
case .TouchIDNotEnrolled:
logError = "TouchID is not enrolled"
case .PasscodeNotSet:
logError = "A passcode has not been set"
default:
logError = "TouchID not available"
}
default:
logError = "Unknown error"
}
print(logError)
showPasswordAlert(successHandler: successHandler)
}
}
func showPasswordAlert(message: String = "Please enter your passcode", successHandler: ()->()) {
var inputTextField: UITextField?
let passwordAlert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert)
passwordAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default) {[weak self] (_) in
if let itf = inputTextField,
let pw = itf.text where pw.characters.count != 0 {
if let data = Locksmith.loadDataForUserAccount("FileBrowser"),
let passcode = data["passcode"] as? String where passcode == pw {
successHandler()
}
else {
self?.showError("Incorrect passcode")
}
}
else {
self?.showPasswordAlert(successHandler: successHandler)
}
})
passwordAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
passwordAlert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.secureTextEntry = true
textField.keyboardType = UIKeyboardType.NumberPad
inputTextField = textField
})
passwordAlert.view.setNeedsLayout()
presentViewController(passwordAlert, animated: true, completion: nil)
}
func showSetPasscodeAlert() {
var inputTextField: UITextField?
let passwordAlert = UIAlertController(title: nil, message: "Please enter your desired passcode", preferredStyle: UIAlertControllerStyle.Alert)
passwordAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default) {[weak self] (_) in
if let itf = inputTextField,
let pw = itf.text where pw.characters.count != 0 {
do {
try Locksmith.saveData(["passcode": pw], forUserAccount: "FileBrowser")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasLoginKey")
NSUserDefaults.standardUserDefaults().synchronize()
self?.locked = true
}
catch (let error as NSError) {
print("Error: \(error.localizedDescription)")
self?.showError("An error occured. Please try again later!")
}
}
else {
self?.showSetPasscodeAlert()
}
})
passwordAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
passwordAlert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.secureTextEntry = true
textField.keyboardType = UIKeyboardType.NumberPad
inputTextField = textField
})
passwordAlert.view.setNeedsLayout()
presentViewController(passwordAlert, animated: true, completion: nil)
}
}
| mit | 591680d0821997e0dbf7abc64fe64590 | 38.241627 | 191 | 0.57078 | 5.5821 | false | false | false | false |
jphacks/TK_21 | ios/Alamofire/Example/DetailViewController.swift | 58 | 6599 | // DetailViewController.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import UIKit
class DetailViewController: UITableViewController {
enum Sections: Int {
case Headers, Body
}
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
title = request?.description
refreshControl?.endRefreshing()
headers.removeAll()
body = nil
elapsedTime = nil
}
}
var headers: [String: String] = [:]
var body: String?
var elapsedTime: NSTimeInterval?
var segueIdentifier: String?
static let numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter
}()
// MARK: View Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
refreshControl?.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
// MARK: IBActions
@IBAction func refresh() {
guard let request = request else {
return
}
refreshControl?.beginRefreshing()
let start = CACurrentMediaTime()
request.responseString { response in
let end = CACurrentMediaTime()
self.elapsedTime = end - start
if let response = response.response {
for (field, value) in response.allHeaderFields {
self.headers["\(field)"] = "\(value)"
}
}
if let segueIdentifier = self.segueIdentifier {
switch segueIdentifier {
case "GET", "POST", "PUT", "DELETE":
self.body = response.result.value
case "DOWNLOAD":
self.body = self.downloadedBodyString()
default:
break
}
}
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
private func downloadedBodyString() -> String {
let fileManager = NSFileManager.defaultManager()
let cachesDirectory = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0]
do {
let contents = try fileManager.contentsOfDirectoryAtURL(
cachesDirectory,
includingPropertiesForKeys: nil,
options: .SkipsHiddenFiles
)
if let
fileURL = contents.first,
data = NSData(contentsOfURL: fileURL)
{
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let prettyData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
if let prettyString = NSString(data: prettyData, encoding: NSUTF8StringEncoding) as? String {
try fileManager.removeItemAtURL(fileURL)
return prettyString
}
}
} catch {
// No-op
}
return ""
}
}
// MARK: - UITableViewDataSource
extension DetailViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Sections(rawValue: section)! {
case .Headers:
return headers.count
case .Body:
return body == nil ? 0 : 1
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch Sections(rawValue: indexPath.section)! {
case .Headers:
let cell = tableView.dequeueReusableCellWithIdentifier("Header")!
let field = headers.keys.sort(<)[indexPath.row]
let value = headers[field]
cell.textLabel?.text = field
cell.detailTextLabel?.text = value
return cell
case .Body:
let cell = tableView.dequeueReusableCellWithIdentifier("Body")!
cell.textLabel?.text = body
return cell
}
}
}
// MARK: - UITableViewDelegate
extension DetailViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
return ""
}
switch Sections(rawValue: section)! {
case .Headers:
return "Headers"
case .Body:
return "Body"
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch Sections(rawValue: indexPath.section)! {
case .Body:
return 300
default:
return tableView.rowHeight
}
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if Sections(rawValue: section) == .Body, let elapsedTime = elapsedTime {
let elapsedTimeText = DetailViewController.numberFormatter.stringFromNumber(elapsedTime) ?? "???"
return "Elapsed Time: \(elapsedTimeText) sec"
}
return ""
}
}
| mit | 523ec009c696442113fee9d05f932ce3 | 31.338235 | 118 | 0.616038 | 5.571791 | false | false | false | false |
codefellows/sea-c40-iOS | Sample Code/GuestlectureProject/GuestlectureProject/AnimationViewController.swift | 1 | 2021 | //
// AnimationViewController.swift
// GuestlectureProject
//
// Created by Adam Wallraff on 6/29/15.
// Copyright (c) 2015 Adam Wallraff. All rights reserved.
//
import UIKit
class AnimationViewController: UIViewController {
@IBOutlet var myRedView: UIView!
@IBOutlet var myBlueView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
myRedView.alpha = 0.0
UIView.animateWithDuration(1.5, animations: { () -> Void in
self.myRedView.alpha = 1.0
self.myBlueView.backgroundColor = UIColor.greenColor()
})
let duration = 1.5
let delay = 1.5
let springDamping : CGFloat = 0.75
let springVelocity : CGFloat = 0.9
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
newView.backgroundColor = UIColor.blackColor()
newView.layer.cornerRadius = 25.0
newView.alpha = 0.0
self.view.addSubview(newView)
UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: springDamping, initialSpringVelocity: springVelocity, options: nil, animations: { () -> Void in
newView.center = CGPoint(x: self.view.center.x, y: self.view.center.y)
newView.alpha = 1.0
}) { (finished) -> Void in
self.myBlueView.alpha = 0.0
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3e7737a904dd90978a746fe414664fb8 | 25.946667 | 174 | 0.655121 | 4.393478 | false | false | false | false |
vivekvpandya/GetSwifter | GetSwifter/FunChallengesTVC.swift | 2 | 8124 | //
// RealWorldChallengesTVC.swift
// GetSwifter
//
//
import UIKit
import Alamofire
class FunChallengesTVC: UITableViewController,UIAlertViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate{
// URL to get details in JSON format
let serviceEndPoint = "http://tc-search.herokuapp.com/challenges/v2/search?q=technologies:Swift%20AND%20-status:(Completed%20OR%20Cancelled%20-%20Failed%20Screening)"
var funChallenges :[NSDictionary] = [] {
didSet{
self.tableView!.reloadData()
}
}
var searchResult : [NSDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
getFunChallenges()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.searchResult.count
}
else{
return funChallenges.count
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
let cell = self.tableView!.dequeueReusableCellWithIdentifier("funChallenge", forIndexPath: indexPath!) as ChallengeDetailsTableViewCell
var details : NSDictionary
var source : NSDictionary
if tableView == self.searchDisplayController?.searchResultsTableView{
details = searchResult[indexPath!.row] as NSDictionary
}
else{
details = funChallenges[indexPath!.row] as NSDictionary
}
source = details.objectForKey("_source") as NSDictionary
var dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSz"
dateFormater.timeZone = NSTimeZone(name:"GMT")
var opDateFormater : NSDateFormatter = NSDateFormatter()
opDateFormater.timeZone = NSTimeZone(name:"GMT")
opDateFormater.dateStyle=NSDateFormatterStyle.MediumStyle
opDateFormater.timeStyle = NSDateFormatterStyle.LongStyle
if let challengeName = source.objectForKey("challengeName") as? NSString {
cell.challenge.text = challengeName
}
if let technology = source.objectForKey("technologies") as? NSArray {
let technologyString = technology.componentsJoinedByString(",")
cell.technologyLabel.text = technologyString
}
if let platform = source.objectForKey("platforms") as? NSArray {
let platfromString = platform.componentsJoinedByString(",")
cell.platformLabel.text = platfromString
}
if let regEnd = source.objectForKey("registrationEndDate") as? NSString {
let regEndDate = dateFormater.dateFromString(regEnd)
let regEndDateString = opDateFormater.stringFromDate(regEndDate!)
cell.regEndLabel.text = regEndDateString
}
if let subEnd = source.objectForKey("submissionEndDate") as? NSString {
let subEndDate = dateFormater.dateFromString(subEnd)
let subEndDateString = opDateFormater.stringFromDate(subEndDate!)
cell.subEndLabel.text = subEndDateString
}
if let registrants = source.objectForKey("numRegistrants") as? Int {
cell.registrantsLabel.text = "\(registrants)"
}
if let submisions = source.objectForKey("numSubmissions") as? Int {
cell.submissionsLabel.text = "\(submisions)"
}
if let totalPrize = source.objectForKey("totalPrize") as? Int{
cell.totalPrize.text = "$ \(totalPrize)"
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var destinationVC : ChallengeDetailsVC = segue.destinationViewController as ChallengeDetailsVC
var details : NSDictionary
if (self.searchDisplayController?.active == true) {
let indexPath : NSIndexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow()!
details = self.searchResult[indexPath.row] as NSDictionary
}
else{
let indexPath :NSIndexPath = self.tableView.indexPathForSelectedRow()!
details = funChallenges[indexPath.row] as NSDictionary
}
var source = details.objectForKey("_source") as NSDictionary
var challengeID = details.objectForKey("_id") as NSString
destinationVC.challengeID = challengeID
}
func getFunChallenges() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
Alamofire.request(.GET,serviceEndPoint, encoding : .JSON).responseJSON{(request,response,JSON,error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error == nil {
if response?.statusCode == 200 {
self.funChallenges = JSON as [NSDictionary]
}
else{
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
println(response?.statusCode)
}
}
else{
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
println(error)
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 241.0
}
@IBAction func refreshTableView(sender: AnyObject) {
getFunChallenges()
self.refreshControl?.endRefreshing()
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
self.searchResult = self.funChallenges.filter({( challenge: NSDictionary) -> Bool in
let source = challenge.objectForKey("_source") as NSDictionary
let challangeName = source.objectForKey("challengeName") as NSString
let stringMatch = challangeName.rangeOfString(searchText)
return (stringMatch.length != 0) && true
})
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
return true
}
}
| mit | bafddd2fe7ec06567ad95833f5c3a753 | 29.656604 | 170 | 0.57644 | 6.283063 | false | false | false | false |
artursDerkintis/Starfly | Starfly/SFBookmarksController.swift | 1 | 1282 | //
// SFBookmarksController.swift
// Starfly
//
// Created by Arturs Derkintis on 12/12/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
class SFBookmarksController: UIViewController {
var tableView : UITableView!
var bookmarksProvider : SFBookmarksProvider!
override func viewDidLoad() {
super.viewDidLoad()
bookmarksProvider = SFBookmarksProvider()
tableView = UITableView(frame: .zero)
bookmarksProvider.tableView = tableView
tableView.registerClass(SFBookmarksCell.self, forCellReuseIdentifier: bookmarksCell)
tableView.backgroundColor = .clearColor()
tableView.separatorColor = .clearColor()
addSubviewSafe(tableView)
tableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.width.equalTo(768)
make.bottom.equalTo(0)
make.centerX.equalTo(self.view.snp_centerX)
}
tableView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 100, right: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func load() {
bookmarksProvider.loadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
}
| mit | 62df764fc6066c2dfd848bb0cb34dddf | 21.473684 | 86 | 0.701795 | 4.255814 | false | false | false | false |
ninjaprawn/iFW | iOS/iFW/RSSParser.swift | 1 | 5560 |
import UIKit
// TODO [DAC] this mixes feed and feed item tags, they should be separated.
enum NodeElement : String {
case Item = "item"
case Title = "title"
case Link = "link"
case GUID = "guid"
case PublicationDate = "pubDate"
case Description = "description"
case ContentType = "content:encoded"
case Language = "language"
case Property = "rdctv:property"
case ParallaxImage = "rdctv:image"
case LastBuildDate = "lastBuildDate"
case Generator = "generator"
case Copyright = "copyright"
// Specific to Wordpress:
case CommentsLink = "comments"
case CommentsCount = "slash:comments"
case CommentRSSLink = "wfw:commentsRSS"
case Author = "dc:creator"
case Category = "category"
}
extension String {
func rssNodeElement() -> NodeElement? {
return NodeElement(rawValue: self)
}
}
class RSSParser: NSObject, NSXMLParserDelegate {
class func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
let rssParser: RSSParser = RSSParser()
rssParser.parseFeedForRequest(request, callback: callback)
}
static var sharedURLSession : NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var callbackClosure: ((feed: RSSFeed?, error: NSError?) -> Void)?
var currentElement: String = ""
var currentItem: RSSItem?
var feed: RSSFeed = RSSFeed()
func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
let theTask = RSSParser.sharedURLSession.dataTaskWithRequest(request) { (data, response, error) -> Void in
if ((error) != nil)
{
callback(feed: nil, error: error)
}
else
{
self.callbackClosure = callback
let parser : NSXMLParser = NSXMLParser(data: data!)
parser.delegate = self
parser.shouldResolveExternalEntities = false
parser.parse()
}
}
theTask.resume()
}
// MARK: NSXMLParserDelegate
func parserDidStartDocument(parser: NSXMLParser)
{
}
func parserDidEndDocument(parser: NSXMLParser)
{
if let closure = self.callbackClosure
{
closure(feed: self.feed, error: nil)
}
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if let e = elementName.rssNodeElement() where e == .Item
{
self.currentItem = RSSItem()
}
self.currentElement = ""
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
// Need to have an element that we know how to handle
guard let element = elementName.rssNodeElement() else { return }
if let e = elementName.rssNodeElement() where e == .Item
{
if let item = self.currentItem
{
self.feed.items.append(item)
}
self.currentItem = nil
return
}
if let item = self.currentItem
{
switch element {
case .Title :
item.title = self.currentElement
case .Link:
item.addLink(self.currentElement)
case .Property:
item.addPropertyID(self.currentElement)
case .GUID:
item.guid = self.currentElement
case .PublicationDate:
item.setPubDate1(self.currentElement)
case .Description:
item.itemDescription = self.currentElement
case .ContentType:
item.content = self.currentElement
case .CommentsLink:
item.setCommentsLink1(self.currentElement)
case .CommentsCount:
item.commentsCount = Int(self.currentElement)
case .CommentRSSLink:
item.setCommentRSSLink1(self.currentElement)
case .Author:
item.author = self.currentElement
case .Category:
item.categories.append(self.currentElement)
default:
print("Unmatched case: \(element)")
}
}
else
{
switch element {
case .Title :
feed.title = self.currentElement
case .Link:
feed.setLink1(self.currentElement)
case .Language:
feed.language = self.currentElement
case .LastBuildDate:
feed.setlastBuildDate(self.currentElement)
case .Description:
feed.feedDescription = self.currentElement
case .Generator:
feed.generator = self.currentElement
case .Copyright:
feed.copyright = self.currentElement
default:
print("Unmatched case: \(element)")
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
self.currentElement += string
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if let closure = self.callbackClosure
{
closure(feed: nil, error: parseError)
}
}
} | mit | 36c0ed46ee401157ec7b535e9da6e8b5 | 27.372449 | 173 | 0.580396 | 5.077626 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Filters/Water.swift | 1 | 2465 | //
// Water.swift
// Pods
//
// Created by Mohssen Fathi on 4/9/16.
//
//
import UIKit
struct WaterUniforms: Uniforms {
var time: Float = 0.0
var speed: Float = 0.5
var frequency: Float = 0.5
var intensity: Float = 0.5
var emboss: Float = 0.5
var delta: Float = 0.5
var intence: Float = 0.5
}
public
class Water: Filter {
var uniforms = WaterUniforms()
@objc public var speed: Float = 0.5 {
didSet {
clamp(&speed, low: 0, high: 1)
}
}
@objc public var frequency: Float = 0.5 {
didSet {
clamp(&frequency, low: 0, high: 1)
}
}
@objc public var intensity: Float = 0.5 {
didSet {
clamp(&intensity, low: 0, high: 1)
}
}
@objc public var emboss: Float = 0.5 {
didSet {
clamp(&emboss, low: 0, high: 1)
}
}
@objc public var delta: Float = 0.5 {
didSet {
clamp(&delta, low: 0, high: 1)
}
}
@objc public var intence: Float = 0.5 {
didSet { clamp(&intence, low: 0, high: 1) }
}
public init() {
super.init(functionName: "water")
title = "Water"
properties = [Property(key: "speed", title: "Speed" ),
Property(key: "frequency", title: "Frequency"),
Property(key: "intensity", title: "Intensity"),
Property(key: "emboss", title: "Enboss" ),
Property(key: "delta", title: "Delta" ),
Property(key: "intence", title: "Intence" )]
update()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func process() {
update()
super.process()
needsUpdate = true
}
override func update() {
if self.input == nil { return }
uniforms.speed = speed * 0.5 + 0.1
uniforms.intensity = Tools.convert(intensity, oldMin: 0, oldMax: 1, newMin: 2.0, newMax: 6.0)
uniforms.emboss = emboss + 0.5
uniforms.frequency = frequency * 6.0 + 3.0
uniforms.delta = delta * 60.0 + 30.0
uniforms.intence = intence * 500.0 + 400.0
uniforms.time += 1.0/60.0
updateUniforms(uniforms: uniforms)
}
override public var continuousUpdate: Bool {
return true
}
}
| mit | 93fb1b43c5ca1b10009303bf9742a660 | 24.153061 | 101 | 0.506288 | 3.798151 | false | false | false | false |
zsheikh-systango/WordPower | Skeleton/Skeleton/NetworkManager/Services/WordInterface.swift | 1 | 2322 | //
// CategoryInterface.swift
// WordPower
//
// Created by BestPeers on 05/06/17.
// Copyright © 2017 BestPeers. All rights reserved.
//
import UIKit
class WordInterface: Interface {
public func getWordInformation(request: WordRequest, completion: @escaping CompletionHandler) {
interfaceBlock = completion
RealAPI().getObject(request: request) { (success, response) in
self.parseSuccessResponse(request:request, response:response as AnyObject)
}
}
public func getTranslationInformation(request: WordRequest, completion: @escaping CompletionHandler) {
interfaceBlock = completion
NetworkAPIClient().getTranslationObject(request: request) { (success, response) in
self.parseSuccessResponse(request:request, response:response as AnyObject)
}
}
public func getTranslationLangs(request: WordRequest, completion: @escaping CompletionHandler) {
interfaceBlock = completion
NetworkAPIClient().getLangsTranslationObject(request: request) { (success, response) in
self.parseGetLangsSuccessResponse(request:request, response:response as AnyObject)
}
}
// MARK: Parse Response
func parseSuccessResponse(request:WordRequest, response: AnyObject?) -> Void {
if validateResponse(response: response!){
let responseDict = response as! Dictionary<String, Any>
guard let translatedText = responseDict["text"] else {
failureResponse()
return
}
let responseList = translatedText as! Array<AnyObject>
if responseDict.count > 0{
interfaceBlock!(true, responseList[0] as? String)
return
}
failureResponse()
}
}
func parseGetLangsSuccessResponse(request:WordRequest, response: AnyObject?) -> Void {
if validateResponse(response: response!){
let responseDict = response as! Dictionary<String, Any>
guard let langs = responseDict["langs"] as? Dictionary<String,String> else {
failureResponse()
return
}
interfaceBlock!(true, langs)
}
}
}
| mit | d173abbba163ff34324258ae4f54138c | 33.641791 | 106 | 0.621715 | 5.360277 | false | false | false | false |
dsonara/DSImageCache | DSImageCache/Classes/Core/ImageCache.swift | 1 | 25032 | //
// ImageCache.swift
// DSImageCache
//
// Created by Dipak Sonara on 29/03/17.
// Copyright © 2017 Dipak Sonara. All rights reserved.
import UIKit
public extension Notification.Name {
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `DSImageCacheDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
*/
public static var DSImageCacheDidCleanDiskCache = Notification.Name.init("com.company.DSImageCache.DSImageCacheDidCleanDiskCache")
}
/**
Key for array of cleaned hashes in `userInfo` of `DSImageCacheDidCleanDiskCacheNotification`.
*/
public let DSImageCacheDiskCacheCleanedHashKey = "com.company.DSImageCache.cleanedHash"
/// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
public typealias RetrieveImageDiskTask = DispatchWorkItem
/**
Cache type of a cached image.
- None: The image is not cached yet when retrieving it.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case none, memory, disk
}
/// `ImageCache` represents both the memory and disk cache system of DSImageCache.
/// While a default image cache object will be used if you prefer the extension methods of DSImageCache,
/// you can create your own cache object and configure it as your need. You could use an `ImageCache`
/// object to manipulate memory and disk cache for DSImageCache.
open class ImageCache {
//Memory
fileprivate let memoryCache = NSCache<NSString, AnyObject>()
/// The largest cache cost of memory cache. The total cost is pixel count of
/// all cached images in memory.
/// Default is unlimited. Memory cache will be purged automatically when a
/// memory warning notification is received.
open var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
fileprivate let ioQueue: DispatchQueue
fileprivate var fileManager: FileManager!
///The disk cache location.
open let diskCachePath: String
/// The default file extension appended to cached files.
open var pathExtension: String?
/// The longest time duration in second of the cache being stored in disk.
/// Default is 1 week (60 * 60 * 24 * 7 seconds).
/// Setting this to a negative value will make the disk cache never expiring.
open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
/// The largest disk size can be taken for the cache. It is the total
/// allocated size of cached files in bytes.
/// Default is no limit.
open var maxDiskCacheSize: UInt = 0
fileprivate let processQueue: DispatchQueue
/// The default cache.
public static let `default` = ImageCache(name: "default")
/// Closure that defines the disk cache path from a given path and cacheName.
public typealias DiskCachePathClosure = (String?, String) -> String
/// The default DiskCachePathClosure
public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String {
let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return (dstPath as NSString).appendingPathComponent(cacheName)
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
- parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name
appending to the cache path. This value should not be an empty string.
- parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value),
the `.cachesDirectory` in of your app will be used.
- parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates
the final disk cache path. You could use it to fully customize your cache path.
- returns: The cache object.
*/
public init(name: String,
path: String? = nil,
diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure)
{
if name.isEmpty {
fatalError("[DSImageCache] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = "com.company.DSImageCache.ImageCache.\(name)"
memoryCache.name = cacheName
diskCachePath = diskCachePathClosure(path, cacheName)
let ioQueueName = "com.company.DSImageCache.ImageCache.ioQueue.\(name)"
ioQueue = DispatchQueue(label: ioQueueName)
let processQueueName = "com.company.DSImageCache.ImageCache.processQueue.\(name)"
processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent)
ioQueue.sync { fileManager = FileManager() }
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Store & Remove
/**
Store an image to cache. It will be saved to both memory and disk. It is an async operation.
- parameter image: The image to be stored.
- parameter original: The original data of the image.
DSImageCache will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- parameter key: Key for the image.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of
processor to it.
This identifier will be used to generate a corresponding key for the combination of `key` and processor.
- parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
- parameter completionHandler: Called when store operation completes.
*/
open func store(_ image: Image,
original: Data? = nil,
forKey key: String,
processorIdentifier identifier: String = "",
cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
toDisk: Bool = true,
completionHandler: (() -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.ds.imageCost)
func callHandlerInMainQueue() {
if let handler = completionHandler {
DispatchQueue.main.async {
handler()
}
}
}
if toDisk {
ioQueue.async {
if let data = serializer.data(with: image, original: original) {
if !self.fileManager.fileExists(atPath: self.diskCachePath) {
do {
try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil)
}
callHandlerInMainQueue()
}
} else {
callHandlerInMainQueue()
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation.
- parameter key: Key for the image.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
This identifier will be used to generate a corresponding key for the combination of `key` and processor.
- parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
- parameter completionHandler: Called when removal operation completes.
*/
open func removeImage(forKey key: String,
processorIdentifier identifier: String = "",
fromDisk: Bool = true,
completionHandler: (() -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
memoryCache.removeObject(forKey: computedKey as NSString)
func callHandlerInMainQueue() {
if let handler = completionHandler {
DispatchQueue.main.async {
handler()
}
}
}
if fromDisk {
ioQueue.async{
do {
try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey))
} catch _ {}
callHandlerInMainQueue()
}
} else {
callHandlerInMainQueue()
}
}
// MARK: - Get data from cache
/**
Get an image for a key from memory or disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- parameter completionHandler: Called when getting operation completes with image result and cached type of
this image. If there is no such key cached, the image will be `nil`.
- returns: The retrieving task.
*/
@discardableResult
open func retrieveImage(forKey key: String,
options: DSImageCacheOptionsInfo?,
completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask?
{
// No completion handler. Not start working and early return.
guard let completionHandler = completionHandler else {
return nil
}
var block: RetrieveImageDiskTask?
let options = options ?? DSImageCacheEmptyOptionsInfo
if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) {
options.callbackDispatchQueue.safeAsync {
completionHandler(image, .memory)
}
} else {
var sSelf: ImageCache! = self
block = DispatchWorkItem(block: {
// Begin to load image from disk
if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) {
if options.backgroundDecode {
sSelf.processQueue.async {
let result = image.ds.decoded(scale: options.scaleFactor)
sSelf.store(result,
forKey: key,
processorIdentifier: options.processor.identifier,
cacheSerializer: options.cacheSerializer,
toDisk: false,
completionHandler: nil)
options.callbackDispatchQueue.safeAsync {
completionHandler(result, .memory)
sSelf = nil
}
}
} else {
sSelf.store(image,
forKey: key,
processorIdentifier: options.processor.identifier,
cacheSerializer: options.cacheSerializer,
toDisk: false,
completionHandler: nil
)
options.callbackDispatchQueue.safeAsync {
completionHandler(image, .disk)
sSelf = nil
}
}
} else {
// No image found from either memory or disk
options.callbackDispatchQueue.safeAsync {
completionHandler(nil, .none)
sSelf = nil
}
}
})
sSelf.ioQueue.async(execute: block!)
}
return block
}
/**
Get an image for a key from memory.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
open func retrieveImageInMemoryCache(forKey key: String, options: DSImageCacheOptionsInfo? = nil) -> Image? {
let options = options ?? DSImageCacheEmptyOptionsInfo
let computedKey = key.computedKey(with: options.processor.identifier)
return memoryCache.object(forKey: computedKey as NSString) as? Image
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
open func retrieveImageInDiskCache(forKey key: String, options: DSImageCacheOptionsInfo? = nil) -> Image? {
let options = options ?? DSImageCacheEmptyOptionsInfo
let computedKey = key.computedKey(with: options.processor.identifier)
return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options)
}
// MARK: - Clear & Clean
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is an async operation.
- parameter completionHander: Called after the operation completes.
*/
open func clearDiskCache(completion handler: (()->())? = nil) {
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.diskCachePath)
try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ { }
if let handler = handler {
DispatchQueue.main.async {
handler()
}
}
}
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc fileprivate func cleanExpiredDiskCache() {
cleanExpiredDiskCache(completion: nil)
}
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
open func cleanExpiredDiskCache(completion handler: (()->())? = nil) {
// Do things in cocurrent io queue
ioQueue.async {
var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItem(at: fileURL)
} catch _ { }
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
// Not valid date information. This should not happen. Just in case.
return true
}
for fileURL in sortedFiles {
do {
try self.fileManager.removeItem(at: fileURL)
} catch { }
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
diskCacheSize -= UInt(fileSize)
}
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async {
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map { $0.lastPathComponent }
NotificationCenter.default.post(name: .DSImageCacheDidCleanDiskCache, object: self, userInfo: [DSImageCacheDiskCacheCleanedHashKey: cleanedHashes])
}
handler?()
}
}
}
fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
let diskCacheURL = URL(fileURLWithPath: diskCachePath)
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
var cachedFiles = [URL: URLResourceValues]()
var urlsToDelete = [URL]()
var diskCacheSize: UInt = 0
for fileUrl in (try? fileManager.contentsOfDirectory(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)) ?? [] {
do {
let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys)
// If it is a Directory. Continue to next file URL.
if resourceValues.isDirectory == true {
continue
}
// If this file is expired, add it to URLsToDelete
if !onlyForCacheSize,
let expiredDate = expiredDate,
let lastAccessData = resourceValues.contentAccessDate,
(lastAccessData as NSDate).laterDate(expiredDate) == expiredDate
{
urlsToDelete.append(fileUrl)
continue
}
if let fileSize = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(fileSize)
if !onlyForCacheSize {
cachedFiles[fileUrl] = resourceValues
}
}
} catch _ { }
}
return (urlsToDelete, diskCacheSize, cachedFiles)
}
// MARK: - Check cache status
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
- parameter key: Key for the image.
- returns: The check result.
*/
open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult {
let computedKey = key.computedKey(with: identifier)
if memoryCache.object(forKey: computedKey as NSString) != nil {
return CacheCheckResult(cached: true, cacheType: .memory)
}
let filePath = cachePath(forComputedKey: computedKey)
var diskCached = false
ioQueue.sync {
diskCached = fileManager.fileExists(atPath: filePath)
}
if diskCached {
return CacheCheckResult(cached: true, cacheType: .disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
- parameter key: The key which is used for caching.
- parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
- returns: Corresponding hash.
*/
open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String {
let computedKey = key.computedKey(with: identifier)
return cacheFileName(forComputedKey: computedKey)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
- parameter completionHandler: Called with the calculated size when finishes.
*/
open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) {
ioQueue.async {
let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
DispatchQueue.main.async {
handler(diskCacheSize)
}
}
}
/**
Get the cache path for the key.
It is useful for projects with UIWebView or anyone that needs access to the local file path.
i.e. Replace the `<img src='path_for_key'>` tag in your HTML.
- Note: This method does not guarantee there is an image already cached in the path. It just returns the path
that the image should be.
You could use `isImageCached(forKey:)` method to check whether the image is cached under that key.
*/
open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String {
let computedKey = key.computedKey(with: identifier)
return cachePath(forComputedKey: computedKey)
}
open func cachePath(forComputedKey key: String) -> String {
let fileName = cacheFileName(forComputedKey: key)
return (diskCachePath as NSString).appendingPathComponent(fileName)
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: DSImageCacheOptionsInfo) -> Image? {
if let data = diskImageData(forComputedKey: key) {
return serializer.image(with: data, options: options)
} else {
return nil
}
}
func diskImageData(forComputedKey key: String) -> Data? {
let filePath = cachePath(forComputedKey: key)
return (try? Data(contentsOf: URL(fileURLWithPath: filePath)))
}
func cacheFileName(forComputedKey key: String) -> String {
if let ext = self.pathExtension {
return (key.ds.md5 as NSString).appendingPathExtension(ext)!
}
return key.ds.md5
}
}
extension DSImageCache where Base: Image {
var imageCost: Int {
return images == nil ?
Int(size.height * size.width * scale * scale) :
Int(size.height * size.width * scale * scale) * images!.count
}
}
extension Dictionary {
func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
}
}
extension String {
func computedKey(with identifier: String) -> String {
if identifier.isEmpty {
return self
} else {
return appending("@\(identifier)")
}
}
}
| mit | c9b272a0107580c818e0d661c71926d3 | 39.568882 | 257 | 0.583796 | 5.704421 | false | false | false | false |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/Toolbar.swift | 1 | 6117 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* 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
private var ToolbarContext: UInt8 = 0
open class Toolbar: Bar {
/// A convenience property to set the titleLabel text.
open var title: String? {
get {
return titleLabel.text
}
set(value) {
titleLabel.text = value
layoutSubviews()
}
}
/// Title label.
open internal(set) lazy var titleLabel = UILabel()
/// A convenience property to set the detailLabel text.
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
layoutSubviews()
}
}
/// Detail label.
open internal(set) lazy var detailLabel = UILabel()
deinit {
removeObserver(self, forKeyPath: "titleLabel.textAlignment")
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
/**
A convenience initializer with parameter settings.
- Parameter leftViews: An Array of UIViews that go on the left side.
- Parameter rightViews: An Array of UIViews that go on the right side.
- Parameter centerViews: An Array of UIViews that go in the center.
*/
public override init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) {
super.init(leftViews: leftViews, rightViews: rightViews, centerViews: centerViews)
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard "titleLabel.textAlignment" == keyPath else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
contentViewAlignment = .center == titleLabel.textAlignment ? .center : .any
}
/// Reloads the view.
open override func reload() {
super.reload()
if nil != title && "" != title {
if nil == titleLabel.superview {
contentView.addSubview(titleLabel)
}
titleLabel.frame = contentView.bounds
} else {
titleLabel.removeFromSuperview()
}
if nil != detail && "" != detail {
if nil == detailLabel.superview {
contentView.addSubview(detailLabel)
}
if nil == titleLabel.superview {
detailLabel.frame = contentView.bounds
} else {
titleLabel.sizeToFit()
detailLabel.sizeToFit()
let diff: CGFloat = (contentView.height - titleLabel.height - detailLabel.height) / 2
titleLabel.height += diff
titleLabel.width = contentView.width
detailLabel.height += diff
detailLabel.width = contentView.width
detailLabel.y = titleLabel.height
}
} else {
detailLabel.removeFromSuperview()
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
zPosition = 1000
contentViewAlignment = .center
prepareTitleLabel()
prepareDetailLabel()
}
/// Prepares the titleLabel.
private func prepareTitleLabel() {
titleLabel.textAlignment = .center
titleLabel.contentScaleFactor = Device.scale
titleLabel.font = RobotoFont.medium(with: 17)
titleLabel.textColor = Color.darkText.primary
addObserver(self, forKeyPath: "titleLabel.textAlignment", options: [], context: &ToolbarContext)
}
/// Prepares the detailLabel.
private func prepareDetailLabel() {
detailLabel.textAlignment = .center
detailLabel.contentScaleFactor = Device.scale
detailLabel.font = RobotoFont.regular(with: 12)
detailLabel.textColor = Color.darkText.secondary
}
}
| gpl-3.0 | 7f86d1fa9376c645eba5535925eb30c4 | 34.358382 | 156 | 0.665686 | 4.812746 | false | false | false | false |
AjayOdedara/CoreKitTest | CoreKit/CoreKit/DateHelper.swift | 1 | 29604 | //
// AFDateHelper.swift
// https://github.com/melvitax/DateHelper
// Version 4.1.2
//
// Created by Melvin Rivera on 7/15/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
public extension Date {
// MARK: Convert from String
/*
Initializes a new Date() objext based on a date string, format, optional timezone and optional locale.
- Returns: A Date() object if successfully converted from string or nil.
*/
init?(fromString string: String, format:DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Foundation.Locale.current) {
guard !string.isEmpty else {
return nil
}
var string = string
switch format {
case .dotNet:
let pattern = "\\\\?/Date\\((\\d+)(([+-]\\d{2})(\\d{2}))?\\)\\\\?/"
let regex = try! NSRegularExpression(pattern: pattern)
guard let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) else {
return nil
}
let dateString = (string as NSString).substring(with: match.rangeAt(1))
let interval = Double(dateString)! / 1000.0
self.init(timeIntervalSince1970: interval)
return
case .rss, .altRSS:
if string.hasSuffix("Z") {
string = string.substring(to: string.index(string.endIndex, offsetBy: -1)).appending("GMT")
}
default:
break
}
let formatter = Date.cachedFormatter(format.stringFormat, timeZone: timeZone.timeZone, locale: locale)
guard let date = formatter.date(from: string) else {
return nil
}
self.init(timeInterval:0, since:date)
}
// MARK: Convert to String
/// Converts the date to string using the short date and time style.
func toString(style:DateStyleType = .short) -> String {
switch style {
case .short:
return self.toString(dateStyle: .short, timeStyle: .short, isRelative: false)
case .medium:
return self.toString(dateStyle: .medium, timeStyle: .medium, isRelative: false)
case .long:
return self.toString(dateStyle: .long, timeStyle: .long, isRelative: false)
case .full:
return self.toString(dateStyle: .full, timeStyle: .full, isRelative: false)
case .weekday:
let weekdaySymbols = Date.cachedFormatter().weekdaySymbols!
let string = weekdaySymbols[component(.weekday)!-1] as String
return string
case .shortWeekday:
let shortWeekdaySymbols = Date.cachedFormatter().shortWeekdaySymbols!
return shortWeekdaySymbols[component(.weekday)!-1] as String
case .veryShortWeekday:
let veryShortWeekdaySymbols = Date.cachedFormatter().veryShortWeekdaySymbols!
return veryShortWeekdaySymbols[component(.weekday)!-1] as String
case .month:
let monthSymbols = Date.cachedFormatter().monthSymbols!
return monthSymbols[component(.month)!-1] as String
case .shortMonth:
let shortMonthSymbols = Date.cachedFormatter().shortMonthSymbols!
return shortMonthSymbols[component(.month)!-1] as String
case .veryShortMonth:
let veryShortMonthSymbols = Date.cachedFormatter().veryShortMonthSymbols!
return veryShortMonthSymbols[component(.month)!-1] as String
}
}
/// Converts the date to string based on a date format, optional timezone and optional locale.
func toString(format: DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Locale.current) -> String {
switch format {
case .dotNet:
let offset = Foundation.NSTimeZone.default.secondsFromGMT() / 3600
let nowMillis = 1000 * self.timeIntervalSince1970
return String(format: format.stringFormat, nowMillis, offset)
default:
break
}
let formatter = Date.cachedFormatter(format.stringFormat, timeZone: timeZone.timeZone, locale: locale)
return formatter.string(from: self)
}
/// Converts the date to string based on DateFormatter's date style and time style with optional relative date formatting, optional time zone and optional locale.
func toString(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, isRelative: Bool = false, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> String {
let formatter = Date.cachedFormatter(dateStyle, timeStyle: timeStyle, doesRelativeDateFormatting: isRelative, timeZone: timeZone, locale: locale)
return formatter.string(from: self)
}
/// Converts the date to string based on a relative time language. i.e. just now, 1 minute ago etc...
func toStringWithRelativeTime(strings:[RelativeTimeStringType:String]? = nil) -> String {
let time = self.timeIntervalSince1970
let now = Date().timeIntervalSince1970
let isPast = now - time > 0
let sec:Double = abs(now - time)
let min:Double = round(sec/60)
let hr:Double = round(min/60)
let d:Double = round(hr/24)
if sec < 60 {
if sec < 10 {
if isPast {
return strings?[.nowPast] ?? NSLocalizedString("just now", comment: "Date format")
} else {
return strings?[.nowFuture] ?? NSLocalizedString("in a few seconds", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.secondsPast] ?? NSLocalizedString("%.f seconds ago", comment: "Date format")
} else {
string = strings?[.secondsFuture] ?? NSLocalizedString("in %.f seconds", comment: "Date format")
}
return String(format: string, sec)
}
}
if min < 60 {
if min == 1 {
if isPast {
return strings?[.oneMinutePast] ?? NSLocalizedString("1 minute ago", comment: "Date format")
} else {
return strings?[.oneMinuteFuture] ?? NSLocalizedString("in 1 minute", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.minutesPast] ?? NSLocalizedString("%.f minutes ago", comment: "Date format")
} else {
string = strings?[.minutesFuture] ?? NSLocalizedString("in %.f minutes", comment: "Date format")
}
return String(format: string, min)
}
}
if hr < 24 {
if hr == 1 {
if isPast {
return strings?[.oneHourPast] ?? NSLocalizedString("last hour", comment: "Date format")
} else {
return strings?[.oneHourFuture] ?? NSLocalizedString("next hour", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.hoursPast] ?? NSLocalizedString("%.f hours ago", comment: "Date format")
} else {
string = strings?[.hoursFuture] ?? NSLocalizedString("in %.f hours", comment: "Date format")
}
return String(format: string, hr)
}
}
if d < 7 {
if d == 1 {
if isPast {
return strings?[.oneDayPast] ?? NSLocalizedString("yesterday", comment: "Date format")
} else {
return strings?[.oneDayFuture] ?? NSLocalizedString("tomorrow", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.daysPast] ?? NSLocalizedString("%.f days ago", comment: "Date format")
} else {
string = strings?[.daysFuture] ?? NSLocalizedString("in %.f days", comment: "Date format")
}
return String(format: string, d)
}
}
if d < 28 {
if isPast {
if compare(.isLastWeek) {
return strings?[.oneWeekPast] ?? NSLocalizedString("last week", comment: "Date format")
} else {
let string = strings?[.weeksPast] ?? NSLocalizedString("%.f weeks ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .week))))
}
} else {
if compare(.isNextWeek) {
return strings?[.oneWeekFuture] ?? NSLocalizedString("next week", comment: "Date format")
} else {
let string = strings?[.weeksFuture] ?? NSLocalizedString("in %.f weeks", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .week))))
}
}
}
if compare(.isThisYear) {
if isPast {
if compare(.isLastMonth) {
return strings?[.oneMonthPast] ?? NSLocalizedString("last month", comment: "Date format")
} else {
let string = strings?[.monthsPast] ?? NSLocalizedString("%.f months ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .month))))
}
} else {
if compare(.isNextMonth) {
return strings?[.oneMonthFuture] ?? NSLocalizedString("next month", comment: "Date format")
} else {
let string = strings?[.monthsFuture] ?? NSLocalizedString("in %.f months", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .month))))
}
}
}
if isPast {
if compare(.isLastYear) {
return strings?[.oneYearPast] ?? NSLocalizedString("last year", comment: "Date format")
} else {
let string = strings?[.yearsPast] ?? NSLocalizedString("%.f years ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .year))))
}
} else {
if compare(.isNextYear) {
return strings?[.oneYearFuture] ?? NSLocalizedString("next year", comment: "Date format")
} else {
let string = strings?[.yearsFuture] ?? NSLocalizedString("in %.f years", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .year))))
}
}
}
// MARK: Compare Dates
/// Compares dates to see if they are equal while ignoring time.
func compare(_ comparison:DateComparisonType) -> Bool {
switch comparison {
case .isToday:
return compare(.isSameDay(as: Date()))
case .isTomorrow:
let comparison = Date().adjust(.day, offset:1)
return compare(.isSameDay(as: comparison))
case .isYesterday:
let comparison = Date().adjust(.day, offset: -1)
return compare(.isSameDay(as: comparison))
case .isSameDay(let date):
return component(.year) == date.component(.year)
&& component(.month) == date.component(.month)
&& component(.day) == date.component(.day)
case .isThisWeek:
return self.compare(.isSameWeek(as: Date()))
case .isNextWeek:
let comparison = Date().adjust(.week, offset:1)
return compare(.isSameWeek(as: comparison))
case .isLastWeek:
let comparison = Date().adjust(.week, offset:-1)
return compare(.isSameWeek(as: comparison))
case .isSameWeek(let date):
if component(.week) != date.component(.week) {
return false
}
// Ensure time interval is under 1 week
return abs(self.timeIntervalSince(date)) < Date.weekInSeconds
case .isThisMonth:
return self.compare(.isSameMonth(as: Date()))
case .isNextMonth:
let comparison = Date().adjust(.month, offset:1)
return compare(.isSameMonth(as: comparison))
case .isLastMonth:
let comparison = Date().adjust(.month, offset:-1)
return compare(.isSameMonth(as: comparison))
case .isSameMonth(let date):
return component(.year) == date.component(.year) && component(.month) == date.component(.month)
case .isThisYear:
return self.compare(.isSameYear(as: Date()))
case .isNextYear:
let comparison = Date().adjust(.year, offset:1)
return compare(.isSameYear(as: comparison))
case .isLastYear:
let comparison = Date().adjust(.year, offset:-1)
return compare(.isSameYear(as: comparison))
case .isSameYear(let date):
return component(.year) == date.component(.year)
case .isInTheFuture:
return self.compare(.isLater(than: Date()))
case .isInThePast:
return self.compare(.isEarlier(than: Date()))
case .isEarlier(let date):
return (self as NSDate).earlierDate(date) == self
case .isLater(let date):
return (self as NSDate).laterDate(date) == self
case .isWeekday:
return !compare(.isWeekend)
case .isWeekend:
let range = Calendar.current.maximumRange(of: Calendar.Component.weekday)!
return (component(.weekday) == range.lowerBound || component(.weekday) == range.upperBound - range.lowerBound)
}
}
// MARK: Adjust dates
/// Creates a new date with adjusted components
func adjust(_ component:DateComponentType, offset:Int) -> Date {
var dateComp = DateComponents()
switch component {
case .second:
dateComp.second = offset
case .minute:
dateComp.minute = offset
case .hour:
dateComp.hour = offset
case .day:
dateComp.day = offset
case .weekday:
dateComp.weekday = offset
case .nthWeekday:
dateComp.weekdayOrdinal = offset
case .week:
dateComp.weekOfYear = offset
case .month:
dateComp.month = offset
case .year:
dateComp.year = offset
}
return Calendar.current.date(byAdding: dateComp, to: self)!
}
/// Return a new Date object with the new hour, minute and seconds values.
func adjust(hour: Int?, minute: Int?, second: Int?, day: Int? = nil, month: Int? = nil) -> Date {
var comp = Date.components(self)
comp.month = month ?? comp.month
comp.day = day ?? comp.day
comp.hour = hour ?? comp.hour
comp.minute = minute ?? comp.minute
comp.second = second ?? comp.second
return Calendar.current.date(from: comp)!
}
// MARK: Date for...
func dateFor(_ type:DateForType) -> Date {
switch type {
case .startOfDay:
return adjust(hour: 0, minute: 0, second: 0)
case .endOfDay:
return adjust(hour: 23, minute: 59, second: 59)
case .startOfWeek:
let offset = component(.weekday)!-1
return adjust(.day, offset: -(offset))
case .endOfWeek:
let offset = 7 - component(.weekday)!
return adjust(.day, offset: offset)
case .startOfMonth:
return adjust(hour: 0, minute: 0, second: 0, day: 1)
case .endOfMonth:
let month = (component(.month) ?? 0) + 1
return adjust(hour: 0, minute: 0, second: 0, day: 0, month: month)
case .tomorrow:
return adjust(.day, offset:1)
case .yesterday:
return adjust(.day, offset:-1)
case .nearestMinute(let nearest):
let minutes = (component(.minute)! + nearest/2) / nearest * nearest
return adjust(hour: nil, minute: minutes, second: nil)
case .nearestHour(let nearest):
let hours = (component(.hour)! + nearest/2) / nearest * nearest
return adjust(hour: hours, minute: 0, second: nil)
}
}
// MARK: Time since...
func since(_ date:Date, in component:DateComponentType) -> Int64 {
switch component {
case .second:
return Int64(timeIntervalSince(date))
case .minute:
let interval = timeIntervalSince(date)
return Int64(interval / Date.minuteInSeconds)
case .hour:
let interval = timeIntervalSince(date)
return Int64(interval / Date.hourInSeconds)
case .day:
let calendar = Calendar.current
let end = calendar.ordinality(of: .day, in: .era, for: self)
let start = calendar.ordinality(of: .day, in: .era, for: date)
return Int64(end! - start!)
case .weekday:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekday, in: .era, for: self)
let start = calendar.ordinality(of: .weekday, in: .era, for: date)
return Int64(end! - start!)
case .nthWeekday:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: self)
let start = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: date)
return Int64(end! - start!)
case .week:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekOfYear, in: .era, for: self)
let start = calendar.ordinality(of: .weekOfYear, in: .era, for: date)
return Int64(end! - start!)
case .month:
let calendar = Calendar.current
let end = calendar.ordinality(of: .month, in: .era, for: self)
let start = calendar.ordinality(of: .month, in: .era, for: date)
return Int64(end! - start!)
case .year:
let calendar = Calendar.current
let end = calendar.ordinality(of: .year, in: .era, for: self)
let start = calendar.ordinality(of: .year, in: .era, for: date)
return Int64(end! - start!)
}
}
// MARK: Extracting components
func component(_ component:DateComponentType) -> Int? {
let components = Date.components(self)
switch component {
case .second:
return components.second
case .minute:
return components.minute
case .hour:
return components.hour
case .day:
return components.day
case .weekday:
return components.weekday
case .nthWeekday:
return components.weekdayOrdinal
case .week:
return components.weekOfYear
case .month:
return components.month
case .year:
return components.year
}
}
func numberOfDaysInMonth() -> Int {
let range = Calendar.current.range(of: Calendar.Component.day, in: Calendar.Component.month, for: self)!
return range.upperBound - range.lowerBound
}
func firstDayOfWeek() -> Int {
let distanceToStartOfWeek = Date.dayInSeconds * Double(self.component(.weekday)! - 1)
let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek
return Date(timeIntervalSinceReferenceDate: interval).component(.day)!
}
func lastDayOfWeek() -> Int {
let distanceToStartOfWeek = Date.dayInSeconds * Double(self.component(.weekday)! - 1)
let distanceToEndOfWeek = Date.dayInSeconds * Double(7)
let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek
return Date(timeIntervalSinceReferenceDate: interval).component(.day)!
}
// MARK: Internal Components
internal static func componentFlags() -> Set<Calendar.Component> { return [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second, Calendar.Component.weekday, Calendar.Component.weekdayOrdinal, Calendar.Component.weekOfYear] }
internal static func components(_ fromDate: Date) -> DateComponents {
return Calendar.current.dateComponents(Date.componentFlags(), from: fromDate)
}
// MARK: Static Cached Formatters
/// A cached static array of DateFormatters so that thy are only created once.
private static func cachedDateFormatters() -> [String: DateFormatter] {
struct Static {
static var formatters: [String: DateFormatter]? = [String: DateFormatter]()
}
return Static.formatters!
}
/// Generates a cached formatter based on the specified format, timeZone and locale. Formatters are cached in a singleton array using hashkeys.
private static func cachedFormatter(_ format:String = DateFormatType.standard.stringFormat, timeZone: Foundation.TimeZone = Foundation.TimeZone.current, locale: Locale = Locale.current) -> DateFormatter {
let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
var formatters = Date.cachedDateFormatters()
if let cachedDateFormatter = formatters[hashKey] {
return cachedDateFormatter
} else {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = timeZone
formatter.locale = locale
formatters[hashKey] = formatter
return formatter
}
}
/// Generates a cached formatter based on the provided date style, time style and relative date. Formatters are cached in a singleton array using hashkeys.
private static func cachedFormatter(_ dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, doesRelativeDateFormatting: Bool, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> DateFormatter {
var formatters = Date.cachedDateFormatters()
let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
if let cachedDateFormatter = formatters[hashKey] {
return cachedDateFormatter
} else {
let formatter = DateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
formatter.doesRelativeDateFormatting = doesRelativeDateFormatting
formatter.timeZone = timeZone
formatter.locale = locale
formatters[hashKey] = formatter
return formatter
}
}
// MARK: Intervals In Seconds
internal static let minuteInSeconds:Double = 60
internal static let hourInSeconds:Double = 3600
internal static let dayInSeconds:Double = 86400
internal static let weekInSeconds:Double = 604800
internal static let yearInSeconds:Double = 31556926
}
// MARK: Enums used
/**
The string format used for date string conversion.
````
case isoYear: i.e. 1997
case isoYearMonth: i.e. 1997-07
case isoDate: i.e. 1997-07-16
case isoDateTime: i.e. 1997-07-16T19:20+01:00
case isoDateTimeSec: i.e. 1997-07-16T19:20:30+01:00
case isoDateTimeMilliSec: i.e. 1997-07-16T19:20:30.45+01:00
case dotNet: i.e. "/Date(1268123281843)/"
case rss: i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
case altRSS: i.e. "09 Sep 2011 15:26:08 +0200"
case httpHeader: i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
case standard: "EEE MMM dd HH:mm:ss Z yyyy"
case custom(String): a custom date format string
````
*/
public enum DateFormatType {
/// The ISO8601 formatted year "yyyy" i.e. 1997
case isoYear
/// The ISO8601 formatted year and month "yyyy-MM" i.e. 1997-07
case isoYearMonth
/// The ISO8601 formatted date "yyyy-MM-dd" i.e. 1997-07-16
case isoDate
/// The ISO8601 formatted date and time "yyyy-MM-dd'T'HH:mmZ" i.e. 1997-07-16T19:20+01:00
case isoDateTime
/// The ISO8601 formatted date, time and sec "yyyy-MM-dd'T'HH:mm:ssZ" i.e. 1997-07-16T19:20:30+01:00
case isoDateTimeSec
/// The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ss.SSSZ" i.e. 1997-07-16T19:20:30.45+01:00
case isoDateTimeMilliSec
/// The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/"
case dotNet
/// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
case rss
/// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200"
case altRSS
/// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
case httpHeader
/// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy"
case standard
/// A custom date format string
case custom(String)
var stringFormat:String {
switch self {
case .isoYear: return "yyyy"
case .isoYearMonth: return "yyyy-MM"
case .isoDate: return "yyyy-MM-dd"
case .isoDateTime: return "yyyy-MM-dd'T'HH:mmZ"
case .isoDateTimeSec: return "yyyy-MM-dd'T'HH:mm:ssZ"
case .isoDateTimeMilliSec: return "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
case .dotNet: return "/Date(%d%f)/"
case .rss: return "EEE, d MMM yyyy HH:mm:ss ZZZ"
case .altRSS: return "d MMM yyyy HH:mm:ss ZZZ"
case .httpHeader: return "EEE, dd MM yyyy HH:mm:ss ZZZ"
case .standard: return "EEE MMM dd HH:mm:ss Z yyyy"
case .custom(let customFormat): return customFormat
}
}
}
/// The time zone to be used for date conversion
public enum TimeZoneType {
case local, utc
var timeZone:TimeZone {
switch self {
case .local: return NSTimeZone.local
case .utc: return TimeZone(secondsFromGMT: 0)!
}
}
}
// The string keys to modify the strings in relative format
public enum RelativeTimeStringType {
case nowPast, nowFuture, secondsPast, secondsFuture, oneMinutePast, oneMinuteFuture, minutesPast, minutesFuture, oneHourPast, oneHourFuture, hoursPast, hoursFuture, oneDayPast, oneDayFuture, daysPast, daysFuture, oneWeekPast, oneWeekFuture, weeksPast, weeksFuture, oneMonthPast, oneMonthFuture, monthsPast, monthsFuture, oneYearPast, oneYearFuture, yearsPast, yearsFuture
}
// The type of comparison to do against today's date or with the suplied date.
public enum DateComparisonType {
// Days
/// Checks if date today.
case isToday
/// Checks if date is tomorrow.
case isTomorrow
/// Checks if date is yesterday.
case isYesterday
/// Compares date days
case isSameDay(as:Date)
// Weeks
/// Checks if date is in this week.
case isThisWeek
/// Checks if date is in next week.
case isNextWeek
/// Checks if date is in last week.
case isLastWeek
/// Compares date weeks
case isSameWeek(as:Date)
// Months
/// Checks if date is in this month.
case isThisMonth
/// Checks if date is in next month.
case isNextMonth
/// Checks if date is in last month.
case isLastMonth
/// Compares date months
case isSameMonth(as:Date)
// Years
/// Checks if date is in this year.
case isThisYear
/// Checks if date is in next year.
case isNextYear
/// Checks if date is in last year.
case isLastYear
/// Compare date years
case isSameYear(as:Date)
// Relative Time
/// Checks if it's a future date
case isInTheFuture
/// Checks if the date has passed
case isInThePast
/// Checks if earlier than date
case isEarlier(than:Date)
/// Checks if later than date
case isLater(than:Date)
/// Checks if it's a weekday
case isWeekday
/// Checks if it's a weekend
case isWeekend
}
// The date components available to be retrieved or modifed
public enum DateComponentType {
case second, minute, hour, day, weekday, nthWeekday, week, month, year
}
// The type of date that can be used for the dateFor function.
public enum DateForType {
case startOfDay, endOfDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, tomorrow, yesterday, nearestMinute(minute:Int), nearestHour(hour:Int)
}
// Convenience types for date to string conversion
public enum DateStyleType {
case short, medium, long, full, weekday, shortWeekday, veryShortWeekday, month, shortMonth, veryShortMonth
}
| mit | d3653117dd57989507da1e1f2695f47c | 40.695775 | 375 | 0.590393 | 4.684918 | false | false | false | false |
JonMercer/burritoVSWHackathon | Burrito/General.swift | 1 | 1640 | //
// General.swift
// Burrito
//
// Created by Gordon Seto on 2016-09-24.
// Copyright © 2016 TeamAlpaka. All rights reserved.
//
import Foundation
import UIKit
let VC_INDEX = 0
let BLUE_COLOR = UIColor(red: 67.0/255.0, green: 125.0/255.0, blue: 234.0/255.0, alpha: 1.0)
let DARK_BLUR_COLOR = UIColor(red: 44.0/255.0, green: 83.0/255.0, blue: 155.0/255.0, alpha: 1.0)
let GREEN_COLOR = UIColor(red: 28.0/255.0, green: 220.0/255.0, blue: 0.0/255.0, alpha: 1.0)
func bounceView(view: UIView, amount: CGFloat){
UIView.animateWithDuration(0.1, delay: 0.0, options: [], animations: {
view.transform = CGAffineTransformMakeScale(amount, amount)
}, completion: {completed in
UIView.animateWithDuration(0.1, delay: 0.0, options: [], animations: {
view.transform = CGAffineTransformMakeScale(1.0, 1.0)
}, completion: {completed in })
})
}
func delay(amount: Double, completion:()->()){
let delay = amount * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
completion()
}
}
func sendLocalNotification(){
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
localNotification.alertBody = "Giveaway: Deer Island Bakery Swipe to enter!"
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
} | mit | 09883755f5e0ed7c1bd9257a3902eaa5 | 37.139535 | 115 | 0.694326 | 3.708145 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Model/CustomStyle.swift | 1 | 3324 | //
// CustomStyle.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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.
//
@objc
open class CustomStyle: NSObject, Identifiable {
open let identifier: String
open let headerBackgroundIdentifier: String?
open let bodyBackgroundIdentifier: String?
open let fontName: String?
open let bio: String?
open let bodyColorsHex: Array<String>?
open let headerColorsHex: Array<String>?
open let bodyCreationURL: String?
open let headerCreationURL: String?
open let createdAt: Date
open let updatedAt: Date
open let userRelationship: Relationship?
open let headerCreationRelationship: Relationship?
open let bodyCreationRelationship: Relationship?
open let user: User?
open let headerCreation: Creation?
open let bodyCreation: Creation?
init(mapper: CustomStyleMapper, dataMapper: DataIncludeMapper? = nil) {
identifier = mapper.identifier!
headerBackgroundIdentifier = mapper.headerBackgroundIdentifier
bodyBackgroundIdentifier = mapper.bodyBackgroundIdentifier
fontName = mapper.fontName
bio = mapper.bio
bodyColorsHex = mapper.bodyColorStrings?.flatMap({ $0.isHexColorString() ? $0 : $0.RGBtoHexString() })
headerColorsHex = mapper.headerColorStrings?.flatMap({ $0.isHexColorString() ? $0 : $0.RGBtoHexString() })
bodyCreationURL = mapper.bodyCreationURL
headerCreationURL = mapper.headerCreationURL
createdAt = mapper.createdAt! as Date
updatedAt = mapper.updatedAt! as Date
userRelationship = MappingUtils.relationshipFromMapper(mapper.userRelationship)
headerCreationRelationship = MappingUtils.relationshipFromMapper(mapper.headerCreationRelationship)
bodyCreationRelationship = MappingUtils.relationshipFromMapper(mapper.bodyCreationRelationship)
user = MappingUtils.objectFromMapper(dataMapper, relationship: userRelationship, type: User.self)
headerCreation = MappingUtils.objectFromMapper(dataMapper, relationship: headerCreationRelationship, type: Creation.self)
bodyCreation = MappingUtils.objectFromMapper(dataMapper, relationship: bodyCreationRelationship, type: Creation.self)
}
}
| mit | f42bf2a26bc6bac05701e4cc7d272667 | 43.918919 | 129 | 0.749097 | 4.888235 | false | false | false | false |
kiliankoe/DVB | Sources/DVB/Models/POI/POI.swift | 1 | 1502 | import Foundation
public struct POI {
public let descriptionString: String // FIXME:
}
extension POI: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.descriptionString = try container.decode(String.self)
}
}
extension POI: Equatable {}
extension POI: Hashable {}
// MARK: - API
extension POI {
public struct CoordRect {
public let northeast: Coordinate
public let southwest: Coordinate
public init(northeast: Coordinate, southwest: Coordinate) {
self.northeast = northeast
self.southwest = southwest
}
}
public static func find(types: [POI.Kind] = POI.Kind.allCases,
in rect: CoordRect,
session: URLSession = .shared,
completion: @escaping (Result<POIResponse>) -> Void) {
guard
let gkSWCoord = rect.southwest.asGK,
let gkNECoord = rect.northeast.asGK
else {
completion(Result(failure: DVBError.coordinate))
return
}
let data: [String: Any] = [
"swlat": gkSWCoord.x,
"swlng": gkSWCoord.y,
"nelat": gkNECoord.x,
"nelng": gkNECoord.y,
"showlines": true,
"pintypes": types.map { $0.rawValue },
]
post(Endpoint.poiSearch, data: data, session: session, completion: completion)
}
}
| mit | 8225b0972ba1b0b31200d148b0512b32 | 26.814815 | 86 | 0.571238 | 4.443787 | false | false | false | false |
richardbuckle/Laurine | Example/Pods/Warp/Source/WRPObject.swift | 1 | 27622 | //
// WRPObject.swift
//
// Copyright (c) 2016 Jiri Trecak (http://jiritrecak.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: - Imports
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Definitions
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extension
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Protocols
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Implementation
public class WRPObject : NSObject {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Setup
override public init() {
super.init()
// No initialization required - nothing to fill object with
}
convenience public init(fromJSON : String) {
if let jsonData : NSData = fromJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
do {
let jsonObject : AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
self.init(parameters: jsonObject as! NSDictionary)
} catch let error as NSError {
self.init(parameters: [:])
print ("Error while parsing a json object: \(error.domain)")
}
} else {
self.init(parameters: NSDictionary())
}
}
convenience public init(fromDictionary : NSDictionary) {
self.init(parameters: fromDictionary)
}
required public init(parameters : NSDictionary) {
super.init()
if self.debugInstantiate() {
NSLog("parameters %@", parameters)
}
self.fillValues(parameters)
self.processClosestRelationships(parameters)
}
required public init(parameters: NSDictionary, parentObject: WRPObject?) {
super.init()
if self.debugInstantiate() {
NSLog("parameters %@", parameters)
}
self.fillValues(parameters)
self.processClosestRelationships(parameters, parentObject: parentObject)
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - User overrides for data mapping
public func propertyMap() -> [WRPProperty] {
return []
}
public func relationMap() -> [WRPRelation] {
return []
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func fillValues(parameters : NSDictionary) {
for element : WRPProperty in self.propertyMap() {
// Dot convention
self.assignValueForElement(element, parameters: parameters)
}
}
private func processClosestRelationships(parameters : NSDictionary) {
self.processClosestRelationships(parameters, parentObject: nil)
}
private func processClosestRelationships(parameters : NSDictionary, parentObject : WRPObject?) {
for element in self.relationMap() {
self.assignDataObjectForElement(element, parameters: parameters, parentObject: parentObject)
}
}
private func assignValueForElement(element : WRPProperty, parameters : NSDictionary) {
switch element.elementDataType {
// Handle string data type
case .String:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.stringFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle boolean data type
case .Bool:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.boolFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle double data type
case .Double:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Double, value: self.doubleFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle float data type
case .Float:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Float, value: self.floatFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle int data type
case .Int:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Int, value: self.intFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle int data type
case .Number:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.numberFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle date data type
case .Date:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.dateFromParameters(parameters, key: elementRemoteName, format: element.format),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle array data type
case .Array:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.arrayFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle dictionary data type
case .Dictionary:
for elementRemoteName in element.remoteNames {
if (self.setValue(.Any, value: self.dictionaryFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
}
}
private func assignDataObjectForElement(element : WRPRelation, parameters : NSDictionary, parentObject : WRPObject?) -> WRPObject? {
switch element.relationshipType {
case .ToOne:
return self.handleToOneRelationshipWithElement(element, parameters : parameters, parentObject: parentObject)
case .ToMany:
self.handleToManyRelationshipWithElement(element, parameters : parameters, parentObject: parentObject)
}
return nil
}
private func handleToOneRelationshipWithElement(element : WRPRelation, parameters : NSDictionary, parentObject : WRPObject?) -> WRPObject? {
if let objectData : AnyObject? = parameters.objectForKey(element.remoteName) {
if objectData is NSDictionary {
// Create object
let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: element.className, parentObject: parentObject)
// Set child object to self.property
self.setValue(.Any, value: dataObject, forKey: element.localName, optional: element.optional, temporaryOptional: false)
// Set inverse relationship
if (element.inverseRelationshipType == .ToOne) {
dataObject.setValue(.Any, value: self, forKey: element.inverseName, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else {
var objects : [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.Any, value: objects, forKey: element.inverseName, optional: true, temporaryOptional: true)
}
return dataObject
} else if objectData is NSNull {
// Set empty object to self.property
self.setValue(.Any, value: nil, forKey: element.localName, optional: element.optional, temporaryOptional: false)
return nil
}
}
return nil
}
private func handleToManyRelationshipWithElement(element : WRPRelation, parameters: NSDictionary, parentObject : WRPObject?) {
if let objectDataPack : AnyObject? = parameters.objectForKey(element.remoteName) {
// While the relationship is .ToMany, we can actually add it from single entry
if objectDataPack is NSDictionary {
// Always override local property, there is no inserting allowed
var objects : [WRPObject]? = [WRPObject]()
self.setValue(objects, forKey: element.localName)
// Create object
let dataObject = self.dataObjectFromParameters(objectDataPack as! NSDictionary, objectType: element.className, parentObject: parentObject)
// Set inverse relationship
if (element.inverseRelationshipType == .ToOne) {
dataObject.setValue(.Any, value: self, forKey: element.inverseName, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else {
var objects : [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.Any, value: objects, forKey: element.inverseName, optional: true, temporaryOptional: true)
}
// Append new data object to array
objects!.append(dataObject)
// Write new objects back
self.setValue(objects, forKey: element.localName)
// More objects in the same entry
} else if objectDataPack is NSArray {
// Always override local property, there is no inserting allowed
var objects : [WRPObject]? = [WRPObject]()
self.setValue(objects, forKey: element.localName)
// Fill that property with data
for objectData in (objectDataPack as! NSArray) {
// Create object
let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: element.className, parentObject: parentObject)
// Assign inverse relationship
if (element.inverseRelationshipType == .ToOne) {
dataObject.setValue(.Any, value: self, forKey: element.inverseName, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else {
var objects : [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.Any, value: objects, forKey: element.inverseName, optional: true, temporaryOptional: true)
}
// Append new data
objects!.append(dataObject)
}
// Write new objects back
self.setValue(objects, forKey: element.localName)
// Null encountered, null the output
} else if objectDataPack is NSNull {
self.setValue(nil, forKey: element.localName)
}
}
}
private func setValue(type: WRPPropertyAssignement, value : AnyObject?, forKey key: String, optional: Bool, temporaryOptional: Bool) -> Bool {
if ((optional || temporaryOptional) && value == nil) {
return false
}
if type == .Any {
self.setValue(value, forKey: key)
} else if type == .Double {
if value is Double {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(value?.doubleValue, forKey: key)
} else {
self.setValue(nil, forKey: key)
}
} else if type == .Int {
if value is Int {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(value?.integerValue, forKey: key)
} else {
self.setValue(nil, forKey: key)
}
} else if type == .Float {
if value is Float {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(value?.floatValue, forKey: key)
} else {
self.setValue(nil, forKey: key)
}
}
return true
}
private func setDictionary(value : Dictionary<AnyKey, AnyKey>?, forKey: String, optional: Bool, temporaryOptional: Bool) -> Bool {
if ((optional || temporaryOptional) && value == nil) {
return false
}
self.setValue((value as! AnyObject), forKey: forKey)
return true
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Variable creation
private func stringFromParameters(parameters : NSDictionary, key : String) -> String? {
if let value : NSString = parameters.valueForKeyPath(key) as? NSString {
return value as String
}
return nil
}
private func numberFromParameters(parameters : NSDictionary, key : String) -> NSNumber? {
if let value : NSNumber = parameters.valueForKeyPath(key) as? NSNumber {
return value as NSNumber
}
return nil
}
private func intFromParameters(parameters : NSDictionary, key : String) -> Int? {
if let value : NSNumber = parameters.valueForKeyPath(key) as? NSNumber {
return Int(value)
}
return nil
}
private func doubleFromParameters(parameters : NSDictionary, key : String) -> Double? {
if let value : NSNumber = parameters.valueForKeyPath(key) as? NSNumber {
return Double(value)
}
return nil
}
private func floatFromParameters(parameters : NSDictionary, key : String) -> Float? {
if let value : NSNumber = parameters.valueForKeyPath(key) as? NSNumber {
return Float(value)
}
return nil
}
private func boolFromParameters(parameters : NSDictionary, key : String) -> Bool? {
if let value : NSNumber = parameters.valueForKeyPath(key) as? NSNumber {
return Bool(value)
}
return nil
}
private func dateFromParameters(parameters : NSDictionary, key : String, format : String?) -> NSDate? {
if let value : String = parameters.valueForKeyPath(key) as? String {
// Create date formatter
let dateFormatter : NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.dateFromString(value)
}
return nil
}
private func arrayFromParameters(parameters : NSDictionary, key : String) -> Array<AnyObject>? {
if let value : Array = parameters.valueForKeyPath(key) as? Array<AnyObject> {
return value
}
return nil
}
private func dictionaryFromParameters(parameters : NSDictionary, key : String) -> NSDictionary? {
if let value : NSDictionary = parameters.valueForKeyPath(key) as? NSDictionary {
return value
}
return nil
}
private func dataObjectFromParameters(parameters: NSDictionary, objectType : WRPObject.Type, parentObject: WRPObject?) -> WRPObject {
let dataObject : WRPObject = objectType.init(parameters: parameters, parentObject: parentObject)
return dataObject
}
private func valueForKey(key: String, optional : Bool) -> AnyObject? {
return nil
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Object serialization
public func toDictionary() -> NSDictionary {
return self.toDictionaryWithSerializationOption(.None, without: [])
}
public func toDictionaryWithout(exclude : [String]) -> NSDictionary {
return self.toDictionaryWithSerializationOption(.None, without: exclude)
}
public func toDictionaryWithOnly(include : [String]) -> NSDictionary {
print("toDictionaryWithOnly(:) is not yet supported. Expected version: 0.2")
return NSDictionary()
// return self.toDictionaryWithSerializationOption(.None, with: include)
}
public func toDictionaryWithSerializationOption(option : WRPSerializationOption) -> NSDictionary {
return self.toDictionaryWithSerializationOption(option, without: [])
}
public func toDictionaryWithSerializationOption(option: WRPSerializationOption, without : [String]) -> NSDictionary {
// Create output
let outputParams : NSMutableDictionary = NSMutableDictionary()
// Get mapping parameters, go through all of them and serialize them into output
for element : WRPProperty in self.propertyMap() {
// Skip element if it should be excluded
if self.keyPathShouldBeExcluded(element.masterRemoteName, exclusionArray: without) {
continue
}
// Get actual value of property
let actualValue : AnyObject? = self.valueForKey(element.localName)
// Check for nil, if it is nil, we add <NSNull> object instead of value
if (actualValue == nil) {
if (option == WRPSerializationOption.IncludeNullProperties) {
outputParams.setObject(NSNull(), forKeyPath: element.remoteNames.first!)
}
} else {
// Otherwise add value itself
outputParams.setObject(self.valueOfElement(element, value: actualValue!), forKeyPath: element.masterRemoteName)
}
}
// Now get all relationships and call .toDictionary above all of them
for element : WRPRelation in self.relationMap() {
if self.keyPathShouldBeExcluded(element.remoteName, exclusionArray: without) {
continue
}
if (element.relationshipType == .ToMany) {
// Get data pack
if let actualValues = self.valueForKey(element.localName) as? [WRPObject] {
// Create data pack if exists, get all values, serialize those, and assign all of them
var outputArray = [NSDictionary]()
for actualValue : WRPObject in actualValues {
outputArray.append(actualValue.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)))
}
// Add all intros back
outputParams.setObject(outputArray, forKeyPath: element.remoteName)
} else {
// Add null value for relationship if needed
if (option == WRPSerializationOption.IncludeNullProperties) {
outputParams.setObject(NSNull(), forKey: element.remoteName)
}
}
} else {
// Get actual value of property
let actualValue : WRPObject? = self.valueForKey(element.localName) as? WRPObject
// Check for nil, if it is nil, we add <NSNull> object instead of value
if (actualValue == nil) {
if (option == WRPSerializationOption.IncludeNullProperties) {
outputParams.setObject(NSNull(), forKey: element.remoteName)
}
} else {
// Otherwise add value itself
outputParams.setObject(actualValue!.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)), forKey: element.remoteName)
}
}
}
return outputParams
}
private func keyPathForChildWithElement(element : WRPRelation, parentRules : [String]) -> [String] {
if (parentRules.count > 0) {
var newExlusionRules = [String]()
for parentRule : String in parentRules {
let objcString: NSString = parentRule as NSString
let range : NSRange = objcString.rangeOfString(String(format: "%@.", element.remoteName))
if range.location != NSNotFound && range.location == 0 {
let newPath = objcString.stringByReplacingCharactersInRange(range, withString: "")
newExlusionRules.append(newPath as String)
}
}
return newExlusionRules
} else {
return []
}
}
private func keyPathShouldBeExcluded(valueKeyPath : String, exclusionArray : [String]) -> Bool {
let objcString: NSString = valueKeyPath as NSString
for exclustionKeyPath : String in exclusionArray {
let range : NSRange = objcString.rangeOfString(exclustionKeyPath)
if range.location != NSNotFound && range.location == 0 {
return true
}
}
return false
}
private func valueOfElement(element: WRPProperty, value: AnyObject) -> AnyObject {
switch element.elementDataType {
case .Int:
return NSNumber(integer: value as! Int)
case .Float:
return NSNumber(float: value as! Float)
case .Double:
return NSNumber(double: value as! Double)
case .Bool:
return NSNumber(bool: value as! Bool)
case .Date:
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = element.format!
return formatter.stringFromDate(value as! NSDate)
default:
return value
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Convenience
public func updateWithJSONString(jsonString : String) -> Bool {
// Try to parse json data
if let jsonData : NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
// If it worked, update data of current object (dictionary is expected on root level)
do {
let jsonObject : AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
self.fillValues(jsonObject as! NSDictionary)
self.processClosestRelationships(jsonObject as! NSDictionary)
return true
} catch let error as NSError {
print ("Error while parsing a json object: \(error.domain)")
}
}
// Could not process json string
return false
}
public func updateWithDictionary(objectData : NSDictionary) -> Bool {
// Update data of current object
self.fillValues(objectData)
self.processClosestRelationships(objectData)
return true
}
public func excludeOnSerialization() -> [String] {
return []
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Debug
public func debugInstantiate() -> Bool {
return false
}
}
| mit | 545b1dd5c6b837d91949617093a0dce7 | 37.31068 | 201 | 0.542177 | 5.695258 | false | false | false | false |
gdollardollar/GMPageViewController | Source/PageViewController.swift | 1 | 9191 | //
// PageViewController.swift
// Tunsy
//
// Created by Guillaume on 19/07/15.
// Copyright (c) 2015 Tunsy. All rights reserved.
//
import UIKit
private let SWIPE_VELOCITY: CGFloat = 700
public class PageViewController: UIViewController {
public static let pageDidChange = Notification.Name(rawValue: "PageViewController.pageDidChangeNotification")
public weak var dataSource: PageViewControllerDataSource?
public weak var delegate: PageViewControllerDelegate?
public fileprivate(set) weak var visibleViewController: UIViewController?
fileprivate var beforeViewController: UIViewController?
fileprivate var afterViewController: UIViewController?
fileprivate var txMin: CGFloat = 0
fileprivate var txMax: CGFloat = 0
public var bounce: CGFloat = 0.1
override public func viewDidLoad() {
super.viewDidLoad()
self.view.clipsToBounds = true
let pan = UIPanGestureRecognizer(target: self, action: #selector(PageViewController.panRecognized(_:)))
pan.delegate = self
self.view.addGestureRecognizer(pan)
}
/**
Sets the visible view controller.
:param: viewController the new view controller
:param: direction the direction
:param: animated true if animated
:param: completion the completion block that will be called only if animated
*/
public func setViewController(_ viewController: UIViewController?, direction: UIPageViewController.NavigationDirection = .forward, animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
let current = visibleViewController
current?.willMove(toParent: nil)
if viewController != nil {
self.addChild(viewController!)
viewController!.view.frame = self.view.bounds
viewController!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(viewController!.view)
}
let finish: () -> Void = {
current?.view.removeFromSuperview()
current?.removeFromParent()
viewController?.didMove(toParent: self)
self.visibleViewController = viewController
}
if animated {
beforeViewController = direction == .reverse ? viewController : nil
afterViewController = direction == .forward ? viewController : nil
setTransform(0)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { () -> Void in
self.setTransform(direction == .forward ? -1 : 1)
}, completion: { (f) -> Void in
finish()
completion?(f)
})
} else {
finish()
}
}
}
extension PageViewController: UIGestureRecognizerDelegate {
fileprivate func addAnimationLayer(_ controller: UIViewController) -> CALayer {
let layer = CALayer()
layer.frame = visibleViewController!.view.layer.frame
let h = controller.view.isHidden
let a = controller.view.alpha
controller.view.isHidden = false
controller.view.alpha = 1
UIGraphicsBeginImageContextWithOptions(controller.view.frame.size, false, 0)
controller.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
controller.view.isHidden = h
controller.view.alpha = a
layer.contents = image
view.layer.addSublayer(layer)
return layer
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let pan = gestureRecognizer as? UIPanGestureRecognizer {
if self.dataSource == nil || self.visibleViewController == nil {
return false
} else if delegate?.pageViewController(self, panGestureRecognizerShouldBegin: pan) ?? true {
let width = self.view.bounds.width
if let before = self.dataSource!.pageViewController(self, viewControllerBefore: self.visibleViewController!) {
beforeViewController = before
txMax = width
} else {
beforeViewController = nil
txMax = bounce * width
}
if let after = self.dataSource!.pageViewController(self, viewControllerAfter: self.visibleViewController!) {
afterViewController = after
txMin = -width
} else {
afterViewController = nil
txMin = -bounce * width
}
if beforeViewController == nil && afterViewController == nil {
return false
} else {
return true
}
} else {
beforeViewController = nil
afterViewController = nil
return false
}
}
return true
}
fileprivate func setTransform(_ progress: CGFloat) {
delegate?.pageViewController(self, applyTransformsTo: beforeViewController, visible: visibleViewController, after: afterViewController, forProgress: progress)
}
@objc open func panRecognized(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
let handleVC: (UIViewController?) -> Void = {
if let vc = $0 {
self.addChild(vc)
vc.view.frame = self.view.bounds
self.view.addSubview(vc.view)
vc.didMove(toParent: self)
}
}
handleVC(beforeViewController)
handleVC(afterViewController)
delegate?.pageViewController(self, willStartPanWith: beforeViewController, visible: visibleViewController, after: afterViewController)
setTransform(0)
break
case .changed:
CATransaction.begin()
CATransaction.setDisableActions(true)
var t = sender.translation(in: self.view).x
if t > txMax {
t = txMax
} else if t < txMin {
t = txMin
}
setTransform(t / self.view.bounds.width)
CATransaction.commit()
default:
let tx = sender.translation(in: self.view).x
let vx = sender.velocity(in: self.view).x
let width = self.view.bounds.width
let finalTx: CGFloat
//TODO: check velocity
let newVisible: UIViewController
let oldVisible = visibleViewController!
if beforeViewController != nil && (tx > 0.5 * width || vx > SWIPE_VELOCITY) {
newVisible = beforeViewController!
finalTx = width
} else if afterViewController != nil && (tx < -0.5 * width || vx < -SWIPE_VELOCITY) {
newVisible = afterViewController!
finalTx = -width
} else {
newVisible = visibleViewController!
finalTx = 0
}
var duration = TimeInterval((finalTx - tx) / vx)
if duration > 0.3 {
duration = 0.3
} else if duration < 0.15 {
duration = 0.15
}
if oldVisible != newVisible {
delegate?.pageViewController(self, willTransitionFrom: oldVisible, to: newVisible)
}
beforeViewController?.willMove(toParent: nil)
afterViewController?.willMove(toParent: nil)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
self.setTransform(finalTx/width)
}, completion: { (_) -> Void in
for vc in [self.beforeViewController, self.visibleViewController, self.afterViewController] {
if vc != nil && vc! != newVisible {
vc!.view.removeFromSuperview()
vc!.removeFromParent()
}
}
self.visibleViewController = newVisible
self.beforeViewController = nil
self.afterViewController = nil
if oldVisible != newVisible {
self.delegate?.pageViewController(self, didTransitionFrom: oldVisible, to: newVisible)
NotificationCenter.default.post(name: PageViewController.pageDidChange, object: self)
}
})
}
}
}
extension PageViewController {
public func previous() {
if let vc = dataSource?.pageViewController(self, viewControllerBefore: visibleViewController!) {
setViewController(vc, direction: .reverse, animated: true, completion: nil)
}
}
public func next() {
if let vc = dataSource?.pageViewController(self, viewControllerAfter: visibleViewController!) {
setViewController(vc, direction: .forward, animated: true, completion: nil)
}
}
}
| mit | 7ecb41fa011642170f45c2636cd77bed | 32.543796 | 196 | 0.587858 | 5.676961 | false | false | false | false |
AlexIzh/Griddle | CollectionPresenter/UI/CollectionViewController.swift | 1 | 3863 | //
// CollectionViewController.swift
// CollectionPresenter
//
// Created by Ravil Khusainov on 10.02.2016.
// Copyright © 2016 Moqod. All rights reserved.
//
import Griddle
import UIKit
class CollectionViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
var presenter: DraggableCollectionPresenter<ArraySource<String>>!
lazy var dataSource: ArraySource<String> = ["First", "Second", "Third"]
var collectionLayout: DraggableCollectionViewFlowLayout? {
let layout = collectionView.collectionViewLayout as? DraggableCollectionViewFlowLayout
return layout
}
var newDragGestureForCell: UILongPressGestureRecognizer {
let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self.collectionLayout, action: #selector(DraggableCollectionViewFlowLayout.handleGesture(_:)))
longPressGestureRecogniser.delegate = self.collectionLayout
longPressGestureRecogniser.minimumPressDuration = 0.2
return longPressGestureRecogniser
}
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
let map = DefaultMap()
map.registrationItems = [RegistrationItem(viewType: .nib(UINib(nibName: "MocCollectionCell", bundle: nil)), id: "Cell")]
map.viewInfoGeneration = { _, _ in ViewInfo(identifier: "Cell", viewClass: MocCollectionCell.self) }
presenter = DraggableCollectionPresenter(collectionView, source: dataSource, map: map)
presenter.delegate.didUpdateCell = { [unowned self] cell, _, _ in
if let cell = cell as? MocCollectionCell {
cell.longPressGesture = self.newDragGestureForCell
}
}
presenter.delegate.didSelectCell = { [unowned self] _, _, path in
self.removeItem(at: path.index)
}
}
func setUpView() {
collectionLayout?.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
collectionLayout?.minimumInteritemSpacing = 10.0
collectionLayout?.minimumLineSpacing = 10.0
collectionLayout?.itemSize = CGSize(width: 140, height: 140)
collectionLayout?.scrollDirection = UICollectionViewScrollDirection.vertical
collectionLayout?.animating = true
}
func removeItem(at index: Int) {
let alert = UIAlertController(title: "Delete?", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.destructive, handler: { _ in
self.dataSource.perform(actions: [.delete(index: index)])
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
present(alert, animated: true, completion: nil)
}
@IBAction func addAction(_: AnyObject) {
let alert = UIAlertController(title: "Insert After:", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
for (index, item) in dataSource.items.enumerated() {
alert.addAction(UIAlertAction(title: item, style: UIAlertActionStyle.default, handler: { _ in
self.insertToIndex(index + 1)
}))
}
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func insertToIndex(_ index: Int) {
let alert = UIAlertController(title: "Enter text:", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { _ in
}
alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.default, handler: { _ in
guard let text = alert.textFields?.first?.text else { return }
self.dataSource.perform(actions: [.insert(index: index, model: text)])
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| mit | 47b8ba3b5ff7e7ddee8c4ee8d439ae74 | 41.43956 | 170 | 0.7087 | 4.894804 | false | false | false | false |
novacom34/StaticLib | StaticLib/Classes/AbstractCell.swift | 1 | 3763 | //
// AbstractCell.swift
// Pods
//
// Created by Roma Novakov on 29.05.16.
//
//
import Foundation
/*
@property (weak, nonatomic) id delegate;
@property (strong, nonatomic) VMBase *viewModel;
-(void)fillWithModel:(VMBase *)viewModel;
*/
// MARK: - ====== AbstractCellDelegateProtocol ======
@objc public protocol AbstractCellDelegateProtocol : class {
@objc optional func needFocus(_ cell: UITableViewCell)
}
// MARK: - ====== Abstract Cell Protocol ======
public protocol AbstractCellProtocol {
func fillWithViewModel(_ viewModel: AbstractViewModel?)
weak var viewModel: AbstractViewModel? {get set}
weak var delegat: AnyObject? {get set}
}
// MARK: - ====== Abstract TableView Cell Class ======
open class AbstractTableViewCell : UITableViewCell, AbstractCellProtocol, ObserverModelProtocol {
open weak var delegat: AnyObject?
open weak var viewModel: AbstractViewModel?{
didSet {
oldValue?.unregisterObserver(self)
viewModel?.registerObserver(self)
self.fillWithViewModel(viewModel)
}
}
override open func prepareForReuse() {
super.prepareForReuse()
self.viewModel = nil
}
// MARK: Abstract Cell Protocol Methods
open func fillWithViewModel(_ viewModel: AbstractViewModel?) {
}
open func needsFocus() {
if let cellDelegate = self.delegat {
if (cellDelegate.responds(to: #selector(AbstractCellDelegateProtocol.needFocus(_:)))) {
cellDelegate.perform(#selector(AbstractCellDelegateProtocol.needFocus(_:)),
with: self)
}
}
}
// MARK: Observer Model Methods
open func modelWillLoad(_ model: AbstractModel) {
}
open func modelDidLoad(_ model: AbstractModel) {
}
open func modelWillReload(_ model: AbstractModel) {
}
open func modelDidReload(_ model: AbstractModel) {
}
open func modelDidUnload(_ model: AbstractModel) {
}
open func modelDidCancel(_ model: AbstractModel) {
}
open func modelLoading(_ model: AbstractModel, withProgress progress: NSNumber) {
}
open func modelFailLoading(_ model: AbstractModel, withError error: NSString) {
}
}
// MARK: - ====== Abstract CollectionView Cell Class ======
open class AbstractCollectionViewCell : UICollectionViewCell, AbstractCellProtocol, ObserverModelProtocol{
open weak var delegat: AnyObject?
open weak var viewModel: AbstractViewModel? {
didSet {
oldValue?.unregisterObserver(self)
viewModel?.registerObserver(self)
self.fillWithViewModel(viewModel)
}
}
override open func prepareForReuse() {
super.prepareForReuse()
self.viewModel = nil
}
open func fillWithViewModel(_ viewModel: AbstractViewModel?) {
}
// MARK: Observer Model Methods
open func modelWillLoad(_ model: AbstractModel) {
}
open func modelDidLoad(_ model: AbstractModel) {
}
open func modelWillReload(_ model: AbstractModel) {
}
open func modelDidReload(_ model: AbstractModel) {
}
open func modelDidUnload(_ model: AbstractModel) {
}
open func modelDidCancel(_ model: AbstractModel) {
}
open func modelLoading(_ model: AbstractModel, withProgress progress: NSNumber) {
}
open func modelFailLoading(_ model: AbstractModel, withError error: NSString) {
}
}
| mit | 149c5bffde6049eab28c55588080a16d | 21.945122 | 106 | 0.602976 | 5.314972 | false | false | false | false |
nofelmahmood/Seam | Tests/Helpers/NSManagedObject+Helper.swift | 3 | 3755 | //
// NSManagedObject+Helper.swift
// Seam
//
// Created by Nofel Mahmood on 05/11/2015.
// Copyright © 2015 CloudKitSpace. All rights reserved.
//
import Foundation
import CoreData
extension NSManagedObjectContext {
class var mainContext: NSManagedObjectContext {
return CoreDataStack.defaultStack.managedObjectContext
}
}
extension NSManagedObject {
private class func mainContextIfContextIsNil(context: NSManagedObjectContext?) -> NSManagedObjectContext {
guard let context = context else {
return NSManagedObjectContext.mainContext
}
return context
}
private class func className() -> String {
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
class func all(inContext context: NSManagedObjectContext?) -> [NSManagedObject]? {
let managedObjectContext = mainContextIfContextIsNil(context)
let fetchRequest = NSFetchRequest(entityName: className())
if let result = try? managedObjectContext.executeFetchRequest(fetchRequest) {
return result as? [NSManagedObject]
}
return nil
}
class func all(inContext context: NSManagedObjectContext?, satisfyingPredicate predicate: NSPredicate) -> [NSManagedObject]? {
let managedObjectContext = mainContextIfContextIsNil(context)
let fetchRequest = NSFetchRequest(entityName: className())
fetchRequest.predicate = predicate
if let result = try? managedObjectContext.executeFetchRequest(fetchRequest) {
return result as? [NSManagedObject]
}
return nil
}
class func all(inContext context: NSManagedObjectContext?, whereKey key: String, isEqualToValue value: NSObject) -> [NSManagedObject]? {
let managedObjectContext = mainContextIfContextIsNil(context)
let fetchRequest = NSFetchRequest(entityName: className())
fetchRequest.predicate = NSPredicate(format: "%K == %@", key,value)
if let result = try? managedObjectContext.executeFetchRequest(fetchRequest) {
return result as? [NSManagedObject]
}
return nil
}
class func new(inContext context: NSManagedObjectContext?) -> NSManagedObject? {
let managedObjectContext = mainContextIfContextIsNil(context)
return NSEntityDescription.insertNewObjectForEntityForName(className(), inManagedObjectContext: managedObjectContext)
}
class func deleteAll(inContext context: NSManagedObjectContext?) throws {
let managedObjectContext = mainContextIfContextIsNil(context)
let fetchRequest = NSFetchRequest(entityName: className())
let objects = try managedObjectContext.executeFetchRequest(fetchRequest)
try objects.forEach { object in
managedObjectContext.deleteObject(object as! NSManagedObject)
try managedObjectContext.save()
}
}
class func deleteAll(inContext context: NSManagedObjectContext?, whereKey key:String, isEqualToValue value: NSObject) throws {
let managedObjectContext = mainContextIfContextIsNil(context)
let fetchRequest = NSFetchRequest(entityName: className())
fetchRequest.predicate = NSPredicate(format: "%K == %@", key,value)
let objects = try managedObjectContext.executeFetchRequest(fetchRequest)
try objects.forEach { object in
managedObjectContext.deleteObject(object as! NSManagedObject)
try managedObjectContext.save()
}
}
func addObject(value: NSManagedObject, forKey: String) {
self.willChangeValueForKey(forKey, withSetMutation: NSKeyValueSetMutationKind.UnionSetMutation, usingObjects: NSSet(object: value) as! Set<NSObject>)
let items = self.mutableSetValueForKey(forKey)
items.addObject(value)
self.didChangeValueForKey(forKey, withSetMutation: NSKeyValueSetMutationKind.UnionSetMutation, usingObjects: NSSet(object: value) as! Set<NSObject>)
}
} | mit | 9a8eb9a94e97972efd693386cd8bc4ff | 40.263736 | 153 | 0.76212 | 5.69651 | false | false | false | false |
coreymason/LAHacks2017 | ios/DreamWell/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift | 10 | 26899 | //
// LineChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class LineChartRenderer: LineRadarRenderer
{
open weak var dataProvider: LineChartDataProvider?
public init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let lineData = dataProvider?.lineData else { return }
for i in 0 ..< lineData.dataSetCount
{
guard let set = lineData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is ILineChartDataSet)
{
fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet")
}
drawDataSet(context: context, dataSet: set as! ILineChartDataSet)
}
}
}
open func drawDataSet(context: CGContext, dataSet: ILineChartDataSet)
{
if dataSet.entryCount < 1
{
return
}
context.saveGState()
context.setLineWidth(dataSet.lineWidth)
if dataSet.lineDashLengths != nil
{
context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
// if drawing cubic lines is enabled
switch dataSet.mode
{
case .linear: fallthrough
case .stepped:
drawLinear(context: context, dataSet: dataSet)
case .cubicBezier:
drawCubicBezier(context: context, dataSet: dataSet)
case .horizontalBezier:
drawHorizontalBezier(context: context, dataSet: dataSet)
}
context.restoreGState()
}
open func drawCubicBezier(context: CGContext, dataSet: ILineChartDataSet)
{
guard
let dataProvider = dataProvider,
let animator = animator
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
let intensity = dataSet.cubicIntensity
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prevDx: CGFloat = 0.0
var prevDy: CGFloat = 0.0
var curDx: CGFloat = 0.0
var curDy: CGFloat = 0.0
// Take an extra point from the left, and an extra from the right.
// That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart.
// So in the starting `prev` and `cur`, go -2, -1
// And in the `lastIndex`, add +1
let firstIndex = _xBounds.min + 1
let lastIndex = _xBounds.min + _xBounds.range
var prevPrev: ChartDataEntry! = nil
var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0))
var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0))
var next: ChartDataEntry! = cur
var nextIndex: Int = -1
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in stride(from: firstIndex, through: lastIndex, by: 1)
{
prevPrev = prev
prev = cur
cur = nextIndex == j ? next : dataSet.entryForIndex(j)
nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j
next = dataSet.entryForIndex(nextIndex)
if next == nil { break }
prevDx = CGFloat(cur.x - prevPrev.x) * intensity
prevDy = CGFloat(cur.y - prevPrev.y) * intensity
curDx = CGFloat(next.x - prev.x) * intensity
curDy = CGFloat(next.y - prev.y) * intensity
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y) * CGFloat(phaseY)),
control1: CGPoint(
x: CGFloat(prev.x) + prevDx,
y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)),
control2: CGPoint(
x: CGFloat(cur.x) - curDx,
y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
context.restoreGState()
}
open func drawHorizontalBezier(context: CGContext, dataSet: ILineChartDataSet)
{
guard
let dataProvider = dataProvider,
let animator = animator
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min)
var cur: ChartDataEntry! = prev
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in stride(from: (_xBounds.min + 1), through: _xBounds.range + _xBounds.min, by: 1)
{
prev = cur
cur = dataSet.entryForIndex(j)
let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0)
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y * phaseY)),
control1: CGPoint(
x: cpx,
y: CGFloat(prev.y * phaseY)),
control2: CGPoint(
x: cpx,
y: CGFloat(cur.y * phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
context.restoreGState()
}
open func drawCubicFill(
context: CGContext,
dataSet: ILineChartDataSet,
spline: CGMutablePath,
matrix: CGAffineTransform,
bounds: XBounds)
{
guard
let dataProvider = dataProvider
else { return }
if bounds.range <= 0
{
return
}
let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0
var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin)
var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin)
pt1 = pt1.applying(matrix)
pt2 = pt2.applying(matrix)
spline.addLine(to: pt1)
spline.addLine(to: pt2)
spline.closeSubpath()
if dataSet.fill != nil
{
drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
open func drawLinear(context: CGContext, dataSet: ILineChartDataSet)
{
guard
let dataProvider = dataProvider,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let entryCount = dataSet.entryCount
let isDrawSteppedEnabled = dataSet.mode == .stepped
let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// if drawing filled is enabled
if dataSet.isDrawFilledEnabled && entryCount > 0
{
drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds)
}
context.saveGState()
context.setLineCap(dataSet.lineCapType)
// more than 1 color
if dataSet.colors.count > 1
{
if _lineSegments.count != pointsPerEntryPair
{
// Allocate once in correct size
_lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair)
}
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
var e: ChartDataEntry! = dataSet.entryForIndex(j)
if e == nil { continue }
_lineSegments[0].x = CGFloat(e.x)
_lineSegments[0].y = CGFloat(e.y * phaseY)
if j < _xBounds.max
{
e = dataSet.entryForIndex(j + 1)
if e == nil { break }
if isDrawSteppedEnabled
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y)
_lineSegments[2] = _lineSegments[1]
_lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
else
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
}
else
{
_lineSegments[1] = _lineSegments[0]
}
for i in 0..<_lineSegments.count
{
_lineSegments[i] = _lineSegments[i].applying(valueToPixelMatrix)
}
if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if !viewPortHandler.isInBoundsLeft(_lineSegments[1].x)
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))
{
continue
}
// get the color that is set for this line-segment
context.setStrokeColor(dataSet.color(atIndex: j).cgColor)
context.strokeLineSegments(between: _lineSegments)
}
}
else
{ // only one color per dataset
var e1: ChartDataEntry!
var e2: ChartDataEntry!
e1 = dataSet.entryForIndex(_xBounds.min)
if e1 != nil
{
context.beginPath()
var firstPoint = true
for x in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1))
e2 = dataSet.entryForIndex(x)
if e1 == nil || e2 == nil { continue }
let pt = CGPoint(
x: CGFloat(e1.x),
y: CGFloat(e1.y * phaseY)
).applying(valueToPixelMatrix)
if firstPoint
{
context.move(to: pt)
firstPoint = false
}
else
{
context.addLine(to: pt)
}
if isDrawSteppedEnabled
{
context.addLine(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e1.y * phaseY)
).applying(valueToPixelMatrix))
}
context.addLine(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
).applying(valueToPixelMatrix))
}
if !firstPoint
{
context.setStrokeColor(dataSet.color(atIndex: 0).cgColor)
context.strokePath()
}
}
}
context.restoreGState()
}
open func drawLinearFill(context: CGContext, dataSet: ILineChartDataSet, trans: Transformer, bounds: XBounds)
{
guard let dataProvider = dataProvider else { return }
let filled = generateFilledPath(
dataSet: dataSet,
fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0,
bounds: bounds,
matrix: trans.valueToPixelMatrix)
if dataSet.fill != nil
{
drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
/// Generates the path that is used for filled drawing.
fileprivate func generateFilledPath(dataSet: ILineChartDataSet, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath
{
let phaseY = animator?.phaseY ?? 1.0
let isDrawSteppedEnabled = dataSet.mode == .stepped
let matrix = matrix
var e: ChartDataEntry!
let filled = CGMutablePath()
e = dataSet.entryForIndex(bounds.min)
if e != nil
{
filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
// create a new path
for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(x) else { continue }
if isDrawSteppedEnabled
{
guard let ePrev = dataSet.entryForIndex(x-1) else { continue }
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix)
}
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
// close up
e = dataSet.entryForIndex(bounds.range + bounds.min)
if e != nil
{
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
}
filled.closeSubpath()
return filled
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
var dataSets = lineData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if !dataSet.isDrawCirclesEnabled
{
valOffset = valOffset / 2
}
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in stride(from: _xBounds.min, through: min(_xBounds.min + _xBounds.range, _xBounds.max), by: 1)
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(
x: pt.x,
y: pt.y - CGFloat(valOffset) - valueFont.lineHeight),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)])
}
}
}
}
open override func drawExtras(context: CGContext)
{
drawCircles(context: context)
}
fileprivate func drawCircles(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
let phaseY = animator.phaseY
let dataSets = lineData.dataSets
var pt = CGPoint()
var rect = CGRect()
context.saveGState()
for i in 0 ..< dataSets.count
{
guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue }
if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0
{
continue
}
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let circleRadius = dataSet.circleRadius
let circleDiameter = circleRadius * 2.0
let circleHoleRadius = dataSet.circleHoleRadius
let circleHoleDiameter = circleHoleRadius * 2.0
let drawCircleHole = dataSet.isDrawCircleHoleEnabled &&
circleHoleRadius < circleRadius &&
circleHoleRadius > 0.0
let drawTransparentCircleHole = drawCircleHole &&
(dataSet.circleHoleColor == nil ||
dataSet.circleHoleColor == NSUIColor.clear)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor)
rect.origin.x = pt.x - circleRadius
rect.origin.y = pt.y - circleRadius
rect.size.width = circleDiameter
rect.size.height = circleDiameter
if drawTransparentCircleHole
{
// Begin path for circle with hole
context.beginPath()
context.addEllipse(in: rect)
// Cut hole in path
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.addEllipse(in: rect)
// Fill in-between
context.fillPath(using: .evenOdd)
}
else
{
context.fillEllipse(in: rect)
if drawCircleHole
{
context.setFillColor(dataSet.circleHoleColor!.cgColor)
// The hole rect
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.fillEllipse(in: rect)
}
}
}
}
context.restoreGState()
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData,
let animator = animator
else { return }
let chartXMax = dataProvider.chartXMax
context.saveGState()
for high in indices
{
guard let set = lineData.getDataSetByIndex(high.dataSetIndex) as? ILineChartDataSet
, set.isHighlightEnabled
else { continue }
guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let x = high.x // get the x-position
let y = high.y * Double(animator.phaseY)
if x > chartXMax * animator.phaseX
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
let pt = trans.pixelForValues(x: x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
}
| mit | e257ce8055c00417cecd6aaa8bdb0261 | 34.580688 | 155 | 0.492695 | 5.728066 | false | false | false | false |
srn214/Floral | Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/views/CLImagePickerCamaroCell.swift | 2 | 1290 | //
// CLImagePickerCamaroCell.swift
// ImageDeal
//
// Created by darren on 2017/8/2.
// Copyright © 2017年 陈亮陈亮. All rights reserved.
//
import UIKit
typealias clickCamaroCellClouse = () -> ()
class CLImagePickerCamaroCell: UICollectionViewCell {
@objc var clickCamaroCell: clickCamaroCellClouse?
@objc lazy var iconView: UIImageView = {
let img = UIImageView.init(frame: CGRect(x: 0, y: 0, width: cellH, height: cellH))
img.image = UIImage(named: "takePicture", in: BundleUtil.getCurrentBundle(), compatibleWith: nil)
img.isUserInteractionEnabled = true
return img
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.iconView)
self.iconView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(clickImage)))
}
@objc func clickImage() {
if clickCamaroCell != nil {
self.clickCamaroCell!()
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.iconView.frame = CGRect(x: 0, y: 0, width: cellH, height: cellH)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1be771616a3d2ef04fc8ce9e1838bdd5 | 27.422222 | 116 | 0.634871 | 4.335593 | false | false | false | false |
bekin/issue-13-viper-swift | VIPER-SWIFT/Classes/Modules/List/Application Logic/Interactor/UpcomingItem.swift | 6 | 1004 | //
// UpcomingItem.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
struct UpcomingItem : Equatable {
let title : String = ""
let dueDate : NSDate = NSDate()
let dateRelation : NearTermDateRelation = NearTermDateRelation.OutOfRange
init(title: String, dueDate: NSDate, dateRelation: NearTermDateRelation) {
self.title = title
self.dueDate = dueDate
self.dateRelation = dateRelation
}
}
func == (leftSide: UpcomingItem, rightSide: UpcomingItem) -> Bool {
var hasEqualSections = false
hasEqualSections = rightSide.title == leftSide.title
if hasEqualSections == false {
return false
}
hasEqualSections = rightSide.dueDate == rightSide.dueDate
if hasEqualSections == false {
return false
}
hasEqualSections = rightSide.dateRelation == rightSide.dateRelation
return hasEqualSections
} | mit | 5cf43cdddb0c3ed6453cd4661977826a | 24.125 | 78 | 0.669323 | 4.648148 | false | false | false | false |
enkaism/SuperTextView | Pod/Classes/SuperTextView.swift | 1 | 2697 | //
// SuperTextView.swift
// SuperTextView
//
// Created by 木村舞由 on 11/20/15.
// Copyright © 2015 daisuke_kobayashi. All rights reserved.
//
import UIKit
@IBDesignable
class SuperTextView : UIView, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var placeHolderLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!
@IBInspectable var placeholder: String = "" {
didSet {
placeHolderLabel.text = placeholder
}
}
@IBInspectable var maxLength: Int = -1 {
didSet {
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
print("init")
let bundle = NSBundle(forClass: SuperTextView.self)
let nib = UINib(nibName: "SuperTextView", bundle: NSBundle(URL: bundle.URLForResource("SuperTextView", withExtension: "bundle")!))
let view = nib.instantiateWithOwner(self, options: nil).first as! UIView
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let bindings = ["view": view]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
textView.delegate = self
placeHolderLabel.font = textView.font
textViewHeightConstraint.constant = textView.sizeThatFits(CGSizeMake(textView.frame.width, CGFloat(MAXFLOAT))).height
}
func textViewDidChangeSelection(textView: UITextView) {
var length = textView.text.characters.count
placeHolderLabel.text = length > 0 ? "" : placeholder
if maxLength == -1 {
} else if length > maxLength {
let _text: NSMutableString = NSMutableString(string: textView.text)
_text.deleteCharactersInRange(NSRange(location: textView.text.characters.count - 1, length: 1))
textView.text = _text as String
length--
}
countLabel.text = "\(length)"
textViewHeightConstraint.constant = textView.sizeThatFits(CGSizeMake(textView.frame.width, CGFloat(MAXFLOAT))).height
}
} | mit | b4a03a3ade5229a8b3dbdee9b0170ef9 | 32.6125 | 138 | 0.63058 | 5.169231 | false | false | false | false |
likumb/LJWebImage | LJWebImage/LJWebImage/LIJWebImage/String+Path.swift | 1 | 1095 | //
// String+Path.swift
// LIJWebImage
//
// Created by 李俊 on 15/7/27.
// Copyright © 2015年 李俊. All rights reserved.
//
import Foundation
extension String {
func documentPath() -> String {
let path = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true).last
let nsPath: NSString = path!
let nsSelf: NSString = self
return nsPath.stringByAppendingPathComponent(nsSelf.lastPathComponent)
}
func cachesPath() -> String {
let path = NSSearchPathForDirectoriesInDomains( .CachesDirectory, .UserDomainMask, true).last
let nsPath: NSString = path!
let nsSelf: NSString = self
return nsPath.stringByAppendingPathComponent(nsSelf.lastPathComponent)
}
func tempPath() -> String {
let path: NSString = NSTemporaryDirectory()
let nsSelf: NSString = self
return path.stringByAppendingPathComponent(nsSelf.lastPathComponent)
}
}
| mit | e0cc5b8f08ae1a4c447774f987bc36e6 | 23.044444 | 103 | 0.610906 | 5.383085 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/Image.swift | 1 | 10999 | //
// Image.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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 Foundation
extension Storefront {
/// Represents an image resource.
open class ImageQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = Image
/// A word or phrase to share the nature or contents of an image.
@discardableResult
open func altText(alias: String? = nil) -> ImageQuery {
addField(field: "altText", aliasSuffix: alias)
return self
}
/// The original height of the image in pixels. Returns `null` if the image is
/// not hosted by Shopify.
@discardableResult
open func height(alias: String? = nil) -> ImageQuery {
addField(field: "height", aliasSuffix: alias)
return self
}
/// A unique identifier for the image.
@discardableResult
open func id(alias: String? = nil) -> ImageQuery {
addField(field: "id", aliasSuffix: alias)
return self
}
/// The location of the original image as a URL. If there are any existing
/// transformations in the original source URL, they will remain and not be
/// stripped.
@available(*, deprecated, message:"Use `url` instead.")
@discardableResult
open func originalSrc(alias: String? = nil) -> ImageQuery {
addField(field: "originalSrc", aliasSuffix: alias)
return self
}
/// The location of the image as a URL.
@available(*, deprecated, message:"Use `url` instead.")
@discardableResult
open func src(alias: String? = nil) -> ImageQuery {
addField(field: "src", aliasSuffix: alias)
return self
}
/// The location of the transformed image as a URL. All transformation
/// arguments are considered "best-effort". If they can be applied to an image,
/// they will be. Otherwise any transformations which an image type does not
/// support will be ignored.
///
/// - parameters:
/// - maxWidth: Image width in pixels between 1 and 5760.
/// - maxHeight: Image height in pixels between 1 and 5760.
/// - crop: Crops the image according to the specified region.
/// - scale: Image size multiplier for high-resolution retina displays. Must be between 1 and 3.
/// - preferredContentType: Best effort conversion of image into content type (SVG -> PNG, Anything -> JPG, Anything -> WEBP are supported).
///
@available(*, deprecated, message:"Use `url(transform:)` instead")
@discardableResult
open func transformedSrc(alias: String? = nil, maxWidth: Int32? = nil, maxHeight: Int32? = nil, crop: CropRegion? = nil, scale: Int32? = nil, preferredContentType: ImageContentType? = nil) -> ImageQuery {
var args: [String] = []
if let maxWidth = maxWidth {
args.append("maxWidth:\(maxWidth)")
}
if let maxHeight = maxHeight {
args.append("maxHeight:\(maxHeight)")
}
if let crop = crop {
args.append("crop:\(crop.rawValue)")
}
if let scale = scale {
args.append("scale:\(scale)")
}
if let preferredContentType = preferredContentType {
args.append("preferredContentType:\(preferredContentType.rawValue)")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
addField(field: "transformedSrc", aliasSuffix: alias, args: argsString)
return self
}
/// The location of the image as a URL. If no transform options are specified,
/// then the original image will be preserved including any pre-applied
/// transforms. All transformation options are considered "best-effort". Any
/// transformation that the original image type doesn't support will be
/// ignored. If you need multiple variations of the same image, then you can
/// use [GraphQL aliases](https://graphql.org/learn/queries/#aliases).
///
/// - parameters:
/// - transform: A set of options to transform the original image.
///
@discardableResult
open func url(alias: String? = nil, transform: ImageTransformInput? = nil) -> ImageQuery {
var args: [String] = []
if let transform = transform {
args.append("transform:\(transform.serialize())")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
addField(field: "url", aliasSuffix: alias, args: argsString)
return self
}
/// The original width of the image in pixels. Returns `null` if the image is
/// not hosted by Shopify.
@discardableResult
open func width(alias: String? = nil) -> ImageQuery {
addField(field: "width", aliasSuffix: alias)
return self
}
}
/// Represents an image resource.
open class Image: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = ImageQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "altText":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return value
case "height":
if value is NSNull { return nil }
guard let value = value as? Int else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return Int32(value)
case "id":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return GraphQL.ID(rawValue: value)
case "originalSrc":
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "src":
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "transformedSrc":
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "url":
guard let value = value as? String else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "width":
if value is NSNull { return nil }
guard let value = value as? Int else {
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
return Int32(value)
default:
throw SchemaViolationError(type: Image.self, field: fieldName, value: fieldValue)
}
}
/// A word or phrase to share the nature or contents of an image.
open var altText: String? {
return internalGetAltText()
}
func internalGetAltText(alias: String? = nil) -> String? {
return field(field: "altText", aliasSuffix: alias) as! String?
}
/// The original height of the image in pixels. Returns `null` if the image is
/// not hosted by Shopify.
open var height: Int32? {
return internalGetHeight()
}
func internalGetHeight(alias: String? = nil) -> Int32? {
return field(field: "height", aliasSuffix: alias) as! Int32?
}
/// A unique identifier for the image.
open var id: GraphQL.ID? {
return internalGetId()
}
func internalGetId(alias: String? = nil) -> GraphQL.ID? {
return field(field: "id", aliasSuffix: alias) as! GraphQL.ID?
}
/// The location of the original image as a URL. If there are any existing
/// transformations in the original source URL, they will remain and not be
/// stripped.
@available(*, deprecated, message:"Use `url` instead.")
open var originalSrc: URL {
return internalGetOriginalSrc()
}
func internalGetOriginalSrc(alias: String? = nil) -> URL {
return field(field: "originalSrc", aliasSuffix: alias) as! URL
}
/// The location of the image as a URL.
@available(*, deprecated, message:"Use `url` instead.")
open var src: URL {
return internalGetSrc()
}
func internalGetSrc(alias: String? = nil) -> URL {
return field(field: "src", aliasSuffix: alias) as! URL
}
/// The location of the transformed image as a URL. All transformation
/// arguments are considered "best-effort". If they can be applied to an image,
/// they will be. Otherwise any transformations which an image type does not
/// support will be ignored.
@available(*, deprecated, message:"Use `url(transform:)` instead")
open var transformedSrc: URL {
return internalGetTransformedSrc()
}
@available(*, deprecated, message:"Use `url(transform:)` instead")
open func aliasedTransformedSrc(alias: String) -> URL {
return internalGetTransformedSrc(alias: alias)
}
func internalGetTransformedSrc(alias: String? = nil) -> URL {
return field(field: "transformedSrc", aliasSuffix: alias) as! URL
}
/// The location of the image as a URL. If no transform options are specified,
/// then the original image will be preserved including any pre-applied
/// transforms. All transformation options are considered "best-effort". Any
/// transformation that the original image type doesn't support will be
/// ignored. If you need multiple variations of the same image, then you can
/// use [GraphQL aliases](https://graphql.org/learn/queries/#aliases).
open var url: URL {
return internalGetUrl()
}
open func aliasedUrl(alias: String) -> URL {
return internalGetUrl(alias: alias)
}
func internalGetUrl(alias: String? = nil) -> URL {
return field(field: "url", aliasSuffix: alias) as! URL
}
/// The original width of the image in pixels. Returns `null` if the image is
/// not hosted by Shopify.
open var width: Int32? {
return internalGetWidth()
}
func internalGetWidth(alias: String? = nil) -> Int32? {
return field(field: "width", aliasSuffix: alias) as! Int32?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit | 7613362d3298138ad54daf77b8d4853a | 33.91746 | 206 | 0.68879 | 3.905895 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Internals/Audio File/AKAudioFile+Processing.swift | 1 | 8764 | //
// AKAudioFile+Processing.swift
// AudioKit
//
// Created by Laurent Veliscek, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
//
// IMPORTANT: Any AKAudioFile process will output a .caf AKAudioFile
// set with a PCM Linear Encoding (no compression)
// But it can be applied to any readable file (.wav, .m4a, .mp3...)
//
extension AKAudioFile {
/// Normalize an AKAudioFile to have a peak of newMaxLevel dB.
///
/// - Parameters:
/// - baseDir: where the file will be located, can be set to .resources, .documents or .temp
/// - name: the name of the file without its extension (String). If none is given, a unique random name is used.
/// - newMaxLevel: max level targeted as a Float value (default if 0 dB)
///
/// - returns: An AKAudioFile, or nil if init failed.
///
public func normalized(baseDir: BaseDirectory = .temp,
name: String = UUID().uuidString,
newMaxLevel: Float = 0.0 ) throws -> AKAudioFile {
let level = self.maxLevel
var outputFile = try AKAudioFile (writeIn: baseDir, name: name)
if self.samplesCount == 0 {
AKLog("WARNING AKAudioFile: cannot normalize an empty file")
return try AKAudioFile(forReading: outputFile.url)
}
if level == Float.leastNormalMagnitude {
AKLog("WARNING AKAudioFile: cannot normalize a silent file")
return try AKAudioFile(forReading: outputFile.url)
}
let gainFactor = Float( pow(10.0, newMaxLevel / 20.0) / pow(10.0, level / 20.0))
let arrays = self.floatChannelData ?? [[]]
var newArrays: [[Float]] = []
for array in arrays {
let newArray = array.map { $0 * gainFactor }
newArrays.append(newArray)
}
outputFile = try AKAudioFile(createFileFromFloats: newArrays,
baseDir: baseDir,
name: name)
return try AKAudioFile(forReading: outputFile.url)
}
/// Returns an AKAudioFile with audio reversed (will playback in reverse from end to beginning).
///
/// - Parameters:
/// - baseDir: where the file will be located, can be set to .resources, .documents or .temp
/// - name: the name of the file without its extension (String). If none is given, a unique random name is used.
///
/// - Returns: An AKAudioFile, or nil if init failed.
///
public func reversed(baseDir: BaseDirectory = .temp,
name: String = UUID().uuidString ) throws -> AKAudioFile {
var outputFile = try AKAudioFile (writeIn: baseDir, name: name)
if self.samplesCount == 0 {
return try AKAudioFile(forReading: outputFile.url)
}
let arrays = self.floatChannelData ?? [[]]
var newArrays: [[Float]] = []
for array in arrays {
newArrays.append(Array(array.reversed()))
}
outputFile = try AKAudioFile(createFileFromFloats: newArrays,
baseDir: baseDir,
name: name)
return try AKAudioFile(forReading: outputFile.url)
}
/// Returns an AKAudioFile with appended audio data from another AKAudioFile.
///
/// Notice that Source file and appended file formats must match.
///
/// - Parameters:
/// - file: an AKAudioFile that will be used to append audio from.
/// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
/// - name: the name of the file without its extension (String). If none is given, a unique random name is used.
///
/// - Returns: An AKAudioFile, or nil if init failed.
///
public func appendedBy(file: AKAudioFile,
baseDir: BaseDirectory = .temp,
name: String = UUID().uuidString) throws -> AKAudioFile {
var sourceBuffer = self.pcmBuffer
var appendedBuffer = file.pcmBuffer
if self.fileFormat != file.fileFormat {
AKLog("WARNING AKAudioFile.append: appended file should be of same format as source file")
AKLog("WARNING AKAudioFile.append: trying to fix by converting files...")
// We use extract method to get a .CAF file with the right format for appending
// So sourceFile and appended File formats should match
do {
// First, we convert the source file to .CAF using extract()
let convertedFile = try self.extracted()
sourceBuffer = convertedFile.pcmBuffer
AKLog("AKAudioFile.append: source file has been successfully converted")
if convertedFile.fileFormat != file.fileFormat {
do {
// If still don't match we convert the appended file to .CAF using extract()
let convertedAppendFile = try file.extracted()
appendedBuffer = convertedAppendFile.pcmBuffer
AKLog("AKAudioFile.append: appended file has been successfully converted")
} catch let error as NSError {
AKLog("ERROR AKAudioFile.append: cannot set append file format match source file format")
throw error
}
}
} catch let error as NSError {
AKLog("ERROR AKAudioFile: Cannot convert sourceFile to .CAF")
throw error
}
}
// We check that both pcm buffers share the same format
if appendedBuffer.format != sourceBuffer.format {
AKLog("ERROR AKAudioFile.append: Couldn't match source file format with appended file format")
let userInfo: [AnyHashable: Any] = [
NSLocalizedDescriptionKey: NSLocalizedString(
"AKAudioFile append process Error",
value: "Couldn't match source file format with appended file format",
comment: ""),
NSLocalizedFailureReasonErrorKey: NSLocalizedString(
"AKAudioFile append process Error",
value: "Couldn't match source file format with appended file format",
comment: "")
]
throw NSError(domain: "AKAudioFile ASync Process Unknown Error", code: 0, userInfo: userInfo as? [String : Any])
}
let outputFile = try AKAudioFile (writeIn: baseDir, name: name)
// Write the buffer in file
do {
try outputFile.write(from: sourceBuffer)
} catch let error as NSError {
AKLog("ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)")
throw error
}
do {
try outputFile.write(from: appendedBuffer)
} catch let error as NSError {
AKLog("ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)")
throw error
}
return try AKAudioFile(forReading: outputFile.url)
}
/// Returns an AKAudioFile that will contain a range of samples from the current AKAudioFile
///
/// - Parameters:
/// - fromSample: the starting sampleFrame for extraction.
/// - toSample: the ending sampleFrame for extraction
/// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
/// - name: the name of the file without its extension (String). If none is given, a unique random name is used.
///
/// - Returns: An AKAudioFile, or nil if init failed.
///
public func extracted(fromSample: Int64 = 0,
toSample: Int64 = 0,
baseDir: BaseDirectory = .temp,
name: String = UUID().uuidString) throws -> AKAudioFile {
let fixedFrom = abs(fromSample)
let fixedTo: Int64 = toSample == 0 ? Int64(self.samplesCount) : min(toSample, Int64(self.samplesCount))
if fixedTo <= fixedFrom {
AKLog("ERROR AKAudioFile: cannot extract, from must be less than to")
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil)
}
let arrays = self.floatChannelData ?? [[]]
var newArrays: [[Float]] = []
for array in arrays {
let extract = Array(array[Int(fixedFrom)..<Int(fixedTo)])
newArrays.append(extract)
}
let newFile = try AKAudioFile(createFileFromFloats: newArrays, baseDir: baseDir, name: name)
return try AKAudioFile(forReading: newFile.url)
}
}
| mit | d78d4d5664cc8cfb3de9101fdf10263f | 42.167488 | 124 | 0.591236 | 5.082947 | false | false | false | false |
TabletopAssistant/DiceKit | DiceKit/SubtractionExpression.swift | 1 | 2353 | //
// SubtractionExpression.swift
// DiceKit
//
// Created by Jonathan Hoffman on 8/15/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
public struct SubtractionExpression<LeftExpression: protocol<ExpressionType, Equatable>, RightExpression: protocol<ExpressionType, Equatable>>: Equatable {
public let minuend: LeftExpression
public let subtrahend: RightExpression
public init(_ minuend: LeftExpression, _ subtrahend: RightExpression) {
self.minuend = minuend
self.subtrahend = subtrahend
}
}
// MARK: - ExpressionType
extension SubtractionExpression: ExpressionType {
public typealias Result = SubtractionExpressionResult<LeftExpression.Result, RightExpression.Result>
public func evaluate() -> Result {
let leftResult = minuend.evaluate()
let rightResult = subtrahend.evaluate()
return Result(leftResult, rightResult)
}
public var probabilityMass: ExpressionProbabilityMass {
return minuend.probabilityMass && subtrahend.probabilityMass.negate()
}
}
// MARK: - CustomStringConvertible
extension SubtractionExpression: CustomStringConvertible {
public var description: String {
return "\(minuend) - \(subtrahend)"
}
}
// MARK: - CustomDebugStringConvertible
extension SubtractionExpression: CustomDebugStringConvertible {
public var debugDescription: String {
return "\(String(reflecting: minuend)) - \(String(reflecting: subtrahend))"
}
}
// MARK: - Equatable
public func == <L, R>(lhs: SubtractionExpression<L, R>, rhs: SubtractionExpression<L, R>) -> Bool {
return lhs.minuend == rhs.minuend && lhs.subtrahend == rhs.subtrahend
}
// MARK: - Operators
public func - <L: protocol<ExpressionType, Equatable>, R: protocol<ExpressionType, Equatable>>(lhs: L, rhs: R) -> SubtractionExpression<L, R> {
return SubtractionExpression(lhs, rhs)
}
public func - <R: protocol<ExpressionType, Equatable>>(lhs: ExpressionResultValue, rhs: R) -> SubtractionExpression<Constant, R> {
return SubtractionExpression(Constant(lhs), rhs)
}
public func - <L: protocol<ExpressionType, Equatable>>(lhs: L, rhs: ExpressionResultValue) -> SubtractionExpression<L, Constant> {
return SubtractionExpression(lhs, Constant(rhs))
}
| apache-2.0 | 0f8b49cf36e13c17a56c50d106a156c6 | 28.4 | 155 | 0.707908 | 4.722892 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/UserCenter/controller/SKUserCenterController.swift | 1 | 5417 | //
// SKUserCenterController.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/30.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKUserCenterController: UIViewController {
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var tableView: UITableView?
var titleArray = ["账号信息", "我的关注", "我的留言", "设置"]
var userShared: SKUserShared?
var headView: SKUserCenterHeadView?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccess), name: NSNotification.Name(rawValue: SKUserLoginSuccessNotifiction), object: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: SKNoUserLoginNotifiction), object: nil, queue: OperationQueue.main){ notifiction in
self.present(SKNavigationController(rootViewController: SKLoginController()), animated: true, completion: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(userLogoutSuccess), name: NSNotification.Name(rawValue: SKUserLogoutNotifiction), object: nil)
loadData()
addSubView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func loadData() {
userShared = SKUserShared.getUserShared()
}
func userLoginSuccess() {
self.userShared = SKUserShared.getUserShared()
self.headView?.userInfo = self.userShared?.userInfo
}
func userLogoutSuccess() {
self.userShared = SKUserShared.getUserShared()
tableView?.reloadData()
}
}
extension SKUserCenterController{
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.title = "我"
navBar?.items = [navItem!]
tableView = UITableView(frame: view.bounds)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.separatorStyle = .none
tableView?.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
tableView?.bounces = false
tableView?.showsVerticalScrollIndicator = false
view.insertSubview(tableView!, at: 0)
}
}
extension SKUserCenterController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "userCenterCell")
cell.selectionStyle = .none
let lineView = UIView(frame: CGRect(x: 16, y: 56, width: SKScreenWidth-32, height: 1))
lineView.backgroundColor = UIColor(white: 245/255.0, alpha: 1)
cell.contentView.addSubview(lineView)
let arrowImageView = UIImageView(frame: CGRect(x: SKScreenWidth-39, y: 18, width: 13, height: 22))
arrowImageView.image = UIImage(named: "icon_content")
cell.contentView.addSubview(arrowImageView)
cell.textLabel?.text = titleArray[indexPath.row]
cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
cell.textLabel?.textColor = UIColor(white: 152/255.0, alpha: 1)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 3 {
navigationController?.pushViewController(SKUserCenterSetController(), animated: true)
} else {
if userShared == nil {
self.present(SKNavigationController(rootViewController: SKLoginController()), animated: true, completion: nil)
} else {
if indexPath.row == 0 {
navigationController?.pushViewController(SKUserCenterAccountInfoController(), animated: true)
} else if indexPath.row == 1 {
navigationController?.pushViewController(SKMyFocusController(), animated: true)
} else if indexPath.row == 2 {
navigationController?.pushViewController(SKMyMessageController(), animated: true)
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 57
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 223
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
headView = SKUserCenterHeadView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 223))
headView?.backgroundColor = UIColor(white: 247/255.0, alpha: 1)
if userShared != nil {
headView?.userInfo = userShared?.userInfo
}
return headView
}
}
| apache-2.0 | 1193db9898e91c1ec198d55273190bea | 37.428571 | 172 | 0.65223 | 5.080264 | false | false | false | false |
milseman/swift | test/Serialization/enum.swift | 13 | 795 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -module-name def_enum -o %t %S/Inputs/def_enum.swift %S/Inputs/def_enum_derived.swift
// RUN: llvm-bcanalyzer %t/def_enum.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -typecheck -I %t %s -o /dev/null
// RUN: %target-swift-frontend -emit-sil -I %t %s -o /dev/null
// CHECK-NOT: UnknownCode
import def_enum
extension Basic {
init(silly: Int) {
self.init()
self = .HasType(silly)
}
}
var a : Basic
a = .Untyped
a.doSomething()
a = .HasType(4)
a.doSomething()
var g = Generic.Left(false)
g = .Right(true)
var lazy = Lazy.Thunk({ 42 })
var comp : Computable = lazy
comp.compute()
lazy.compute()
struct Tea {}
let meal = Breakfast<Basic>.Bacon
let n = meal.rawValue
do { throw meal } catch {}
| apache-2.0 | c8addaabe3f873c3ffdd87fa91f2dd93 | 20.486486 | 129 | 0.669182 | 2.819149 | false | false | false | false |
salimbraksa/SBSlideMenu | SBSlideMenu/Extensions.swift | 1 | 2840 | //
// Extensions.swift
// Shop
//
// Created by Salim Ive on 12/10/15.
// Copyright © 2015 Braksa. All rights reserved.
//
import UIKit
extension CAAnimationGroup {
var basicAnimations: [CABasicAnimation]? {
return convertToBasicAnimation()
}
private func convertToBasicAnimation() -> [CABasicAnimation]? {
// Unwrap animations
guard let animations = self.animations else { return nil }
// The array that will hold basic animation
var basicAnimations = [CABasicAnimation]()
// Loop through each animation
for animation in animations {
// If animation is a basic animation
if animation.isKindOfClass(CABasicAnimation) {
basicAnimations.append(animation as! CABasicAnimation)
} else if animation.isKindOfClass(CAAnimationGroup) {
basicAnimations.appendContentsOf((animation as! CAAnimationGroup).convertToBasicAnimation() ?? [])
}
}
return basicAnimations
}
}
extension CAAnimation {
var name: String? {
get {
return valueForKey("Animation Name") as? String
} set {
setValue(newValue, forKey: "Animation Name")
}
}
}
extension CALayer {
var maxOfAnimationsDurations: Double {
get {
return valueForKey("Maximum Of Animations Duration") as? Double ?? -1
} set {
setValue(newValue, forKey: "Maximum Of Animations Duration")
}
}
func explicitAnimationKeys() -> [String]? {
let keys = valueForKey("Explicit Animation Keys") as? [String]
return keys
}
func addExplicitAnimationKey(key: String?) {
guard let key = key else { return }
var keys = explicitAnimationKeys() ?? []
keys.append(key)
setValue(keys, forKey: "Explicit Animation Keys")
}
func removeExplicitAnimationKey(key: String?) {
guard let key = key else { return }
var keys = explicitAnimationKeys() ?? []
guard let index = keys.indexOf(key) else { return }
keys.removeAtIndex(index)
setValue(keys, forKey: "Explicit Animation Keys")
}
public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
// Remove animation name for keys
removeExplicitAnimationKey(anim.name)
// Recalculate the maximum of the animations durations
let allAnimations = animationKeys()?.map { animationForKey($0)! }
let durations = allAnimations?.map { $0.valueForKey("duration") as? Double ?? -1 }
maxOfAnimationsDurations = durations?.maxElement() ?? -1
// Report to the delegate that this layer's animation is stopped
Animator.sharedInstance.layerAnimationDidStop(self, animation: anim, finished: flag)
}
} | mit | d3fe3ec7587d043215b8ea33898fe26b | 27.4 | 110 | 0.632617 | 4.989455 | false | false | false | false |
Sajjon/ViewComposer | Source/Classes/ViewStyle/UIView+ViewStyle/UIControl+ViewStyle.swift | 1 | 909 | //
// UIControl+ViewStyle.swift
// ViewComposer
//
// Created by Alexander Cyon on 2017-06-22.
//
//
import Foundation
internal extension UIControl {
func applyToSuperclass(_ style: ViewStyle) {
style.attributes.forEach {
switch $0 {
case .contentVerticalAlignment(let alignment):
contentVerticalAlignment = alignment
case .contentHorizontalAlignment(let alignment):
contentHorizontalAlignment = alignment
case .enabled(let enabled):
isEnabled = enabled
case .selected(let selected):
isSelected = selected
case .highlighted(let highlighted):
isHighlighted = highlighted
case .targets(let actors):
actors.forEach { addTarget(using: $0) }
default:
break
}
}
}
}
| mit | 08355b77729f5e6e23a26e8a1c5ac0c9 | 27.40625 | 60 | 0.565457 | 5.645963 | false | false | false | false |
coodly/ios-gambrinus | Packages/Sources/KioskUI/Autolayout/UIView+Autolayout.swift | 1 | 1143 | /*
* Copyright 2018 Coodly LLC
*
* 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
internal extension UIView {
func pinToSuperviewEdges(insets: UIEdgeInsets = .zero) {
guard let s = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
topAnchor.constraint(equalTo: s.topAnchor, constant: insets.top).isActive = true
trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
bottomAnchor.constraint(equalTo: s.bottomAnchor).isActive = true
}
}
| apache-2.0 | 230a1b9ef46cf6aa6c14509db99d1906 | 35.870968 | 88 | 0.72091 | 4.646341 | false | false | false | false |
rob-brown/DataSourceCombinators | DataSourceCombinators/ContainerCollectionCell.swift | 1 | 4033 | // ~MMMMMMMM,. .,MMMMMMM ..
// DNMMDMMMMMMMM,. ..MMMMNMMMNMMM,
// MMM.. ...NMMM MMNMM ,MMM
// NMM, , MMND MMMM .MM
// MMN MMMMM MMM
// .MM , MMMMMM , MMM
// .MM MMM. MMMM MMM
// .MM~ .MMM. NMMN. MMM
// MMM MMMM: .M ..MMM .MM,
// MMM.NNMMMMMMMMMMMMMMMMMMMMMMMMMM:MMM,
// ,,MMMMMMMMMMMMMMM NMMDNMMMMMMMMN~,
// MMMMMMMMM,, OMMM NMM . ,MMNMMMMN.
// ,MMMND .,MM= NMM~ MMMMMM+. MMM. NMM. .:MMMMM.
// MMMM NMM,MMMD MMM$ZZZMMM: .NMN.MMM NMMM
// MMNM MMMMMM MMZO~:ZZZZMM~ MMNMMN .MMM
// MMM MMMMM MMNZ~~:ZZZZZNM, MMMM MMN.
// MM. .MMM. MMZZOZZZZZZZMM. MMMM MMM.
// MMN MMMMN MMMZZZZZZZZZNM. MMMM MMM.
// NMMM .MMMNMN .MM$ZZZZZZZMMN ..NMMMMM MMM
// MMMMM MMM.MMM~ .MNMZZZZMMMD MMM MMM . . NMMN,
// NMMMM: ..MM8 MMM, . MNMMMM: .MMM: NMM ..MMMMM
// ...MMMMMMNMM MMM .. MMM. MNDMMMMM.
// .: MMMMMMMMMMDMMND MMMMMMMMNMMMMM
// NMM8MNNMMMMMMMMMMMMMMMMMMMMMMMMMMNMM
// ,MMM NMMMDMMMMM NMM.,. ,MM
// MMO ..MMM NMMM MMD
// .MM. ,,MMM+.MMMM= ,MMM
// .MM. MMMMMM~. MMM
// MM= MMMMM.. .MMN
// MMM MMM8 MMMN. MM,
// +MMO MMMN, MMMMM, MMM
// ,MMMMMMM8MMMMM, . MMNMMMMMMMMM.
// .NMMMMNMM DMDMMMMMM
import UIKit
public final class ContainerCollectionCell<T>: UICollectionViewCell {
public typealias SimpleContentCreator = () -> CellContent
public typealias ContentCreator = (T, UIView?) -> CellContent
private var object: T?
private weak var view: UIView?
public class func cell(reuseID: String, collectionView: UICollectionView, indexPath: IndexPath, object: T, contentCreator: ContentCreator) -> UICollectionViewCell {
register(reuseID: reuseID, collectionView: collectionView)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath)
guard let containerCell = cell as? ContainerCollectionCell else { return cell }
containerCell.object = object
containerCell.addContentView(object: object, contentCreator: contentCreator)
return containerCell
}
public class func cell(reuseID: String, collectionView: UICollectionView, indexPath: IndexPath, contentCreator: SimpleContentCreator) -> UICollectionViewCell {
return ContainerCollectionCell<Void>.cell(reuseID: reuseID, collectionView: collectionView, indexPath: indexPath, object: ()) { _,_ in
return contentCreator()
}
}
private class func register(reuseID: String, collectionView: UICollectionView) {
collectionView.register(self, forCellWithReuseIdentifier: reuseID)
}
private func addContentView(object: T, contentCreator: ContentCreator) {
let oldView = view
oldView?.removeFromSuperview()
let content = contentCreator(object, oldView)
contentView.addSubview(content.view)
switch content.mode {
case .fill:
content.view.pinToSuperview()
case .center:
content.view.centerInSuperview()
case let .inset(insets):
content.view.pinToSuperview(insets: insets)
}
view = content.view
content.style.forEach(apply(option:))
}
private func apply(option: StyleOption) {
switch option {
case .backgroundColor(let color):
backgroundColor = color
contentView.backgroundColor = color
}
}
}
| mit | ab34f45c69dff8345b30733b877ff728 | 41.452632 | 168 | 0.545996 | 4.227463 | false | false | false | false |
mpangburn/RayTracer | RayTracer/Models/Vector.swift | 1 | 5053 | //
// Vector.swift
// RayTracer
//
// Created by Michael Pangburn on 6/25/17.
// Copyright © 2017 Michael Pangburn. All rights reserved.
//
import Foundation
/// Represents a vector in 3D space.
struct Vector {
/// The x-component of the vector.
var x: Double
/// The y-component of the vector.
var y: Double
/// The z-component of the vector.
var z: Double
/**
Creates a vector from the given components.
- Parameters:
- x: The x-component of the vector.
- y: The y-component of the vector.
- z: The z-component of the vector.
*/
init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
/**
Creates a vector from the initial point to the terminal point.
- Parameters:
- initial: The point from which the vector begins.
- terminal: The point at which the vector ends.
*/
init(from initial: Point, to terminal: Point) {
self.init(x: terminal.x - initial.x, y: terminal.y - initial.y, z: terminal.z - initial.z)
}
}
// MARK: - Vector properties
extension Vector {
/// The length of the vector, equivalent to its magnitude.
var length: Double {
return sqrt((x * x) + (y * y) + (z * z))
}
/// The magnitude of the vector, equivalent to its length.
var magnitude: Double {
return self.length
}
}
// MARK: - Vector math
extension Vector {
/// Normalizes the vector.
mutating func normalize() {
self = self.normalized()
}
/**
Returns the normalized vector.
- Returns: The vector with the same direction and magnitude 1.
*/
func normalized() -> Vector {
return self / self.magnitude
}
/**
Scales the vector by the scalar.
- Parameter scalar: The scalar to scale by.
*/
mutating func scale(by scalar: Double) {
self = self.scaled(by: scalar)
}
/**
Returns the vector scaled by the scalar.
- Parameter scalar: The scalar to scale by.
- Returns: The vector scaled by the scalar.
*/
func scaled(by scalar: Double) -> Vector {
return Vector(x: self.x * scalar, y: self.y * scalar, z: self.z * scalar)
}
/**
Returns the dot product with the given vector.
- Parameter other: The vector to dot with.
- Returns: The dot product of the vectors.
*/
func dot(with other: Vector) -> Double {
return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
}
/**
Returns the cross product with the given vector.
- Parameter other: The vector to cross with.
- Returns: The cross product of the vectors.
*/
func cross(with other: Vector) -> Vector {
let x = self.y * other.z - self.z * other.y
let y = -(self.x * other.z - self.z * other.x)
let z = self.x * other.y - self.y * other.x
return Vector(x: x, y: y, z: z)
}
}
// MARK: - Vector operators
extension Vector {
/// Negates each component of the vector.
static prefix func - (vector: Vector) -> Vector {
return Vector(x: -vector.x, y: -vector.y, z: -vector.z)
}
/// Adds the components of the two vectors.
static func + (lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z)
}
/// Subtracts the components of the second vector from the first.
static func - (lhs: Vector, rhs: Vector) -> Vector {
return lhs + (-rhs)
}
/// Multiplies each component of the the vector by the scalar.
static func * (lhs: Vector, rhs: Double) -> Vector {
return lhs.scaled(by: rhs)
}
/// Multiplies each component of the the vector by the scalar.
static func * (lhs: Double, rhs: Vector) -> Vector {
return rhs.scaled(by: lhs)
}
/// Divides each component of the vector by the scalar.
static func / (lhs: Vector, rhs: Double) -> Vector {
return lhs * (1 / rhs)
}
}
// MARK: - Custom vector operators
infix operator •: MultiplicationPrecedence
infix operator ×: MultiplicationPrecedence
extension Vector {
/// Returns the dot product of the two vectors.
static func • (lhs: Vector, rhs: Vector) -> Double {
return lhs.dot(with: rhs)
}
/// Returns the cross product of the two vectors.
static func × (lhs: Vector, rhs: Vector) -> Vector {
return lhs.cross(with: rhs)
}
}
// MARK: - Vector constants
extension Vector {
/// The zero vector.
static var zero: Vector {
return Vector(x: 0, y: 0, z: 0)
}
}
extension Vector: Equatable { }
func == (lhs: Vector, rhs: Vector) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
extension Vector: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return "<\(self.x), \(self.y), \(self.z)>"
}
var debugDescription: String {
return "Vector(x: \(self.x), y: \(self.y), z: \(self.z))"
}
}
| mit | cccd5665f8d4c3d49eefc6742b791859 | 24.356784 | 98 | 0.591359 | 3.7713 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.