repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
blinker13/Aviary
|
Sources/Connection/Connection.swift
|
1
|
451
|
import SQLite3
internal final class Connection {
internal let access: Access
internal let location: Location
private var handle: OpaquePointer? = nil
internal init(location: Location, access: Access) {
let error = sqlite3_open_v2(location.rawValue, &handle, access.rawValue, nil)
precondition(error == SQLITE_OK, "Failed to open connection")
self.location = location
self.access = access
}
deinit {
sqlite3_close_v2(handle)
}
}
|
mit
|
df608733147a521c7053e1b44c9b88dc
| 20.47619 | 79 | 0.736142 | 3.469231 | false | false | false | false |
atuooo/notGIF
|
notGIF/Extensions/UIColor+NG.swift
|
1
|
726
|
//
// UIColor+NG.swift
// notGIF
//
// Created by Atuooo on 03/06/2017.
// Copyright © 2017 xyz. All rights reserved.
//
import UIKit
extension UIColor {
@nonobjc static let tintRed = UIColor.hex(0xF4511E)
@nonobjc static let tintBlue = UIColor.hex(0x039BE5)
@nonobjc static let tintBar = UIColor.hex(0x1C1C1C, alpha: 0.5)
@nonobjc static let tintColor = UIColor.hex(0xFBFBFB, alpha: 0.95)
public class func hex(_ hex: NSInteger, alpha: CGFloat = 1.0) -> UIColor {
return UIColor(red: ((CGFloat)((hex & 0xFF0000) >> 16))/255.0,
green: ((CGFloat)((hex & 0xFF00) >> 8))/255.0,
blue: ((CGFloat)(hex & 0xFF))/255.0, alpha: alpha)
}
}
|
mit
|
72b9bc8eecdd5621b09dfdf023b60022
| 30.521739 | 78 | 0.601379 | 3.179825 | false | false | false | false |
swojtyna/starsview
|
StarsView/StarsView/SendableRequest.swift
|
1
|
1388
|
//
// SendableRequest.swift
// StarsView
//
// Created by Sebastian Wojtyna on 29/08/16.
// Copyright © 2016 Sebastian Wojtyna. All rights reserved.
//
import Foundation
struct SendableRequestError: ErrorType {
let message: String
}
protocol SendableRequest: ConstructableRequest, StatusCodeCheckable, Result {}
extension SendableRequest {
func sendRequest(success success: (result: ResultType) -> (), failure: (error: ErrorType) -> ()) {
let session = NSURLSession.sharedSession()
guard let request = buildRequest() else {
failure(error: SendableRequestError(message: "Request can't be nil"))
return
}
let task = session.dataTaskWithRequest(request, completionHandler: { (taskData, taskResponse, taskError) -> Void in
if let taskError = taskError {
failure (error: taskError)
} else if let statusCodeError = self.checkStatusCode(taskResponse) {
failure (error: statusCodeError)
} else if let taskData = taskData {
guard let result = self.parseData(taskData) else {
failure(error: SendableRequestError(message: "Result parse error. Check result type for \(request)"))
return
}
success(result: result)
}
})
task.resume()
}
}
|
agpl-3.0
|
7733373b4051bada70d3f1ed288b79d6
| 32.02381 | 123 | 0.61788 | 4.90106 | false | false | false | false |
zhangao0086/DKImagePickerController
|
Sources/DKImageDataManager/Model/DKAsset+Fetch.swift
|
2
|
7043
|
//
// DKAsset+Fetch.swift
// DKImagePickerController
//
// Created by ZhangAo on 30/11/2017.
// Copyright © 2017 ZhangAo. All rights reserved.
//
import Foundation
import UIKit
import Photos
public extension DKAsset {
/**
Fetch an image with the specific size.
*/
@objc func fetchImage(with size: CGSize,
options: PHImageRequestOptions? = nil,
contentMode: PHImageContentMode = .aspectFit,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) {
if self.originalAsset != nil {
self.add(requestID: getImageDataManager().fetchImage(for: self,
size: size,
options: options,
contentMode: contentMode,
completeBlock: completeBlock))
} else {
completeBlock(self.image, nil)
}
}
/**
Fetch an image with the current screen size.
*/
@objc func fetchFullScreenImage(completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) {
if let (image, info) = self.fullScreenImage {
completeBlock(image, info)
} else if self.originalAsset == nil {
completeBlock(self.image, nil)
} else {
let screenSize = UIScreen.main.bounds.size
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
self.add(requestID: getImageDataManager().fetchImage(for: self,
size: screenSize.toPixel(),
options: options,
contentMode: .aspectFit) { [weak self] image, info in
guard let strongSelf = self else { return }
strongSelf.fullScreenImage = (image, info)
completeBlock(image, info)
})
}
}
/**
Fetch an image with the original size.
*/
@objc func fetchOriginalImage(options: PHImageRequestOptions? = nil,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) {
if self.originalAsset != nil {
self.add(requestID: getImageDataManager().fetchImageData(for: self,
options: options,
completeBlock: { (data, info) in
var image: UIImage?
if let data = data {
image = UIImage(data: data)
}
completeBlock(image, info)
}))
} else {
completeBlock(self.image, nil)
}
}
/**
Fetch an image data with the original size.
*/
@objc func fetchImageData(options: PHImageRequestOptions? = nil,
compressionQuality: CGFloat = 0.9,
completeBlock: @escaping (_ imageData: Data?, _ info: [AnyHashable: Any]?) -> Void) {
if self.originalAsset != nil {
self.add(requestID: getImageDataManager().fetchImageData(for: self,
options: options,
completeBlock: completeBlock))
} else {
if let image = self.image {
if self.hasAlphaChannel(image: image) {
completeBlock(image.pngData(), nil)
} else {
completeBlock(image.jpegData(compressionQuality: compressionQuality), nil)
}
} else {
assert(false)
}
}
}
/**
Fetch an AVAsset with a completeBlock and PHVideoRequestOptions.
*/
@objc func fetchAVAsset(options: PHVideoRequestOptions? = nil,
completeBlock: @escaping (_ AVAsset: AVAsset?, _ info: [AnyHashable: Any]?) -> Void) {
self.add(requestID: getImageDataManager().fetchAVAsset(for: self,
options: options,
completeBlock: completeBlock))
}
@objc func cancelRequests() {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if let requestIDs = self.requestIDs {
getImageDataManager().cancelRequests(requestIDs: requestIDs as! [DKImageRequestID])
self.requestIDs?.removeAllObjects()
}
}
// MARK: - Private
private func hasAlphaChannel(image: UIImage) -> Bool {
if let cgImage = image.cgImage {
let alphaInfo = cgImage.alphaInfo
return alphaInfo == .first
|| alphaInfo == .last
|| alphaInfo == .premultipliedFirst
|| alphaInfo == .premultipliedLast
} else {
return false
}
}
private func add(requestID: DKImageRequestID) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
var requestIDs: NSMutableArray! = self.requestIDs
if requestIDs == nil {
requestIDs = NSMutableArray()
self.requestIDs = requestIDs
}
requestIDs.add(requestID)
}
// MARK: - Attributes
private struct FetchKeys {
static fileprivate var requestIDs: UInt8 = 0
static fileprivate var fullScreenImage: UInt8 = 0
}
private var requestIDs: NSMutableArray? {
get { return getAssociatedObject(key: &FetchKeys.requestIDs) as? NSMutableArray }
set { setAssociatedObject(key: &FetchKeys.requestIDs, value: newValue) }
}
private(set) var fullScreenImage: (image: UIImage?, info: [AnyHashable: Any]?)? {
get { return getAssociatedObject(key: &FetchKeys.fullScreenImage) as? (image: UIImage?, info: [AnyHashable: Any]?) }
set { setAssociatedObject(key: &FetchKeys.fullScreenImage, value: newValue) }
}
}
|
mit
|
49dbfc49f9daa4a7cd5dc812820e7cc4
| 40.423529 | 124 | 0.459671 | 6.231858 | false | false | false | false |
iWeslie/Ant
|
Ant/Ant/LunTan/Detials/Controller/RentOutDVC.swift
|
1
|
11144
|
//
// DatailViewController.swift
// Ant
//
// Created by Weslie on 2017/7/19.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
class RentOutDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
var houseRentId = 0
lazy var urls = [String]()
override func viewDidLoad() {
super.viewDidLoad()
loadDetialTableView()
// MARK:- 底部菜单
let menuView = Menu()
self.tabBarController?.tabBar.isHidden = true
menuView.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(menuView)
loadCellData()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "RentOutBasicInfo", bundle: nil), forCellReuseIdentifier: "rentOutBasicInfo")
tableView?.register(UINib(nibName: "RentOutDetial", bundle: nil), forCellReuseIdentifier: "rentOutDetial")
tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 3
case 2: return 5
case 3: return 1
case 4: return 1
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6)
var urlArray: [URL] = [URL]()
for str in urls {
let url = URL(string: str)
urlArray.append(url!)
}
return LoopView(images: urlArray, frame: frame, isAutoScroll: true)
case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情介绍"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return UIScreen.main.bounds.width * 0.6
case 1:
return 30
case 2:
return 30
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
let rentoutbasicinfo = tableView.dequeueReusableCell(withIdentifier: "rentOutBasicInfo") as! RentOutBasicInfo
rentoutbasicinfo.viewModel = modelInfo
cell = rentoutbasicinfo
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1:
let rentoutdetial = tableView.dequeueReusableCell(withIdentifier: "rentOutDetial") as! RentOutDetial
rentoutdetial.viewModel = modelInfo
cell = rentoutdetial
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 2:
let locationinfo = tableView.dequeueReusableCell(withIdentifier: "locationInfo") as! LocationInfo
locationinfo.viewModel = modelInfo
cell = locationinfo
default: break
}
case 1:
let detialcontroduction = tableView.dequeueReusableCell(withIdentifier: "detialControduction") as! DetialControduction
detialcontroduction.viewModel = modelInfo
cell = detialcontroduction
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
// guard modelInfo.con else {
// <#statements#>
// }
// guard indexPath.row >= 5 else{
//
// }
if let contact = modelInfo?.connactDict[indexPath.row] {
if let key = contact.first?.key{
connactoptions.con_Ways.text = key
}
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return 60
case 1: return 110
case 2: return 40
default: return 20
}
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 2:
switch indexPath.row {
case 1:
//自动打开拨号页面并自动拨打电话
let urlString = "tel://123456"
if let url = URL(string: urlString) {
//根据iOS系统版本,分别处理
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
})
} else {
UIApplication.shared.openURL(url)
}
}
default:
break
}
default:
break
}
}
}
extension RentOutDVC {
// MARK:- load data
fileprivate func loadCellData() {
let group = DispatchGroup()
//将当前的下载操作添加到组中
group.enter()
NetWorkTool.shareInstance.infoDetial(VCType: .house, id: houseRentId) { [weak self](result, error) in
//在这里异步加载任务
if error != nil {
print(error ?? "load house info list failed")
return
}
guard let resultDict = result!["result"] else {
return
}
let basic = LunTanDetialModel(dict: resultDict as! [String : AnyObject])
self?.modelInfo = basic
//离开当前组
group.leave()
}
group.notify(queue: DispatchQueue.main) {
//在这里告诉调用者,下完完毕,执行下一步操作
self.tableView?.reloadData()
}
}
}
|
apache-2.0
|
6c61f5f465eb3836153e42579ef7be94
| 32.39939 | 130 | 0.53948 | 5.264296 | false | false | false | false |
AnRanScheme/magiGlobe
|
magi/magiGlobe/magiGlobe/Classes/Tool/Extension/Foundation/Bundle/Bundle+AppIcon.swift
|
1
|
1014
|
//
// NSBundle+AppIcon.swift
// swift-magic
//
// Created by 安然 on 17/2/15.
// Copyright © 2017年 安然. All rights reserved.
//
import Foundation
import UIKit
public extension Bundle {
/// 获取多个app icon名字数组
///
/// - Returns: 多个app icon名字的可选数组
public class func m_appIconsPath() -> [String]?{
if let infoDict = Bundle.main.infoDictionary,let bundleIcons = infoDict["CFBundleIcons"] as? [String : Any], let bundlePrimaryIcon = bundleIcons["CFBundlePrimaryIcon"] as? [String : Any], let bundleIconFiles = bundlePrimaryIcon["CFBundleIconFiles"] as? [String]{
return bundleIconFiles
}
return nil
}
/// 获取app 第一个 icon 图片
///
/// - Returns: app 第一个 icon 图片
public class func m_appIcon() -> UIImage?{
if let iconsPath = Bundle.m_appIconsPath() , iconsPath.count > 0 {
return UIImage(named: iconsPath[0])
}
return nil
}
}
|
mit
|
101f3b2fac87512d68372d474d29fe72
| 26.794118 | 270 | 0.616931 | 3.795181 | false | false | false | false |
learning/B64
|
B64/ViewController.swift
|
1
|
1511
|
//
// ViewController.swift
// B64
//
// Created by Learning on 15/2/16.
// Copyright (c) 2015年 Learning. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, DropDelegate {
@IBOutlet weak var labelDrag: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the
(self.view as DropView).delegate = self
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func dragIn() {
labelDrag.textColor = NSColor.controlDarkShadowColor()
}
func dragOut() {
labelDrag.textColor = NSColor.controlShadowColor()
}
func dragDrop(array:Array<String>) {
var pboard:NSPasteboard = NSPasteboard.generalPasteboard()
pboard.clearContents()
var manage:NSFileManager = NSFileManager.defaultManager()
for filePath in array {
var isDir = ObjCBool(false)
manage.fileExistsAtPath(filePath, isDirectory: &isDir)
if (isDir.boolValue) {
continue
}
var data:NSData = NSData.dataWithContentsOfMappedFile(filePath) as NSData
var output:String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
pboard.writeObjects(["data:image/png;base64," + output])
}
labelDrag.textColor = NSColor.controlShadowColor()
}
}
|
mit
|
d12090544989919efa007ad00fa03e86
| 24.576271 | 105 | 0.630881 | 4.821086 | false | false | false | false |
ahoppen/swift
|
test/SILGen/copy_lvalue_peepholes.swift
|
5
|
2185
|
// RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
var zero = getInt()
func getInt() -> Int { return zero }
// CHECK-LABEL: sil hidden [ossa] @$s21copy_lvalue_peepholes014init_var_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[X:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[XLIFETIME:%[^,]+]] = begin_borrow [lexical] [[X]]
// CHECK: [[PBX:%.*]] = project_box [[XLIFETIME]]
// CHECK: [[Y:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[YLIFETIME:%[^,]+]] = begin_borrow [lexical] [[Y]]
// CHECK: [[PBY:%.*]] = project_box [[YLIFETIME]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]]
// CHECK: copy_addr [[READ]] to [initialization] [[PBY]] : $*Builtin.Int64
func init_var_from_lvalue(x: Int) {
var x = x
var y = x
}
// -- Peephole doesn't apply to computed lvalues
var computed: Int {
get {
return zero
}
set {}
}
// CHECK-LABEL: sil hidden [ossa] @$s21copy_lvalue_peepholes023init_var_from_computed_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @$s21copy_lvalue_peepholes8computedBi64_vg
// CHECK: [[GOTTEN:%.*]] = apply [[GETTER]]()
// CHECK: store [[GOTTEN]] to [trivial] {{%.*}}
func init_var_from_computed_lvalue() {
var y = computed
}
// CHECK-LABEL: sil hidden [ossa] @$s21copy_lvalue_peepholes021assign_computed_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[Y:%.*]] = alloc_box
// CHECK: [[YLIFETIME:%[^,]+]] = begin_borrow [lexical] [[Y]]
// CHECK: [[PBY:%.*]] = project_box [[YLIFETIME]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBY]]
// CHECK: [[Y_VAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[SETTER:%.*]] = function_ref @$s21copy_lvalue_peepholes8computedBi64_vs
// CHECK: apply [[SETTER]]([[Y_VAL]])
func assign_computed_from_lvalue(y: Int) {
var y = y
computed = y
}
// CHECK-LABEL: sil hidden [ossa] @$s21copy_lvalue_peepholes24assign_var_from_computed{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: assign {{%.*}} to [[WRITE]]
func assign_var_from_computed(x: inout Int) {
x = computed
}
|
apache-2.0
|
8a33f1e95214365f1913d8be2c7bbeda
| 36.033898 | 106 | 0.60595 | 3.030513 | false | false | false | false |
rails365/elected
|
elected-ios/elected-ios/MembersTableViewController.swift
|
1
|
7396
|
//
// MembersTableViewController.swift
// elected-ios
//
// Created by Peter Hitchcock on 3/24/16.
// Copyright © 2016 Peter Hitchcock. All rights reserved.
//
import UIKit
import Alamofire
import Haneke
class MembersTableViewController: UITableViewController {
var city: City?
var officials = [Official]()
override func viewDidLoad() {
super.viewDidLoad()
getLocations()
if let city = city {
title = city.name
}
tableView.rowHeight = 100
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return officials.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! OfficialTableViewCell
cell.nameLabel.text = officials[indexPath.row].name
cell.titleLabel.text = officials[indexPath.row].title
if officials[indexPath.row].image.isEmpty {
cell.cellImageView.image = UIImage(named: "logo")
} else {
let URLString = officials[indexPath.row].image
let URL = NSURL(string:URLString)!
cell.cellImageView.hnk_setImageFromURL(URL)
}
return cell
}
func getLocations() {
Alamofire.request(.GET, "https://sac-elected.herokuapp.com/api/v1/cities/\(city!.id)")
.responseJSON { response in
if let JSON = response.result.value {
self.officials.removeAll()
let dict = JSON
let ar = dict["officials"] as! [AnyObject]
for a in ar {
var name: String
var image: String
var cityId: Int
var bio: String
var street: String
var cityCode: String
var state: String
var zip: String
var phone: String
var email: String
var fb: String?
var fax: String
var title: String
var staffMembers = [StaffMember]()
if let nameJson = a["name"] {
name = nameJson as! String
} else {
name = "ERROR"
}
if let imageJson = a["image"] {
image = imageJson as! String
} else {
image = "ERROR"
}
if let idJson = a["id"] {
cityId = idJson as! Int
} else {
cityId = 0
}
if let bioJson = a["bio"] {
bio = bioJson as! String
} else {
bio = "ERROR"
}
if let streetJson = a["street"] {
street = streetJson as! String
} else {
street = "ERROR"
}
if let cityJson = a["city_code"] {
cityCode = cityJson as! String
} else {
cityCode = "ERROR"
}
if let stateJson = a["state"] {
state = stateJson as! String
} else {
state = "ERROR"
}
if let zipJson = a["zip"] {
zip = zipJson as! String
} else {
zip = "ERROR"
}
if let phoneJson = a["phone"] {
phone = phoneJson as! String
} else {
phone = "ERROR"
}
if let emailJson = a["email"] {
email = emailJson as! String
} else {
email = "ERROR"
}
if let faxJson = a["fax"] {
fax = faxJson as! String
} else {
fax = "ERROR"
}
if let fbJson = a["facebook"] {
fb = fbJson as? String
} else {
fb = nil
}
if let titleJson = a["title"] {
title = titleJson as! String
} else {
title = "ERROR"
}
let official = Official(name: name, image: image, cityId: cityId, bio: bio, street: street, cityCode: cityCode, state: state, zip: zip, phone: phone, email: email, fax: fax, title: title)
if fb != nil {
official.fb = fb
}
if let staffJson = a["staff_members"] {
let dict = staffJson as! [AnyObject]
for o in dict {
var name1 = String()
var email1 = String()
var title1 = String()
if let nameJ = o["name"] {
name1 = nameJ as! String
}
if let emailJ = o["email"] {
email1 = emailJ as! String
}
if let titleJ = o["title"] {
title1 = titleJ as! String
}
let staffMember = StaffMember(name: name1, email: email1, title: title1)
official.staffMembers = staffMembers
staffMembers.append(staffMember)
}
}
self.officials.append(official)
}
self.tableView.reloadData()
}
}
}
@IBAction func unwind(segue: UIStoryboardSegue) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "officialSegue" {
let dvc = segue.destinationViewController as! ProfileViewController
if let row = tableView.indexPathForSelectedRow?.row {
let official = officials[row]
dvc.official = official
}
}
}
}
|
mit
|
0a0edbb96d7e2e6df23218c1504fd660
| 31.721239 | 211 | 0.393103 | 6.101485 | false | false | false | false |
e78l/swift-corelibs-foundation
|
Foundation/HTTPCookie.swift
|
1
|
25139
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
extension HTTPCookiePropertyKey {
/// Key for cookie name
public static let name = HTTPCookiePropertyKey(rawValue: "Name")
/// Key for cookie value
public static let value = HTTPCookiePropertyKey(rawValue: "Value")
/// Key for cookie origin URL
public static let originURL = HTTPCookiePropertyKey(rawValue: "OriginURL")
/// Key for cookie version
public static let version = HTTPCookiePropertyKey(rawValue: "Version")
/// Key for cookie domain
public static let domain = HTTPCookiePropertyKey(rawValue: "Domain")
/// Key for cookie path
public static let path = HTTPCookiePropertyKey(rawValue: "Path")
/// Key for cookie secure flag
public static let secure = HTTPCookiePropertyKey(rawValue: "Secure")
/// Key for cookie expiration date
public static let expires = HTTPCookiePropertyKey(rawValue: "Expires")
/// Key for cookie comment text
public static let comment = HTTPCookiePropertyKey(rawValue: "Comment")
/// Key for cookie comment URL
public static let commentURL = HTTPCookiePropertyKey(rawValue: "CommentURL")
/// Key for cookie discard (session-only) flag
public static let discard = HTTPCookiePropertyKey(rawValue: "Discard")
/// Key for cookie maximum age (an alternate way of specifying the expiration)
public static let maximumAge = HTTPCookiePropertyKey(rawValue: "Max-Age")
/// Key for cookie ports
public static let port = HTTPCookiePropertyKey(rawValue: "Port")
// For Cocoa compatibility
internal static let created = HTTPCookiePropertyKey(rawValue: "Created")
}
/// `HTTPCookie` represents an http cookie.
///
/// An `HTTPCookie` instance represents a single http cookie. It is
/// an immutable object initialized from a dictionary that contains
/// the various cookie attributes. It has accessors to get the various
/// attributes of a cookie.
open class HTTPCookie : NSObject {
let _comment: String?
let _commentURL: URL?
let _domain: String
let _expiresDate: Date?
let _HTTPOnly: Bool
let _secure: Bool
let _sessionOnly: Bool
let _name: String
let _path: String
let _portList: [NSNumber]?
let _value: String
let _version: Int
var _properties: [HTTPCookiePropertyKey : Any]
// See: https://tools.ietf.org/html/rfc2616#section-3.3.1
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
static let _formatter1: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
static let _formatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE MMM d HH:mm:ss yyyy"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
// Sun, 06-Nov-1994 08:49:37 GMT ; Tomcat servers sometimes return cookies in this format
static let _formatter3: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd-MMM-yyyy HH:mm:ss O"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
static let _allFormatters: [DateFormatter]
= [_formatter1, _formatter2, _formatter3]
static let _attributes: [HTTPCookiePropertyKey]
= [.name, .value, .originURL, .version, .domain,
.path, .secure, .expires, .comment, .commentURL,
.discard, .maximumAge, .port]
/// Initialize a HTTPCookie object with a dictionary of parameters
///
/// - Parameter properties: The dictionary of properties to be used to
/// initialize this cookie.
///
/// Supported dictionary keys and value types for the
/// given dictionary are as follows.
///
/// All properties can handle an NSString value, but some can also
/// handle other types.
///
/// <table border=1 cellspacing=2 cellpadding=4>
/// <tr>
/// <th>Property key constant</th>
/// <th>Type of value</th>
/// <th>Required</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.comment</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Comment for the cookie. Only valid for version 1 cookies and
/// later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.commentURL</td>
/// <td>NSURL or NSString</td>
/// <td>NO</td>
/// <td>Comment URL for the cookie. Only valid for version 1 cookies
/// and later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.domain</td>
/// <td>NSString</td>
/// <td>Special, a value for either .originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>Domain for the cookie. Inferred from the value for
/// HTTPCookiePropertyKey.originURL if not provided.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.discard</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be discarded at
/// the end of the session. String value must be either "TRUE" or
/// "FALSE". Default is "FALSE", unless this is cookie is version
/// 1 or greater and a value for HTTPCookiePropertyKey.maximumAge is not
/// specified, in which case it is assumed "TRUE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.expires</td>
/// <td>NSDate or NSString</td>
/// <td>NO</td>
/// <td>Expiration date for the cookie. Used only for version 0
/// cookies. Ignored for version 1 or greater.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.maximumAge</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string containing an integer value stating how long in
/// seconds the cookie should be kept, at most. Only valid for
/// version 1 cookies and later. Default is "0".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.name</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Name of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.originURL</td>
/// <td>NSURL or NSString</td>
/// <td>Special, a value for either HTTPCookiePropertyKey.originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>URL that set this cookie. Used as default for other fields
/// as noted.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.path</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Path for the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.port</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>comma-separated integer values specifying the ports for the
/// cookie. Only valid for version 1 cookies and later. Default is
/// empty string ("").</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.secure</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be transmitted
/// only over secure channels. String value must be either "TRUE"
/// or "FALSE". Default is "FALSE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.value</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Value of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.version</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Specifies the version of the cookie. Must be either "0" or
/// "1". Default is "0".</td>
/// </tr>
/// </table>
///
/// All other keys are ignored.
///
/// - Returns: An initialized `HTTPCookie`, or nil if the set of
/// dictionary keys is invalid, for example because a required key is
/// missing, or a recognized key maps to an illegal value.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public init?(properties: [HTTPCookiePropertyKey : Any]) {
func stringValue(_ strVal: Any?) -> String? {
if let subStr = strVal as? Substring {
return String(subStr)
}
return strVal as? String
}
guard
let path = stringValue(properties[.path]),
let name = stringValue(properties[.name]),
let value = stringValue(properties[.value])
else {
return nil
}
let canonicalDomain: String
if let domain = properties[.domain] as? String {
canonicalDomain = domain
} else if
let originURL = properties[.originURL] as? URL,
let host = originURL.host
{
canonicalDomain = host
} else {
return nil
}
_path = path
_name = name
_value = value
_domain = canonicalDomain.lowercased()
if let
secureString = properties[.secure] as? String, !secureString.isEmpty
{
_secure = true
} else {
_secure = false
}
let version: Int
if let
versionString = properties[.version] as? String, versionString == "1"
{
version = 1
} else {
version = 0
}
_version = version
if let portString = properties[.port] as? String {
let portList = portString.split(separator: ",")
.compactMap { Int(String($0)) }
.map { NSNumber(value: $0) }
if version == 1 {
_portList = portList
} else {
// Version 0 only stores a single port number
_portList = portList.count > 0 ? [portList[0]] : nil
}
} else {
_portList = nil
}
var expDate: Date? = nil
// Maximum-Age is preferred over expires-Date but only version 1 cookies use Maximum-Age
if let maximumAge = properties[.maximumAge] as? String,
let secondsFromNow = Int(maximumAge) {
if version == 1 {
expDate = Date(timeIntervalSinceNow: Double(secondsFromNow))
}
} else {
let expiresProperty = properties[.expires]
if let date = expiresProperty as? Date {
expDate = date
} else if let dateString = expiresProperty as? String {
let results = HTTPCookie._allFormatters.compactMap { $0.date(from: dateString) }
expDate = results.first
}
}
_expiresDate = expDate
if let discardString = properties[.discard] as? String {
_sessionOnly = discardString == "TRUE"
} else {
_sessionOnly = properties[.maximumAge] == nil && version >= 1
}
_comment = properties[.comment] as? String
if let commentURL = properties[.commentURL] as? URL {
_commentURL = commentURL
} else if let commentURL = properties[.commentURL] as? String {
_commentURL = URL(string: commentURL)
} else {
_commentURL = nil
}
_HTTPOnly = false
_properties = [
.created : Date().timeIntervalSinceReferenceDate, // Cocoa Compatibility
.discard : _sessionOnly,
.domain : _domain,
.name : _name,
.path : _path,
.secure : _secure,
.value : _value,
.version : _version
]
if let comment = properties[.comment] {
_properties[.comment] = comment
}
if let commentURL = properties[.commentURL] {
_properties[.commentURL] = commentURL
}
if let expires = properties[.expires] {
_properties[.expires] = expires
}
if let maximumAge = properties[.maximumAge] {
_properties[.maximumAge] = maximumAge
}
if let originURL = properties[.originURL] {
_properties[.originURL] = originURL
}
if let _portList = _portList {
_properties[.port] = _portList
}
}
/// Return a dictionary of header fields that can be used to add the
/// specified cookies to the request.
///
/// - Parameter cookies: The cookies to turn into request headers.
/// - Returns: A dictionary where the keys are header field names, and the values
/// are the corresponding header field values.
open class func requestHeaderFields(with cookies: [HTTPCookie]) -> [String : String] {
var cookieString = cookies.reduce("") { (sum, next) -> String in
return sum + "\(next._name)=\(next._value); "
}
//Remove the final trailing semicolon and whitespace
if ( cookieString.length > 0 ) {
cookieString.removeLast()
cookieString.removeLast()
}
if cookieString == "" {
return [:]
} else {
return ["Cookie": cookieString]
}
}
/// Return an array of cookies parsed from the specified response header fields and URL.
///
/// This method will ignore irrelevant header fields so
/// you can pass a dictionary containing data other than cookie data.
/// - Parameter headerFields: The response header fields to check for cookies.
/// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpreted.
/// - Returns: An array of HTTPCookie objects
open class func cookies(withResponseHeaderFields headerFields: [String : String], for URL: URL) -> [HTTPCookie] {
//HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265
//Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is
//pretty common. It also suggests that commas and semicolons among other characters, cannot be a part of
// names and values. This implementation takes care of multiple cookies in the same field, however it doesn't
//support commas and semicolons in names and values(except for dates)
guard let cookies: String = headerFields["Set-Cookie"] else { return [] }
let nameValuePairs = cookies.components(separatedBy: ";") //split the name/value and attribute/value pairs
.map({$0.trim()}) //trim whitespaces
.map({removeCommaFromDate($0)}) //get rid of commas in dates
.flatMap({$0.components(separatedBy: ",")}) //cookie boundaries are marked by commas
.map({$0.trim()}) //trim again
.filter({$0.caseInsensitiveCompare("HTTPOnly") != .orderedSame}) //we don't use HTTPOnly, do we?
.flatMap({createNameValuePair(pair: $0)}) //create Name and Value properties
//mark cookie boundaries in the name-value array
var cookieIndices = (0..<nameValuePairs.count).filter({nameValuePairs[$0].hasPrefix("Name")})
cookieIndices.append(nameValuePairs.count)
//bake the cookies
var httpCookies: [HTTPCookie] = []
for i in 0..<cookieIndices.count-1 {
if let aCookie = createHttpCookie(url: URL, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) {
httpCookies.append(aCookie)
}
}
return httpCookies
}
//Bake a cookie
private class func createHttpCookie(url: URL, pairs: ArraySlice<String>) -> HTTPCookie? {
var properties: [HTTPCookiePropertyKey : Any] = [:]
for pair in pairs {
let name = pair.components(separatedBy: "=")[0]
var value = pair.components(separatedBy: "\(name)=")[1] //a value can have an "="
if canonicalize(name) == .expires {
value = value.unmaskCommas() //re-insert the comma
}
properties[canonicalize(name)] = value
}
// If domain wasn't provided, extract it from the URL
if properties[.domain] == nil {
properties[.domain] = url.host
}
//the default Path is "/"
if properties[.path] == nil {
properties[.path] = "/"
}
return HTTPCookie(properties: properties)
}
//we pass this to a map()
private class func removeCommaFromDate(_ value: String) -> String {
if value.hasPrefix("Expires") || value.hasPrefix("expires") {
return value.maskCommas()
}
return value
}
//These cookie attributes are defined in RFC 6265 and 2965(which is obsolete)
//HTTPCookie supports these
private class func isCookieAttribute(_ string: String) -> Bool {
return _attributes.first(where: {$0.rawValue.caseInsensitiveCompare(string) == .orderedSame}) != nil
}
//Cookie attribute names are case-insensitive as per RFC6265: https://tools.ietf.org/html/rfc6265
//but HTTPCookie needs only the first letter of each attribute in uppercase
private class func canonicalize(_ name: String) -> HTTPCookiePropertyKey {
let idx = _attributes.firstIndex(where: {$0.rawValue.caseInsensitiveCompare(name) == .orderedSame})!
return _attributes[idx]
}
//A name=value pair should be translated to two properties, Name=name and Value=value
private class func createNameValuePair(pair: String) -> [String] {
if pair.caseInsensitiveCompare(HTTPCookiePropertyKey.secure.rawValue) == .orderedSame {
return ["Secure=TRUE"]
}
let name = pair.components(separatedBy: "=")[0]
let value = pair.components(separatedBy: "\(name)=")[1]
if !isCookieAttribute(name) {
return ["Name=\(name)", "Value=\(value)"]
}
return [pair]
}
/// Returns a dictionary representation of the receiver.
///
/// This method returns a dictionary representation of the
/// `HTTPCookie` which can be saved and passed to
/// `init(properties:)` later to reconstitute an equivalent cookie.
///
/// See the `HTTPCookie` `init(properties:)` method for
/// more information on the constraints imposed on the dictionary, and
/// for descriptions of the supported keys and values.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open var properties: [HTTPCookiePropertyKey : Any]? {
return _properties
}
/// The version of the receiver.
///
/// Version 0 maps to "old-style" Netscape cookies.
/// Version 1 maps to RFC2965 cookies. There may be future versions.
open var version: Int {
return _version
}
/// The name of the receiver.
open var name: String {
return _name
}
/// The value of the receiver.
open var value: String {
return _value
}
/// Returns The expires date of the receiver.
///
/// The expires date is the date when the cookie should be
/// deleted. The result will be nil if there is no specific expires
/// date. This will be the case only for *session-only* cookies.
/*@NSCopying*/ open var expiresDate: Date? {
return _expiresDate
}
/// Whether the receiver is session-only.
///
/// `true` if this receiver should be discarded at the end of the
/// session (regardless of expiration date), `false` if receiver need not
/// be discarded at the end of the session.
open var isSessionOnly: Bool {
return _sessionOnly
}
/// The domain of the receiver.
///
/// This value specifies URL domain to which the cookie
/// should be sent. A domain with a leading dot means the cookie
/// should be sent to subdomains as well, assuming certain other
/// restrictions are valid. See RFC 2965 for more detail.
open var domain: String {
return _domain
}
/// The path of the receiver.
///
/// This value specifies the URL path under the cookie's
/// domain for which this cookie should be sent. The cookie will also
/// be sent for children of that path, so `"/"` is the most general.
open var path: String {
return _path
}
/// Whether the receiver should be sent only over secure channels
///
/// Cookies may be marked secure by a server (or by a javascript).
/// Cookies marked as such must only be sent via an encrypted connection to
/// trusted servers (i.e. via SSL or TLS), and should not be delivered to any
/// javascript applications to prevent cross-site scripting vulnerabilities.
open var isSecure: Bool {
return _secure
}
/// Whether the receiver should only be sent to HTTP servers per RFC 2965
///
/// Cookies may be marked as HTTPOnly by a server (or by a javascript).
/// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests
/// for URL's that match both the path and domain of the respective Cookies.
/// Specifically these cookies should not be delivered to any javascript
/// applications to prevent cross-site scripting vulnerabilities.
open var isHTTPOnly: Bool {
return _HTTPOnly
}
/// The comment of the receiver.
///
/// This value specifies a string which is suitable for
/// presentation to the user explaining the contents and purpose of this
/// cookie. It may be nil.
open var comment: String? {
return _comment
}
/// The comment URL of the receiver.
///
/// This value specifies a URL which is suitable for
/// presentation to the user as a link for further information about
/// this cookie. It may be nil.
/*@NSCopying*/ open var commentURL: URL? {
return _commentURL
}
/// The list ports to which the receiver should be sent.
///
/// This value specifies an NSArray of NSNumbers
/// (containing integers) which specify the only ports to which this
/// cookie should be sent.
///
/// The array may be nil, in which case this cookie can be sent to any
/// port.
open var portList: [NSNumber]? {
return _portList
}
open override var description: String {
var str = "<\(type(of: self)) "
str += "version:\(self._version) name:\"\(self._name)\" value:\"\(self._value)\" expiresDate:"
if let expires = self._expiresDate {
str += "\(expires)"
} else {
str += "nil"
}
str += " sessionOnly:\(self._sessionOnly) domain:\"\(self._domain)\" path:\"\(self._path)\" isSecure:\(self._secure) comment:"
if let comments = self._comment {
str += "\(comments)"
} else {
str += "nil"
}
str += " ports:{ "
if let ports = self._portList {
str += "\(NSArray(array: (ports)).componentsJoined(by: ","))"
} else {
str += "0"
}
str += " }>"
return str
}
}
//utils for cookie parsing
fileprivate extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func maskCommas() -> String {
return self.replacingOccurrences(of: ",", with: "&comma")
}
func unmaskCommas() -> String {
return self.replacingOccurrences(of: "&comma", with: ",")
}
}
|
apache-2.0
|
47118f500de7462d15018d51b8a45972
| 36.803008 | 134 | 0.597558 | 4.567406 | false | false | false | false |
monyschuk/CwlSignal
|
Sources/CwlSignal/CwlSignalReactive.swift
|
1
|
122479
|
//
// CwlSignalReactive.swift
// CwlSignal
//
// Created by Matt Gallagher on 2016/09/08.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
#if SWIFT_PACKAGE
import CwlUtils
#endif
#if swift(>=4)
#else
public typealias Numeric = IntegerArithmetic & ExpressibleByIntegerLiteral
public typealias BinaryInteger = IntegerArithmetic & ExpressibleByIntegerLiteral
#endif
extension Signal {
/// - Note: the [Reactive X operator "Create"](http://reactivex.io/documentation/operators/create.html) is considered unnecessary, given the `CwlSignal.Signal.generate` and `CwlSignal.Signal.create` methods.
/// - Note: the [Reactive X operator "Defer"](http://reactivex.io/documentation/operators/defer.html) is considered not applicable, given the different semantics of "activation" with `CwlSignal.Signal`. If `Defer`-like behavior is desired, either a method that constructs and returns a new `Signal` graph should be used (if a truly distinct graph is desired) or `CwlSignal.Signal.generate` should be used (if wait-until-activated behavior is desired).
/// - Note: the Reactive X operator [Reactive X operator "Empty"](http://reactivex.io/documentation/operators/empty-never-throw.html) is redundant with the default invocation of `CwlSignal.Signal.preclosed`
}
extension Signal {
/// Implementation of [Reactive X operator "Never"](http://reactivex.io/documentation/operators/empty-never-throw.html)
///
/// - returns: a non-sending, non-closing signal of the desired type
public static func never() -> Signal<T> {
return .from(values: [], error: nil)
}
/// Implementation of [Reactive X operator "From"](http://reactivex.io/documentation/operators/from.html) in the context of the Swift `Sequence`
///
/// - parameter values: A Swift `Sequence` that generates the signal values.
/// - parameter error: The error with which to close the sequence. Can be `nil` to leave the sequence open.
/// - parameter context: the `Exec` where the `SequenceType` will be enumerated (default: .direct).
/// - returns: a signal that emits `values` and then closes
public static func from<S: Sequence>(values: S, error: Error? = SignalError.closed, context: Exec = .direct) -> Signal<T> where S.Iterator.Element == T {
if let e = error {
return generate(context: context) { input in
guard let i = input else { return }
for v in values {
if let _ = i.send(value: v) {
break
}
}
i.send(error: e)
}
} else {
return retainedGenerate(context: context) { input in
guard let i = input else { return }
for v in values {
if let _ = i.send(value: v) {
break
}
}
}
}
}
@available(*, deprecated, message:"Use from(values:error:context:) instead")
public static func fromSequence<S: Sequence>(_ values: S, context: Exec = .direct) -> Signal<T> where S.Iterator.Element == T {
return from(values: values, context: context)
}
/// Implementation of [Reactive X operator "To"](http://reactivex.io/documentation/operators/to.html) in the context of the Swift `Sequence`
///
/// WARNING: For potential deadlock reasons, and because it undermines the principle of *reactive* programming, this function is not advised.
/// `SignalSequence` subscribes to `self` and blocks. This means that if any earlier signals in the graph force processing on the same context where `SignalSequence` is iterated, a deadlock may occur between the iteration and the signal processing.
/// This function is safe only when you can guarantee all parts of the signal graph are independent of the blocking context.
public func toSequence() -> SignalSequence<T> {
return SignalSequence<T>(self)
}
}
/// Represents a Signal<T> converted to a synchronously iterated sequence. Values can be obtained using typical SequenceType actions. The error that ends the sequence is available through the `error` property.
public class SignalSequence<T>: Sequence, IteratorProtocol {
typealias GeneratorType = SignalSequence<T>
typealias ElementType = T
let semaphore = DispatchSemaphore(value: 0)
let context = Exec.syncQueue()
var endpoint: SignalEndpoint<T>? = nil
var queued: Array<T> = []
/// Error type property is `nil` before the end of the signal is reached and contains the error used to close the signal in other cases
public var error: Error?
// Only intended to be constructed by `Signal.toSequence`
init(_ signal: Signal<T>) {
endpoint = signal.subscribe(context: context) { [weak self] (r: Result<T>) in
guard let s = self else { return }
switch r {
case .success(let v):
s.queued.append(v)
s.semaphore.signal()
case .failure(let e):
s.error = e
s.semaphore.signal()
}
}
}
/// Stops listening to the signal and set the error value to SignalError.Cancelled
public func cancel() {
context.invokeAndWait {
self.error = SignalError.cancelled
self.endpoint?.cancel()
self.semaphore.signal()
}
}
/// Implementation of GeneratorType method.
public func next() -> T? {
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
var result: T? = nil
context.invokeAndWait { [weak self] in
guard let s = self else { return }
if !s.queued.isEmpty {
result = s.queued.removeFirst()
} else {
// Signal the sempahore so that `nil` can be fetched again.
s.semaphore.signal()
}
}
return result
}
deinit {
if error == nil {
semaphore.signal()
}
}
}
/// Implementation of [Reactive X operator "Interval"](http://reactivex.io/documentation/operators/interval.html)
///
/// - parameter seconds: Number of seconds between values.
/// - parameter initialSeconds: Number of seconds before the first value. Leave `nil` (default) or omit to use the `seconds` value.
/// - parameter restartOnActivate: If `true` (default), the returned signal timer restarts and the signal value resets to 0 every time the node is activated. If `false`, the generator starts immediately and runs continuously, independent of activation and reactivation.
/// -
/// - returns: a signal that issues an increasing count (starting at 0) every `seconds`.
public func intervalSignal(interval: DispatchTimeInterval, initialInterval: DispatchTimeInterval? = nil, restartOnActivate: Bool = true, context: Exec = .default) -> Signal<Int> {
// We need to protect the `count` variable and make sure that out-of-date timers don't update it so we use a `serialized` context for the `generate` and the timers, since the combination of the two will ensure that these requirements are met.
let serialContext = context.serialized()
var timer: Cancellable? = nil
var count = 0
return Signal<Int>.generate(context: serialContext) { input in
guard let i = input else {
timer?.cancel()
count = 0
return
}
let repeater = {
timer = serialContext.periodicTimer(interval: interval) {
i.send(value: count)
count += 1
}
}
if let initial = initialInterval {
timer = serialContext.singleTimer(interval: initial) {
i.send(value: count)
count += 1
repeater()
}
} else {
repeater()
}
}
}
extension Signal {
/// - Note: the [Reactive X operator "Just"](http://reactivex.io/documentation/operators/just.html) is redundant with the default invocation of `CwlSignal.Signal.preclosed`
/// - Note: the [Reactive X operator `Range`](http://reactivex.io/documentation/operators/range.html) is considered unnecessary, given the `CwlSignal.Signal.fromSequence`. Further, since Swift uses multiple different *kinds* of range, multiple implementations would be required. Doesn't seem worth the effort.
}
extension Signal {
/// Implementation of [Reactive X operator "Repeat"](http://reactivex.io/documentation/operators/repeat.html) for a Swift `CollectionType`
///
/// - parameter values: A Swift `CollectionType` that generates the signal values.
/// - parameter count: the number of times that `values` will be repeated.
/// - parameter context: the `Exec` where the `SequenceType` will be enumerated.
/// - returns: a signal that emits `values` a `count` number of times and then closes
public static func repeatCollection<C: Collection>(_ values: C, count: Int, context: Exec = .direct) -> Signal<T> where C.Iterator.Element == T {
return generate(context: context) { input in
guard let i = input else { return }
for _ in 0..<count {
for v in values {
if i.send(value: v) != nil {
break
}
}
}
i.close()
}
}
/// Implementation of [Reactive X operator "Start"](http://reactivex.io/documentation/operators/start.html)
///
/// - parameter context: the `Exec` where `f` will be evaluated (default: .direct).
/// - parameter f: a function that is run to generate the value.
/// - returns: a signal that emits a single value emitted from a function
public static func start(context: Exec = .direct, f: @escaping () -> T) -> Signal<T> {
return Signal.generate(context: context) { input in
guard let i = input else { return }
i.send(value: f())
i.close()
}
}
/// Implementation of [Reactive X operator "Timer"](http://reactivex.io/documentation/operators/timer.html)
///
/// - parameter seconds: the time until the value is sent.
/// - returns: a signal that will fire once after `seconds` and then close
public static func timer(interval: DispatchTimeInterval, value: T? = nil, context: Exec = .default) -> Signal<T> {
var timer: Cancellable? = nil
return Signal<T>.generate(context: context) { input in
if let i = input {
timer = context.singleTimer(interval: interval) {
if let v = value {
i.send(value: v)
}
i.close()
}
} else {
timer?.cancel()
}
}
}
/// A shared function for emitting a boundary signal usable by the timed, non-overlapping buffer/window functions buffer(timeshift:count:continuous:behavior:) or window(timeshift:count:continuous:behavior:)
///
/// - parameter seconds: maximum seconds between boundaries
/// - parameter count: maximum values between boundaries
/// - parameter continuous: timer is paused immediately after a boundary until the next value is received
/// - parameter context: used for time
///
/// - returns: the boundary signal
private func timedCountedBoundary(interval: DispatchTimeInterval, count: Int, continuous: Bool, context: Exec) -> Signal<()> {
// An interval signal
let intSig = intervalSignal(interval: interval, context: context)
if count == Int.max {
// If number of values per boundary is infinite, then all we need is the timer signal
return intSig.map { v in () }
}
// The interval signal may need to be disconnectable so create a junction
let intervalJunction = intSig.junction()
let (initialInput, signal) = Signal<Int>.create()
// Continuous signals don't really need the junction. Just connect it immediately and ignore it.
if continuous {
do {
try intervalJunction.join(to: initialInput)
} catch {
assertionFailure()
return Signal<()>.preclosed()
}
}
return combine(withState: (0, nil), second: signal) { (state: inout (count: Int, timerInput: SignalInput<Int>?), cr: EitherResult2<T, Int>, n: SignalNext<()>) in
var send = false
switch cr {
case .result1(.success):
// Count the values received per window
state.count += 1
// If we hit `count` values, trigger the boundary signal
if state.count == count {
send = true
} else if !continuous, let i = state.timerInput {
// If we're not continuous, make sure the timer is connected
do {
try intervalJunction.join(to: i)
} catch {
n.send(error: error)
}
}
case .result1(.failure(let e)):
// If there's an error on the `self` signal, forward it on.
n.send(error: e)
case .result2(.success):
// When the timer fires, trigger the boundary signal
send = true
case .result2(.failure(let e)):
// If there's a timer error, close
n.send(error: e)
}
if send {
// Send the boundary signal
n.send(value: ())
// Reset the count and – if not continuous – disconnect the timer until we receive a signal from `self`
state.count = 0
if !continuous {
state.timerInput = intervalJunction.disconnect()
}
}
}
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping/no-gap buffers.
///
/// - parameter boundaries: when this `Signal` sends a value, the buffer is emitted and cleared
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `boundaries`
public func buffer<U>(boundaries: Signal<U>) -> Signal<[T]> {
return combine(withState: [T](), second: boundaries) { (buffer: inout [T], cr: EitherResult2<T, U>, next: SignalNext<[T]>) in
switch cr {
case .result1(.success(let v)):
buffer.append(v)
case .result1(.failure(let e)):
next.send(value: buffer)
buffer.removeAll()
next.send(error: e)
case .result2(.success):
next.send(value: buffer)
buffer.removeAll()
case .result2(.failure(let e)):
next.send(value: buffer)
buffer.removeAll()
next.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for buffers with overlap or gaps between.
///
/// - parameter windows: a "windows" signal (one that describes a series of times and durations). Each value `Signal` in the stream starts a new buffer and when the value `Signal` closes, the buffer is emitted.
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func buffer<U>(windows: Signal<Signal<U>>) -> Signal<[T]> {
return combine(withState: [Int: [T]](), second: windows.valueDurations { s in s }) { (buffers: inout [Int: [T]], cr: EitherResult2<T, (Int, Signal<U>?)>, next: SignalNext<[T]>) in
switch cr {
case .result1(.success(let v)):
for index in buffers.keys {
buffers[index]?.append(v)
}
case .result1(.failure(let e)):
for (_, b) in buffers {
next.send(value: b)
}
buffers.removeAll()
next.send(error: e)
case .result2(.success(let index, .some)):
buffers[index] = []
case .result2(.success(let index, .none)):
if let b = buffers[index] {
next.send(value: b)
buffers.removeValue(forKey: index)
}
case .result2(.failure(let e)):
for (_, b) in buffers {
next.send(value: b)
}
buffers.removeAll()
next.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for buffers of fixed length and a fixed number of values separating starts.
///
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - parameter skip: the stride between the start of each new buffer (can be smaller than `count`, resulting in overlapping buffers)
/// - returns: a signal where the values are arrays of length `count` of values from `self`, with start values separated by `skip`
public func buffer(count: UInt, skip: UInt) -> Signal<[T]> {
if count == 0 {
return Signal<[T]>.preclosed()
}
let multi = multicast()
// Create the two listeners to the "multi" signal carefully so that the window signal is *first* (so it reaches the buffer before the value signal)
let windowSignal = multi.stride(count: Int(skip)).map { _ in
// `count - 1` is the index of the count-th element but since `valuesSignal` will resolve before this, we need to fire 1 element sooner, hence `count - 2`
multi.elementAt(count - 2).ignoreElements()
}
return multi.buffer(windows: windowSignal)
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping, periodic buffer start times and possibly limited buffer sizes.
///
/// - parameter seconds: the number of seconds between the start of each buffer (if smaller than `timespan`, buffers will overlap).
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - parameter continuous: if `true` (default), the `timeshift` periodic timer runs continuously (empty buffers may be emitted if a timeshift elapses without any source signals). If `false`, the periodic timer does start until the first value is received from the source and the periodic timer is paused when a buffer is emitted.
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func buffer(interval: DispatchTimeInterval, count: Int = Int.max, continuous: Bool = true, context: Exec = .direct) -> Signal<[T]> {
let multi = multicast()
// Create the two listeners to the "multi" signal carefully so that the raw signal is *first* (so it reaches the buffer before the boundary signal)
let valuesSignal = multi.map { v in v }
let boundarySignal = multi.timedCountedBoundary(interval: interval, count: count, continuous: continuous, context: context)
return valuesSignal.buffer(boundaries: boundarySignal)
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping buffers of fixed length.
///
/// - Note: this is just a convenience wrapper around `buffer(count:skip:behavior)` where `skip` equals `count`.
///
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `count`
public func buffer(count: UInt) -> Signal<[T]> {
return buffer(count: count, skip: count)
}
/// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for periodic buffer start times and fixed duration buffers.
///
/// - Note: this is just a convenience wrapper around `buffer(windows:behaviors)` where the `windows` signal contains `timerSignal` signals contained in a `intervalSignal` signal.
///
/// - parameter timespan: the duration of each buffer, in seconds.
/// - parameter timeshift: the number of seconds between the start of each buffer (if smaller than `timespan`, buffers will overlap).
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func buffer(timespan: DispatchTimeInterval, timeshift: DispatchTimeInterval, context: Exec = .direct) -> Signal<[T]> {
return buffer(windows: intervalSignal(interval: timeshift, initialInterval: .seconds(0), context: context).map { v in Signal<()>.timer(interval: timespan, context: context) })
}
/// Implementation of map and filter. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over child `Optional`s.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func filterMap<U>(context: Exec = .direct, _ processor: @escaping (T) -> U?) -> Signal<U> {
return transform(context: context) { (r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
if let u = processor(v) {
n.send(value: u)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of map and filter. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over child `Optional`s.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func filterMap<S, U>(withState initial : S, context: Exec = .direct, _ processor: @escaping (inout S, T) -> U?) -> Signal<U> {
return transform(withState: initial, context: context) { (s: inout S, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
if let u = processor(&s, v) {
n.send(value: u)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of map where the closure can throw. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over values or thrown errors.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func failableMap<U>(context: Exec = .direct, _ processor: @escaping (T) throws -> U) -> Signal<U> {
return transform(context: context) { (r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
do {
let u = try processor(v)
n.send(value: u)
} catch {
n.send(error: error)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of map where the closure can throw. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over values or thrown errors.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func failableMap<S, U>(withState initial: S, context: Exec = .direct, _ processor: @escaping (inout S, T) throws -> U) -> Signal<U> {
return transform(withState: initial, context: context) { (s: inout S, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
do {
let u = try processor(&s, v)
n.send(value: u)
} catch {
n.send(error: error)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of map where the closure can throw. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over values or thrown errors.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func failableFilterMap<U>(context: Exec = .direct, _ processor: @escaping (T) throws -> U?) -> Signal<U> {
return transform(context: context) { (r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
do {
if let u = try processor(v) {
n.send(value: u)
}
} catch {
n.send(error: error)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of map where the closure can throw. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over values or thrown errors.
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func failableFilterMap<S, U>(withState initial: S, context: Exec = .direct, _ processor: @escaping (inout S, T) throws -> U?) -> Signal<U> {
return transform(withState: initial, context: context) { (s: inout S, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
do {
if let u = try processor(&s, v) {
n.send(value: u)
}
} catch {
n.send(error: error)
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "FlatMap"](http://reactivex.io/documentation/operators/flatmap.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func flatMap<U>(context: Exec = .direct, _ processor: @escaping (T) -> Signal<U>) -> Signal<U> {
return transformFlatten(context: context) { (v: T, mergeSet: SignalMergeSet<U>) in
_ = try? mergeSet.add(processor(v), removeOnDeactivate: true)
}
}
/// Implementation of [Reactive X operator "FlatMapFirst"](http://reactivex.io/documentation/operators/flatmap.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func flatMapFirst<U>(context: Exec = .direct, _ processor: @escaping (T) -> Signal<U>) -> Signal<U> {
return transformFlatten(withState: false, context: context) { (s: inout Bool, v: T, mergeSet: SignalMergeSet<U>) in
if !s {
_ = try? mergeSet.add(processor(v), removeOnDeactivate: true)
s = true
}
}
}
/// Implementation of [Reactive X operator "FlatMapLatest"](http://reactivex.io/documentation/operators/flatmap.html)
///
/// See also `switchLatestSignal`
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func flatMapLatest<U>(context: Exec = .direct, _ processor: @escaping (T) -> Signal<U>) -> Signal<U> {
return transformFlatten(withState: nil, context: context) { (s: inout Signal<U>?, v: T, mergeSet: SignalMergeSet<U>) in
if let existing = s {
mergeSet.remove(existing)
}
let next = processor(v)
_ = try? mergeSet.add(next, removeOnDeactivate: true)
s = next
}
}
/// Implementation of [Reactive X operator "FlatMap"](http://reactivex.io/documentation/operators/flatmap.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func flatMap<U, V>(withState initial: V, context: Exec = .direct, _ processor: @escaping (inout V, T) -> Signal<U>) -> Signal<U> {
return transformFlatten(withState: initial, context: context) { (s: inout V, v: T, mergeSet: SignalMergeSet<U>) in
_ = try? mergeSet.add(processor(&s, v), removeOnDeactivate: true)
}
}
/// Implementation of [Reactive X operator "ConcatMap"](http://reactivex.io/documentation/operators/flatmap.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a new `Signal`
/// - returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream
public func concatMap<U>(context: Exec = .direct, _ processor: @escaping (T) -> Signal<U>) -> Signal<U> {
return transformFlatten(withState: 0, context: context) { (index: inout Int, v: T, mergeSet: SignalMergeSet<(Int, Result<U>)>) in
_ = try? mergeSet.add(processor(v).transform { (r: Result<U>, n: SignalNext<Result<U>>) in
switch r {
case .success:
n.send(value: r)
case .failure(let e):
n.send(value: r)
n.send(error: e)
}
}.map { [index] (r: Result<U>) -> (Int, Result<U>) in (index, r) }, removeOnDeactivate: true)
index += 1
}.transform(withState: (0, Array<Array<Result<U>>>())) { (state: inout (completed: Int, buffers: Array<Array<Result<U>>>), result: Result<(Int, Result<U>)>, next: SignalNext<U>) in
switch result {
case .success(let index, .success(let v)):
// We can send results for the first incomplete signal without buffering
if index == state.completed {
next.send(value: v)
} else {
// Make sure we have enough buffers
while index >= state.buffers.count {
state.buffers.append([])
}
// Buffer the result
state.buffers[index].append(Result<U>.success(v))
}
case .success(let index, .failure(let e)):
// If its an error, try to send some more buffers
if index == state.completed {
state.completed += 1
for i in state.completed..<state.buffers.count {
for j in state.buffers[i] where !j.isError {
next.send(result: j)
}
let incomplete = state.buffers[i].last?.isError != true
state.buffers[i].removeAll()
if incomplete {
break
}
state.completed += 1
}
} else {
// If we're not up to that buffer, just record the error
state.buffers[index].append(Result<U>.failure(e))
}
case .failure(let error): next.send(error: error)
}
}
}
/// Implementation of [Reactive X operator "GroupBy"](http://reactivex.io/documentation/operators/groupby.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs the "key" for the output `Signal`
/// - returns: a parent `Signal` where values are tuples of a "key" and a child `Signal` that will contain all values from `self` associated with that "key".
public func groupBy<U: Hashable>(context: Exec = .direct, _ processor: @escaping (T) -> U) -> Signal<(U, Signal<T>)> {
return self.transform(withState: Dictionary<U, SignalInput<T>>(), context: context) { (outputs: inout Dictionary<U, SignalInput<T>>, r: Result<T>, n: SignalNext<(U, Signal<T>)>) in
switch r {
case .success(let v):
let u = processor(v)
if let o = outputs[u] {
o.send(value: v)
} else {
let (input, signal) = Signal<T>.create { s in s.cacheUntilActive() }
input.send(value: v)
n.send(value: (u, signal))
outputs[u] = input
}
case .failure(let e):
n.send(error: e)
outputs.forEach { tuple in tuple.value.send(error: e) }
}
}
}
/// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a value for the output `Signal`
/// - returns: a `Signal` where all the values have been transformed by the `processor`. Any error is emitted in the output without change.
public func map<U>(context: Exec = .direct, _ processor: @escaping (T) -> U) -> Signal<U> {
return transform(context: context) { (r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v): n.send(value: processor(v))
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: for each value emitted by `self`, outputs a value for the output `Signal`
/// - returns: a `Signal` where all the values have been transformed by the `processor`. Any error is emitted in the output without change.
public func map<U, V>(withState initial: V, context: Exec = .direct, _ processor: @escaping (inout V, T) -> U) -> Signal<U> {
return transform(withState: initial, context: context) { (s: inout V, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v): n.send(value: processor(&s, v))
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Scan"](http://reactivex.io/documentation/operators/scan.html)
///
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: takes the most recently emitted value and the most recent value from `self` and returns the next emitted value
/// - returns: a `Signal` where the result from each invocation of `processor` are emitted
public func scan<U>(initial: U, context: Exec = .direct, _ processor: @escaping (U, T) -> U) -> Signal<U> {
return transform(withState: initial, context: context) { (accumulated: inout U, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
accumulated = processor(accumulated, v)
n.send(value: accumulated)
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping/no-gap buffers.
///
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter boundaries: when this `Signal` sends a value, the buffer is emitted and cleared
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `boundaries`
public func window<U>(boundaries: Signal<U>) -> Signal<Signal<T>> {
return combine(withState: nil, second: boundaries) { (current: inout SignalInput<T>?, cr: EitherResult2<T, U>, next: SignalNext<Signal<T>>) in
switch cr {
case .result1(.success(let v)):
if current == nil {
let (i, s) = Signal<T>.create()
current = i
next.send(value: s)
}
if let c = current {
c.send(value: v)
}
case .result1(.failure(let e)):
next.send(error: e)
case .result2(.success):
_ = current?.close()
current = nil
case .result2(.failure(let e)):
next.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for buffers with overlap or gaps between.
///
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter windows: a "windows" signal (one that describes a series of times and durations). Each value `Signal` in the stream starts a new buffer and when the value `Signal` closes, the buffer is emitted.
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func window<U>(windows: Signal<Signal<U>>) -> Signal<Signal<T>> {
return combine(withState: [Int: SignalInput<T>](), second: windows.valueDurations { s in s }) { (children: inout [Int: SignalInput<T>], cr: EitherResult2<T, (Int, Signal<U>?)>, next: SignalNext<Signal<T>>) in
switch cr {
case .result1(.success(let v)):
for index in children.keys {
if let c = children[index] {
c.send(value: v)
}
}
case .result1(.failure(let e)):
next.send(error: e)
case .result2(.success(let index, .some)):
let (i, s) = Signal<T>.create()
children[index] = i
next.send(value: s)
case .result2(.success(let index, .none)):
if let c = children[index] {
c.close()
children.removeValue(forKey: index)
}
case .result2(.failure(let e)):
next.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for buffers of fixed length and a fixed number of values separating starts.
///
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - parameter skip: the stride between the start of each new buffer (can be smaller than `count`, resulting in overlapping buffers)
/// - returns: a signal where the values are arrays of length `count` of values from `self`, with start values separated by `skip`
public func window(count: UInt, skip: UInt) -> Signal<Signal<T>> {
let multi = multicast()
// Create the two listeners to the "multi" signal carefully so that the window signal is *first* (so it reaches the buffer before the value signal)
let windowSignal = multi.stride(count: Int(skip)).map { v in
// `count - 1` is the index of the count-th element but since `valuesSignal` will resolve before this, we need to fire 1 element sooner, hence `count - 2`
multi.elementAt(count - 2).ignoreElements()
}
return multi.window(windows: windowSignal)
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping, periodic buffer start times and possibly limited buffer sizes.
///
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter seconds: the number of seconds between the start of each buffer (if smaller than `timespan`, buffers will overlap).
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - parameter continuous: if `true` (default), the `timeshift` periodic timer runs continuously (empty buffers may be emitted if a timeshift elapses without any source signals). If `false`, the periodic timer does start until the first value is received from the source and the periodic timer is paused when a buffer is emitted.
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func window(interval: DispatchTimeInterval, count: Int = Int.max, continuous: Bool = true, context: Exec = .direct) -> Signal<Signal<T>> {
let multi = multicast()
// Create the two listeners to the "multi" signal carefully so that the raw signal is *first* (so it reaches the buffer before the boundary signal)
let valuesSignal = multi.map { v in v }
let boundarySignal = multi.timedCountedBoundary(interval: interval, count: count, continuous: continuous, context: context)
return valuesSignal.window(boundaries: boundarySignal)
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping buffers of fixed length.
///
/// - Note: this is just a convenience wrapper around `buffer(count:skip:behavior)` where `skip` equals `count`.
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter count: the number of separate values to accumulate before emitting an array of values
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `count`
public func window(count: UInt) -> Signal<Signal<T>> {
return window(count: count, skip: count)
}
/// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for periodic buffer start times and fixed duration buffers.
///
/// - Note: this is just a convenience wrapper around `buffer(windows:behaviors)` where the `windows` signal contains `timerSignal` signals contained in a `intervalSignal` signal.
/// - Note: equivalent to "buffer" method with same parameters
///
/// - parameter seconds: the duration of each buffer, in seconds.
/// - parameter timeshift: the number of seconds between the start of each buffer (if smaller than `timespan`, buffers will overlap).
/// - returns: a signal where the values are arrays of values from `self`, accumulated according to `windows`
public func window(timespan: DispatchTimeInterval, timeshift: DispatchTimeInterval, context: Exec = .direct) -> Signal<Signal<T>> {
return window(windows: intervalSignal(interval: timeshift, initialInterval: .seconds(0), context: context).map { v in Signal<()>.timer(interval: timespan, context: context) })
}
/// Implementation of [Reactive X operator "Debounce"](http://reactivex.io/documentation/operators/debounce.html)
///
/// - parameter seconds: the duration over which to drop values.
/// - returns: a signal where values are emitted after a `timespan` but only if no another value occurs during that `timespan`.
public func debounce(interval: DispatchTimeInterval, flushOnClose: Bool = true, context: Exec = .direct) -> Signal<T> {
// The topology of this construction is particularly weird.
// Basically...
//
// -> incoming signal -> combiner -> post delay emission ->
// ^ \
// \______/
// delayed values held by `singleTimer`
// closure, sent to `timerInput`
//
// The weird structure of the loopback (using an input pulled from a `generate` function) is so that the overall function remains robust under deactivation and reactivation. The mutable `timerInput` is protected by the serialized `context`, shared between the `generate` and the `combine`.
let serialContext = context.serialized()
var timerInput: SignalInput<T>? = nil
let timerSignal = Signal<T>.generate(context: serialContext) { input in
timerInput = input
}
var last: T? = nil
return timerSignal.combine(withState: (timer: nil, onDelete: nil), second: self, context: serialContext) { (state: inout (timer: Cancellable?, onDelete: OnDelete?), cr: EitherResult2<T, T>, n: SignalNext<T>) in
if state.onDelete == nil {
state.onDelete = OnDelete { last = nil }
}
switch cr {
case .result2(.success(let v)):
last = v
state.timer = serialContext.singleTimer(interval: interval) {
if let l = last {
_ = timerInput?.send(value: l)
last = nil
}
}
case .result2(.failure(let e)):
if flushOnClose, let l = last {
_ = timerInput?.send(value: l)
last = nil
}
n.send(error: e)
case .result1(.success(let v)): n.send(value: v)
case .result1(.failure(let e)): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "throttleFirst"](http://reactivex.io/documentation/operators/sample.html)
///
/// - Note: this is largely the reverse of `debounce`.
///
/// - parameter timespan: the duration over which to drop values.
/// - returns: a signal where a timer is started when a value is received and emitted and further values received within that `timespan` will be dropped.
public func throttleFirst(interval: DispatchTimeInterval, context: Exec = .direct) -> Signal<T> {
let timerQueue = context.serialized()
var timer: Cancellable? = nil
return transform(withState: nil, context: timerQueue) { (cleanup: inout OnDelete?, r: Result<T>, n: SignalNext<T>) -> Void in
cleanup = cleanup ?? OnDelete {
timer = nil
}
switch r {
case .failure(let e):
n.send(error: e)
case .success(let v) where timer == nil:
n.send(value: v)
timer = timerQueue.singleTimer(interval: interval) {
timer = nil
}
default:
break
}
}
}
}
extension Signal where T: Hashable {
/// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html)
///
/// - returns: a signal where all values received are remembered and only values not previously received are emitted.
public func distinct() -> Signal<T> {
return transform(withState: Set<T>()) { (previous: inout Set<T>, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v):
if !previous.contains(v) {
previous.insert(v)
n.send(value: v)
}
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html)
///
/// - returns: a signal that emits the first value but then emits subsequent values only when they are different to the previous value.
public func distinctUntilChanged() -> Signal<T> {
return transform(withState: nil) { (previous: inout T?, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v):
if previous != v {
previous = v
n.send(value: v)
}
case .failure(let e):
n.send(error: e)
}
}
}
}
extension Signal {
/// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html)
///
/// - parameter context: the `Exec` where `comparator` will be evaluated (default: .direct).
/// - parameter comparator: a function taking two parameters (the previous and current value in the signal) which should return `false` to indicate the current value should be emitted.
/// - returns: a signal that emits the first value but then emits subsequent values only if the function `comparator` returns `false` when passed the previous and current values.
public func distinctUntilChanged(context: Exec = .direct, comparator: @escaping (T, T) -> Bool) -> Signal<T> {
return transform(withState: nil) { (previous: inout T?, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v):
if let p = previous, comparator(p, v) {
// no action required
} else {
n.send(value: v)
}
previous = v
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "elementAt"](http://reactivex.io/documentation/operators/elementat.html)
///
/// - parameter index: identifies the element to be emitted.
/// - returns: a signal that emits the zero-indexed element identified by `index` and then closes.
public func elementAt(_ index: UInt) -> Signal<T> {
return transform(withState: 0, context: .direct) { (curr: inout UInt, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where curr == index:
n.send(value: v)
n.close()
case .success:
break
case .failure(let e):
n.send(error: e)
}
curr += 1
}
}
/// Implementation of [Reactive X operator "filter"](http://reactivex.io/documentation/operators/filter.html)
///
/// - parameter context: the `Exec` where `matching` will be evaluated (default: .direct).
/// - parameter matching: a function which is passed the current value and should return `true` to indicate the value should be emitted.
/// - returns: a signal that emits received values only if the function `matching` returns `true` when passed the value.
public func filter(context: Exec = .direct, matching: @escaping (T) -> Bool) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where matching(v):
n.send(value: v)
case .success:
break
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "ofType"](http://reactivex.io/documentation/operators/filter.html)
///
/// - parameter type: values will be filtered to this type (NOTE: only the *static* type of this parameter is considered – if the runtime type is more specific, that will be ignored).
/// - parameter context: the `Exec` where `matching` will be evaluated (default: .direct).
/// - returns: a signal that emits received values only if the value can be dynamically cast to the type `U`, specified statically by `type`.
public func ofType<U>(_ type: U.Type, context: Exec = .direct) -> Signal<U> {
return self.transform(withState: 0, context: context) { (curr: inout Int, r: Result<T>, n: SignalNext<U>) -> Void in
switch r {
case .success(let v as U):
n.send(value: v)
case .success:
break
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "first"](http://reactivex.io/documentation/operators/first.html)
///
/// - parameter context: the `Exec` where `matching` will be evaluated (default: .direct).
/// - returns: a signal that, when an error is received, emits the first value (if any) in the signal where `matching` returns `true` when invoked with the value, followed by the error.
public func first(context: Exec = .direct, matching: @escaping (T) -> Bool = { _ in true }) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where matching(v):
n.send(value: v)
n.close()
case .success:
break
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "single"](http://reactivex.io/documentation/operators/first.html)
///
/// - parameter context: the `Exec` where `matching` will be evaluated (default: .direct).
/// - returns: a signal that, if a single value in the sequence, when passed to `matching` returns `true`, then that value will be returned, followed by a SignalError.Closed when the input signal closes (otherwise a SignalError.Closed will be emitted without emitting any prior values).
public func single(context: Exec = .direct, matching: @escaping (T) -> Bool = { _ in true }) -> Signal<T> {
return transform(withState: nil, context: context) { (state: inout (firstMatch: T, unique: Bool)?, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where matching(v):
if let s = state {
state = (firstMatch: s.firstMatch, unique: false)
} else {
state = (firstMatch: v, unique: true)
}
case .success:
break
case .failure:
if let s = state, s.unique == true {
n.send(value: s.firstMatch)
}
n.send(result: r)
}
}
}
/// Implementation of [Reactive X operator "ignoreElements"](http://reactivex.io/documentation/operators/ignoreelements.html)
///
/// - returns: a signal that emits the input error, when received, otherwise ignores all values.
public func ignoreElements() -> Signal<T> {
return transform { (r: Result<T>, n: SignalNext<T>) -> Void in
if case .failure = r {
n.send(result: r)
}
}
}
/// Implementation of [Reactive X operator "ignoreElements"](http://reactivex.io/documentation/operators/ignoreelements.html)
///
/// - returns: a signal that emits the input error, when received, otherwise ignores all values.
public func ignoreElements<S: Sequence>(endWith: @escaping (Error) -> (S, Error)?) -> Signal<S.Iterator.Element> {
return transform() { (r: Result<T>, n: SignalNext<S.Iterator.Element>) in
switch r {
case .success: break
case .failure(let e):
if let (sequence, err) = endWith(e) {
sequence.forEach { n.send(value: $0) }
n.send(error: err)
} else {
n.send(error: e)
}
}
}
}
/// Implementation of [Reactive X operator "last"](http://reactivex.io/documentation/operators/last.html)
///
/// - parameter context: the `Exec` where `matching` will be evaluated (default: .direct).
/// - returns: a signal that, when an error is received, emits the last value (if any) in the signal where `matching` returns `true` when invoked with the value, followed by the error.
public func last(context: Exec = .direct, matching: @escaping (T) -> Bool = { _ in true }) -> Signal<T> {
return transform(withState: nil, context: context) { (last: inout T?, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where matching(v): last = v
case .success: break
case .failure:
if let l = last {
n.send(value: l)
}
n.send(result: r)
}
}
}
/// Implementation of [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html)
///
/// - parameter trigger: instructs the result to emit the last value from `self`
/// - returns: a signal that, when a value is received from `trigger`, emits the last value (if any) received from `self`.
public func sample(_ trigger: Signal<()>) -> Signal<T> {
return combine(withState: nil, second: trigger, context: .direct) { (last: inout T?, c: EitherResult2<T, ()>, n: SignalNext<T>) -> Void in
switch (c, last) {
case (.result1(.success(let v)), _): last = v
case (.result1(.failure(let e)), _): n.send(error: e)
case (.result2(.success), .some(let l)): n.send(value: l)
case (.result2(.success), _): break
case (.result2(.failure(let e)), _): n.send(error: e)
}
}.continuous()
}
/// Implementation similar to [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html) except that the output also includes the value from the trigger signal.
///
/// - parameter trigger: instructs the result to emit the last value from `self`
/// - returns: a signal that, when a value is received from `trigger`, emits the last value (if any) received from `self`.
public func sampleCombine<U>(_ trigger: Signal<U>) -> Signal<(T, U)> {
return combine(withState: nil, second: trigger, context: .direct) { (last: inout T?, c: EitherResult2<T, U>, n: SignalNext<(T, U)>) -> Void in
switch (c, last) {
case (.result1(.success(let v)), _): last = v
case (.result1(.failure(let e)), _): n.send(error: e)
case (.result2(.success(let trigger)), .some(let l)): n.send(value: (l, trigger))
case (.result2(.success), _): break
case (.result2(.failure(let e)), _): n.send(error: e)
}
}.continuous()
}
/// Implementation of [Reactive X operator "skip"](http://reactivex.io/documentation/operators/skip.html)
///
/// - parameter count: the number of values from the start of `self` to drop
/// - returns: a signal that drops `count` values from `self` then mirrors `self`.
public func skip(_ count: Int) -> Signal<T> {
return transform(withState: 0) { (progressCount: inout Int, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v) where progressCount >= count: n.send(value: v)
case .success: break
case .failure(let e): n.send(error: e)
}
progressCount = progressCount + 1
}
}
/// Implementation of [Reactive X operator "skipLast"](http://reactivex.io/documentation/operators/skiplast.html)
///
/// - parameter count: the number of values from the end of `self` to drop
/// - returns: a signal that buffers `count` values from `self` then for each new value received from `self`, emits the oldest value in the buffer. When `self` closes, all remaining values in the buffer are discarded.
public func skipLast(_ count: Int) -> Signal<T> {
return transform(withState: Array<T>()) { (buffer: inout Array<T>, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v):
buffer.append(v)
if buffer.count > count {
n.send(value: buffer.removeFirst())
}
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "skip"](http://reactivex.io/documentation/operators/skip.html)
///
/// - parameter count: the number of values from the start of `self` to emit
/// - returns: a signal that emits `count` values from `self` then closes.
public func take(_ count: Int) -> Signal<T> {
return transform(withState: 0) { (progressCount: inout Int, r: Result<T>, n: SignalNext<T>) -> Void in
progressCount = progressCount + 1
switch r {
case .success(let v) where progressCount >= count:
n.send(value: v)
n.close()
case .success(let v): n.send(value: v)
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "skipLast"](http://reactivex.io/documentation/operators/skiplast.html)
///
/// - parameter count: the number of values from the end of `self` to emit
/// - returns: a signal that buffers `count` values from `self` then for each new value received from `self`, drops the oldest value in the buffer. When `self` closes, all values in the buffer are emitted, followed by the close.
public func takeLast(_ count: Int) -> Signal<T> {
return transform(withState: Array<T>()) { (buffer: inout Array<T>, r: Result<T>, n: SignalNext<T>) -> Void in
switch r {
case .success(let v):
buffer.append(v)
if buffer.count > count {
buffer.removeFirst()
}
case .failure(let e):
for v in buffer {
n.send(value: v)
}
n.send(error: e)
}
}
}
}
extension Signal {
/// - Note: the [Reactive X operators "And", "Then" and "When"](http://reactivex.io/documentation/operators/and-then-when.html) are considered unnecessary, given the slightly different implementation of `CwlSignal.Signal.zip` which produces tuples (rather than producing a non-structural type) and is hence equivalent to `and`+`then`.
}
extension Signal {
/// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for two observed signals.
///
/// - parameter second: an observed signal.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value
/// - returns: a signal that emits the values from the processor and closes when any of the observed signals closes
public func combineLatest<U, V>(second: Signal<U>, context: Exec = .direct, _ processor: @escaping (T, U) -> V) -> Signal<V> {
return combine(withState: (nil, nil), second: second, context: context) { (state: inout (T?, U?), r: EitherResult2<T, U>, n: SignalNext<V>) -> Void in
switch r {
case .result1(.success(let v)): state = (v, state.1)
case .result2(.success(let v)): state = (state.0, v)
case .result1(.failure(let e)): n.send(error: e); return
case .result2(.failure(let e)): n.send(error: e); return
}
if let v0 = state.0, let v1 = state.1 {
n.send(value: processor(v0, v1))
}
}
}
/// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for three observed signals.
///
/// - parameter second: an observed signal.
/// - parameter third: an observed signal.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value
/// - returns: a signal that emits the values from the processor and closes when any of the observed signals closes
public func combineLatest<U, V, W>(second: Signal<U>, third: Signal<V>, context: Exec = .direct, _ processor: @escaping (T, U, V) -> W) -> Signal<W> {
return combine(withState: (nil, nil, nil), second: second, third: third, context: context) { (state: inout (T?, U?, V?), r: EitherResult3<T, U, V>, n: SignalNext<W>) -> Void in
switch r {
case .result1(.success(let v)): state = (v, state.1, state.2)
case .result2(.success(let v)): state = (state.0, v, state.2)
case .result3(.success(let v)): state = (state.0, state.1, v)
case .result1(.failure(let e)): n.send(error: e); return
case .result2(.failure(let e)): n.send(error: e); return
case .result3(.failure(let e)): n.send(error: e); return
}
if let v0 = state.0, let v1 = state.1, let v2 = state.2 {
n.send(value: processor(v0, v1, v2))
}
}
}
/// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for four observed signals.
///
/// - Note: support for multiple listeners and reactivation is determined by the specified `behavior`.
///
/// - parameter second: an observed signal.
/// - parameter third: an observed signal.
/// - parameter fourth: an observed signal.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value
/// - returns: a signal that emits the values from the processor and closes when any of the observed signals closes
public func combineLatest<U, V, W, X>(second: Signal<U>, third: Signal<V>, fourth: Signal<W>, context: Exec = .direct, _ processor: @escaping (T, U, V, W) -> X) -> Signal<X> {
return combine(withState: (nil, nil, nil, nil), second: second, third: third, fourth: fourth, context: context) { (state: inout (T?, U?, V?, W?), r: EitherResult4<T, U, V, W>, n: SignalNext<X>) -> Void in
switch r {
case .result1(.success(let v)): state = (v, state.1, state.2, state.3)
case .result2(.success(let v)): state = (state.0, v, state.2, state.3)
case .result3(.success(let v)): state = (state.0, state.1, v, state.3)
case .result4(.success(let v)): state = (state.0, state.1, state.2, v)
case .result1(.failure(let e)): n.send(error: e); return
case .result2(.failure(let e)): n.send(error: e); return
case .result3(.failure(let e)): n.send(error: e); return
case .result4(.failure(let e)): n.send(error: e); return
}
if let v0 = state.0, let v1 = state.1, let v2 = state.2, let v3 = state.3 {
n.send(value: processor(v0, v1, v2, v3))
}
}
}
/// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for five observed signals.
///
/// - Note: support for multiple listeners and reactivation is determined by the specified `behavior`.
///
/// - parameter second: an observed signal.
/// - parameter third: an observed signal.
/// - parameter fourth: an observed signal.
/// - parameter fifth: an observed signal.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value
/// - returns: a signal that emits the values from the processor and closes when any of the observed signals closes
public func combineLatest<U, V, W, X, Y>(second: Signal<U>, third: Signal<V>, fourth: Signal<W>, fifth: Signal<X>, context: Exec = .direct, _ processor: @escaping (T, U, V, W, X) -> Y) -> Signal<Y> {
return combine(withState: (nil, nil, nil, nil, nil), second: second, third: third, fourth: fourth, fifth: fifth, context: context) { (state: inout (T?, U?, V?, W?, X?), r: EitherResult5<T, U, V, W, X>, n: SignalNext<Y>) -> Void in
switch r {
case .result1(.success(let v)): state = (v, state.1, state.2, state.3, state.4)
case .result2(.success(let v)): state = (state.0, v, state.2, state.3, state.4)
case .result3(.success(let v)): state = (state.0, state.1, v, state.3, state.4)
case .result4(.success(let v)): state = (state.0, state.1, state.2, v, state.4)
case .result5(.success(let v)): state = (state.0, state.1, state.2, state.3, v)
case .result1(.failure(let e)): n.send(error: e); return
case .result2(.failure(let e)): n.send(error: e); return
case .result3(.failure(let e)): n.send(error: e); return
case .result4(.failure(let e)): n.send(error: e); return
case .result5(.failure(let e)): n.send(error: e); return
}
if let v0 = state.0, let v1 = state.1, let v2 = state.2, let v3 = state.3, let v4 = state.4 {
n.send(value: processor(v0, v1, v2, v3, v4))
}
}
}
/// Implementation of [Reactive X operator "join"](http://reactivex.io/documentation/operators/join.html)
///
/// - Note: support for multiple listeners and reactivation is determined by the specified `behavior`.
///
/// - parameter left: an observed signal.
/// - parameter right: an observed signal.
/// - parameter leftEnd: function invoked when a value is received from `left`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received left value.
/// - parameter rightEnd: function invoked when a value is received from `right`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `right` value.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: invoked with the corresponding `left` and `right` values when a `left` value is emitted during a `right`->`rightEnd` window or a `right` value is received during a `left`->`leftEnd` window
/// - returns: a signal that emits the values from the processor and closes when any of the last of the observed windows closes.
public func join<U, V, W, X>(withRight: Signal<U>, leftEnd: @escaping (T) -> Signal<V>, rightEnd: @escaping (U) -> Signal<W>, context: Exec = .direct, _ processor: @escaping ((T, U)) -> X) -> Signal<X> {
let leftDurations = valueDurations(duration: { t in leftEnd(t).takeWhile { _ in false } })
let rightDurations = withRight.valueDurations(duration: { u in rightEnd(u).takeWhile { _ in false } })
let a = leftDurations.combine(withState: ([Int: T](), [Int: U]()), second: rightDurations) { (state: inout (activeLeft: [Int: T], activeRight: [Int: U]), cr: EitherResult2<(Int, T?), (Int, U?)>, next: SignalNext<(T, U)>) in
switch cr {
case .result1(.success(let leftIndex, .some(let leftValue))):
state.activeLeft[leftIndex] = leftValue
state.activeRight.sorted { $0.0 < $1.0 }.forEach { tuple in next.send(value: (leftValue, tuple.value)) }
case .result2(.success(let rightIndex, .some(let rightValue))):
state.activeRight[rightIndex] = rightValue
state.activeLeft.sorted { $0.0 < $1.0 }.forEach { tuple in next.send(value: (tuple.value, rightValue)) }
case .result1(.success(let leftIndex, .none)): state.activeLeft.removeValue(forKey: leftIndex)
case .result2(.success(let rightIndex, .none)): state.activeRight.removeValue(forKey: rightIndex)
default: next.close()
}
}
return a.map(context: context, processor)
}
/// Implementation of [Reactive X operator "groupJoin"](http://reactivex.io/documentation/operators/join.html)
///
/// - parameter left: an observed signal.
/// - parameter right: an observed signal.
/// - parameter leftEnd: function invoked when a value is received from `left`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received left value.
/// - parameter rightEnd: function invoked when a value is received from `right`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `right` value.
/// - parameter context: the `Exec` where `processor` will be evaluated (default: .direct).
/// - parameter processor: when a `left` value is received, this function is invoked with the `left` value and a `Signal` that will emit all the `right` values encountered until the `left`->`leftEnd` window closes. The value returned by this function will be emitted as part of the `Signal` returned from `groupJoin`.
/// - returns: a signal that emits the values from the processor and closes when any of the last of the observed windows closes.
public func groupJoin<U, V, W, X>(withRight: Signal<U>, leftEnd: @escaping (T) -> Signal<V>, rightEnd: @escaping (U) -> Signal<W>, context: Exec = .direct, _ processor: @escaping ((T, Signal<U>)) -> X) -> Signal<X> {
let leftDurations = valueDurations(duration: { u in leftEnd(u).takeWhile { _ in false } })
let rightDurations = withRight.valueDurations(duration: { u in rightEnd(u).takeWhile { _ in false } })
return leftDurations.combine(withState: ([Int: SignalInput<U>](), [Int: U]()), second: rightDurations) { (state: inout (activeLeft: [Int: SignalInput<U>], activeRight: [Int: U]), cr: EitherResult2<(Int, T?), (Int, U?)>, next: SignalNext<(T, Signal<U>)>) in
switch cr {
case .result1(.success(let leftIndex, .some(let leftValue))):
let (li, ls) = Signal<U>.create()
state.activeLeft[leftIndex] = li
next.send(value: (leftValue, ls))
state.activeRight.sorted { $0.0 < $1.0 }.forEach { tuple in li.send(value: tuple.value) }
case .result2(.success(let rightIndex, .some(let rightValue))):
state.activeRight[rightIndex] = rightValue
state.activeLeft.sorted { $0.0 < $1.0 }.forEach { tuple in tuple.value.send(value: rightValue) }
case .result1(.success(let leftIndex, .none)):
_ = state.activeLeft[leftIndex]?.close()
state.activeLeft.removeValue(forKey: leftIndex)
case .result2(.success(let rightIndex, .none)):
state.activeRight.removeValue(forKey: rightIndex)
default: next.close()
}
}.map(context: context, processor)
}
/// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes.
///
/// NOTE: the signal closes as `SignalError.cancelled` when the last output closes. For other closing semantics, use `Signal.mergSetAndSignal` instead.
///
/// - parameter sources: an `Array` where `signal` is merged into the result.
/// - returns: a signal that emits every value from every `sources` input `signal`.
public static func merge<S: Sequence>(_ sources: S) -> Signal<T> where S.Iterator.Element == Signal<T> {
let (_, signal) = Signal<T>.createMergeSet(sources)
return signal
}
/// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes.
///
/// NOTE: the signal closes as `SignalError.cancelled` when the last output closes. For other closing semantics, use `Signal.mergSetAndSignal` instead.
///
/// - parameter sources: an `Array` where `signal` is merged into the result.
/// - returns: a signal that emits every value from every `sources` input `signal`.
public func mergeWith(_ sources: Signal<T>...) -> Signal<T> {
let (mergeSet, signal) = Signal<T>.createMergeSet()
try! mergeSet.add(self)
for s in sources {
try! mergeSet.add(s)
}
return signal
}
/// Implementation of [Reactive X operator "startWith"](http://reactivex.io/documentation/operators/startwith.html)
///
/// - parameter sequence: a sequence of values.
/// - returns: a signal that emits every value from `sequence` on activation and then mirrors `self`.
public func startWith<S: Sequence>(_ sequence: S) -> Signal<T> where S.Iterator.Element == T {
return Signal.preclosed(values: sequence).combine(second: self) { (r: EitherResult2<T, T>, n: SignalNext<T>) in
switch r {
case .result1(.success(let v)): n.send(value: v)
case .result1(.failure): break
case .result2(.success(let v)): n.send(value: v)
case .result2(.failure(let e)): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "endWith"](http://reactivex.io/documentation/operators/endwith.html)
///
/// - returns: a signal that emits every value from `sequence` on activation and then mirrors `self`.
public func endWith<U: Sequence>(_ sequence: U, conditional: @escaping (Error) -> Error? = { e in e }) -> Signal<T> where U.Iterator.Element == T {
return transform() { (r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v): n.send(value: v)
case .failure(let e):
if let newEnd = conditional(e) {
sequence.forEach { n.send(value: $0) }
n.send(error: newEnd)
} else {
n.send(error: e)
}
}
}
}
/// Implementation of [Reactive X operator "switch"](http://reactivex.io/documentation/operators/switch.html)
///
/// See also: `flatMapLatest` (emits values from the latest `Signal` to start emitting)
///
/// NOTE: ideally, this would not be a static function but a "same type" conditional extension. In a future Swift release this will probably change.
///
/// - returns: a signal that emits the values from the latest `Signal` emitted by `self`.
public static func switchLatest<T>(_ signal: Signal<Signal<T>>) -> Signal<T> {
return signal.transformFlatten(withState: nil, closesImmediate: true) { (latest: inout Signal<T>?, next: Signal<T>, mergeSet: SignalMergeSet<T>) in
if let l = latest {
mergeSet.remove(l)
}
latest = next
_ = try? mergeSet.add(next, closesOutput: false, removeOnDeactivate: true)
}
}
/// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html)
///
/// - parameter with: another `Signal`
/// - returns: a signal that emits the values from `self`, paired with corresponding value from `with`.
public func zip<U>(second: Signal<U>) -> Signal<(T, U)> {
return combine(withState: (Array<T>(), Array<U>(), false, false), second: second) { (queues: inout (first: Array<T>, second: Array<U>, firstClosed: Bool, secondClosed: Bool), r: EitherResult2<T, U>, n: SignalNext<(T, U)>) in
switch (r, queues.first.first, queues.second.first) {
case (.result1(.success(let first)), _, .some(let second)):
n.send(value: (first, second))
queues.second.removeFirst()
if (queues.second.isEmpty && queues.secondClosed) {
n.close()
}
case (.result1(.success(let first)), _, _):
queues.first.append(first)
case (.result1(.failure(let e)), _, _):
if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) {
n.send(error: e)
} else {
queues.firstClosed = true
}
case (.result2(.success(let second)), .some(let first), _):
n.send(value: (first, second))
queues.first.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) {
n.close()
}
case (.result2(.success(let second)), _, _):
queues.second.append(second)
case (.result2(.failure(let e)), _, _):
if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) {
n.send(error: e)
} else {
queues.secondClosed = true
}
}
}
}
/// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html)
///
/// - parameter with: another `Signal`
/// - returns: a signal that emits the values from `self`, paired with corresponding value from `with`.
public func zip<U, V>(second: Signal<U>, third: Signal<V>) -> Signal<(T, U, V)> {
return combine(withState: (Array<T>(), Array<U>(), Array<V>(), false, false, false), second: second, third: third) { (queues: inout (first: Array<T>, second: Array<U>, third: Array<V>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool), r: EitherResult3<T, U, V>, n: SignalNext<(T, U, V)>) in
switch (r, queues.first.first, queues.second.first, queues.third.first) {
case (.result1(.success(let first)), _, .some(let second), .some(let third)):
n.send(value: (first, second, third))
queues.second.removeFirst()
queues.third.removeFirst()
if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.close()
}
case (.result1(.success(let first)), _, _, _):
queues.first.append(first)
case (.result1(.failure(let e)), _, _, _):
if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.send(error: e)
} else {
queues.firstClosed = true
}
case (.result2(.success(let second)), .some(let first), _, .some(let third)):
n.send(value: (first, second, third))
queues.first.removeFirst()
queues.third.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.close()
}
case (.result2(.success(let second)), _, _, _):
queues.second.append(second)
case (.result2(.failure(let e)), _, _, _):
if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.send(error: e)
} else {
queues.secondClosed = true
}
case (.result3(.success(let third)), .some(let first), .some(let second), _):
n.send(value: (first, second, third))
queues.first.removeFirst()
queues.second.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) {
n.close()
}
case (.result3(.success(let third)), _, _, _):
queues.third.append(third)
case (.result3(.failure(let e)), _, _, _):
if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) {
n.send(error: e)
} else {
queues.thirdClosed = true
}
}
}
}
/// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html)
///
/// - parameter with: another `Signal`
/// - returns: a signal that emits the values from `self`, paired with corresponding value from `with`.
public func zip<U, V, W>(second: Signal<U>, third: Signal<V>, fourth: Signal<W>) -> Signal<(T, U, V, W)> {
return combine(withState: (Array<T>(), Array<U>(), Array<V>(), Array<W>(), false, false, false, false), second: second, third: third, fourth: fourth) { (queues: inout (first: Array<T>, second: Array<U>, third: Array<V>, fourth: Array<W>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool, fourthClosed: Bool), r: EitherResult4<T, U, V, W>, n: SignalNext<(T, U, V, W)>) in
switch (r, queues.first.first, queues.second.first, queues.third.first, queues.fourth.first) {
case (.result1(.success(let first)), _, .some(let second), .some(let third), .some(let fourth)):
n.send(value: (first, second, third, fourth))
queues.second.removeFirst()
queues.third.removeFirst()
queues.fourth.removeFirst()
if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.close()
}
case (.result1(.success(let first)), _, _, _, _):
queues.first.append(first)
case (.result1(.failure(let e)), _, _, _, _):
if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.send(error: e)
} else {
queues.firstClosed = true
}
case (.result2(.success(let second)), .some(let first), _, .some(let third), .some(let fourth)):
n.send(value: (first, second, third, fourth))
queues.first.removeFirst()
queues.third.removeFirst()
queues.fourth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.close()
}
case (.result2(.success(let second)), _, _, _, _):
queues.second.append(second)
case (.result2(.failure(let e)), _, _, _, _):
if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.send(error: e)
} else {
queues.secondClosed = true
}
case (.result3(.success(let third)), .some(let first), .some(let second), _, .some(let fourth)):
n.send(value: (first, second, third, fourth))
queues.first.removeFirst()
queues.second.removeFirst()
queues.fourth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.close()
}
case (.result3(.success(let third)), _, _, _, _):
queues.third.append(third)
case (.result3(.failure(let e)), _, _, _, _):
if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.send(error: e)
} else {
queues.thirdClosed = true
}
case (.result4(.success(let fourth)), .some(let first), .some(let second), .some(let third), _):
n.send(value: (first, second, third, fourth))
queues.first.removeFirst()
queues.second.removeFirst()
queues.third.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.close()
}
case (.result4(.success(let fourth)), _, _, _, _):
queues.fourth.append(fourth)
case (.result4(.failure(let e)), _, _, _, _):
if queues.fourth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) {
n.send(error: e)
} else {
queues.fourthClosed = true
}
}
}
}
/// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html)
///
/// - parameter with: another `Signal`
/// - returns: a signal that emits the values from `self`, paired with corresponding value from `with`.
public func zip<U, V, W, X>(second: Signal<U>, third: Signal<V>, fourth: Signal<W>, fifth: Signal<X>) -> Signal<(T, U, V, W, X)> {
return combine(withState: (Array<T>(), Array<U>(), Array<V>(), Array<W>(), Array<X>(), false, false, false, false, false), second: second, third: third, fourth: fourth, fifth: fifth) { (queues: inout (first: Array<T>, second: Array<U>, third: Array<V>, fourth: Array<W>, fifth: Array<X>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool, fourthClosed: Bool, fifthClosed: Bool), r: EitherResult5<T, U, V, W, X>, n: SignalNext<(T, U, V, W, X)>) in
switch (r, queues.first.first, queues.second.first, queues.third.first, queues.fourth.first, queues.fifth.first) {
case (.result1(.success(let first)), _, .some(let second), .some(let third), .some(let fourth), .some(let fifth)):
n.send(value: (first, second, third, fourth, fifth))
queues.second.removeFirst()
queues.third.removeFirst()
queues.fourth.removeFirst()
queues.fifth.removeFirst()
if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.close()
}
case (.result1(.success(let first)), _, _, _, _, _):
queues.first.append(first)
case (.result1(.failure(let e)), _, _, _, _, _):
if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.send(error: e)
} else {
queues.firstClosed = true
}
case (.result2(.success(let second)), .some(let first), _, .some(let third), .some(let fourth), .some(let fifth)):
n.send(value: (first, second, third, fourth, fifth))
queues.first.removeFirst()
queues.third.removeFirst()
queues.fourth.removeFirst()
queues.fifth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.close()
}
case (.result2(.success(let second)), _, _, _, _, _):
queues.second.append(second)
case (.result2(.failure(let e)), _, _, _, _, _):
if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.send(error: e)
} else {
queues.secondClosed = true
}
case (.result3(.success(let third)), .some(let first), .some(let second), _, .some(let fourth), .some(let fifth)):
n.send(value: (first, second, third, fourth, fifth))
queues.first.removeFirst()
queues.second.removeFirst()
queues.fourth.removeFirst()
queues.fifth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.close()
}
case (.result3(.success(let third)), _, _, _, _, _):
queues.third.append(third)
case (.result3(.failure(let e)), _, _, _, _, _):
if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.send(error: e)
} else {
queues.thirdClosed = true
}
case (.result4(.success(let fourth)), .some(let first), .some(let second), .some(let third), _, .some(let fifth)):
n.send(value: (first, second, third, fourth, fifth))
queues.first.removeFirst()
queues.second.removeFirst()
queues.third.removeFirst()
queues.fifth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.close()
}
case (.result4(.success(let fourth)), _, _, _, _, _):
queues.fourth.append(fourth)
case (.result4(.failure(let e)), _, _, _, _, _):
if queues.fourth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fifth.isEmpty && queues.fifthClosed) {
n.send(error: e)
} else {
queues.fourthClosed = true
}
case (.result5(.success(let fifth)), .some(let first), .some(let second), .some(let third), .some(let fourth), _):
n.send(value: (first, second, third, fourth, fifth))
queues.first.removeFirst()
queues.second.removeFirst()
queues.third.removeFirst()
queues.fourth.removeFirst()
if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.close()
}
case (.result5(.success(let fifth)), _, _, _, _, _):
queues.fifth.append(fifth)
case (.result5(.failure(let e)), _, _, _, _, _):
if queues.fifth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) {
n.send(error: e)
} else {
queues.fifthClosed = true
}
}
}
}
/// Implementation of [Reactive X operator "catch"](http://reactivex.io/documentation/operators/catch.html), returning a sequence on error in `self`.
///
/// - parameter recover: a function that, when passed the `ErrorType` that closed `self`, returns a sequence of values and an `ErrorType` that should be emitted instead of the error that `self` emitted.
/// - returns: a signal that emits the values from `self` until an error is received and then emits the values from `recover` and then emits the error from `recover`.
public func catchError<S: Sequence>(context: Exec = .direct, recover: @escaping (Error) -> (S, Error)) -> Signal<T> where S.Iterator.Element == T {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v): n.send(value: v)
case .failure(let e):
let (sequence, error) = recover(e)
sequence.forEach { n.send(value: $0) }
n.send(error: error)
}
}
}
}
// Essentially a closure type used by `catchError`, defined as a separate class so the function can reference itself
private class CatchErrorRecovery<T> {
fileprivate let recover: (Error) -> Signal<T>?
fileprivate init(recover: @escaping (Error) -> Signal<T>?) {
self.recover = recover
}
fileprivate func catchErrorRejoin(j: SignalJunction<T>, e: Error, i: SignalInput<T>) {
if let s = recover(e) {
do {
let f: (SignalJunction<T>, Error, SignalInput<T>) -> () = self.catchErrorRejoin
try s.join(to: i, onError: f)
} catch {
i.send(error: error)
}
} else {
i.send(error: e)
}
}
}
// Essentially a closure type used by `retry`, defined as a separate class so the function can reference itself
private class RetryRecovery<U> {
fileprivate let shouldRetry: (inout U, Error) -> DispatchTimeInterval?
fileprivate var state: U
fileprivate let context: Exec
fileprivate var timer: Cancellable? = nil
fileprivate init(shouldRetry: @escaping (inout U, Error) -> DispatchTimeInterval?, state: U, context: Exec) {
self.shouldRetry = shouldRetry
self.state = state
self.context = context
}
fileprivate func retryRejoin<T>(j: SignalJunction<T>, e: Error, i: SignalInput<T>) {
if let t = shouldRetry(&state, e) {
timer = context.singleTimer(interval: t) {
do {
try j.join(to: i, onError: self.retryRejoin)
} catch {
i.send(error: error)
}
}
} else {
i.send(error: e)
}
}
}
extension Signal {
/// Implementation of [Reactive X operator "catch"](http://reactivex.io/documentation/operators/catch.html), returning a `Signal` on error in `self`.
///
/// - parameter recover: a function that, when passed the `ErrorType` that closed `self`, returns an `Optional<Signal<T>>`.
/// - returns: a signal that emits the values from `self` until an error is received and then, if `recover` returns non-`nil` emits the values from `recover` and then emits the error from `recover`, otherwise if `recover` returns `nil`, emits the `ErrorType` from `self`.
public func catchError(context: Exec = .direct, recover: @escaping (Error) -> Signal<T>?) -> Signal<T> {
let (input, signal) = Signal<T>.create()
do {
try join(to: input, onError: CatchErrorRecovery(recover: recover).catchErrorRejoin)
} catch {
input.send(error: error)
}
return signal
}
/// Implementation of [Reactive X operator "retry"](http://reactivex.io/documentation/operators/retry.html) where the choice to retry and the delay between retries is controlled by a function.
///
/// - Note: a ReactiveX "resubscribe" is interpreted as a disconnect and reconnect, which will trigger reactivation iff the preceding nodes have behavior that supports that.
///
/// - parameter initialState: a mutable state value that will be passed into `shouldRetry`.
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter shouldRetry: a function that, when passed the current state value and the `ErrorType` that closed `self`, returns an `Optional<Double>`.
/// - returns: a signal that emits the values from `self` until an error is received and then, if `shouldRetry` returns non-`nil`, disconnects from `self`, delays by the number of seconds returned from `shouldRetry`, and reconnects to `self` (triggering re-activation), otherwise if `shouldRetry` returns `nil`, emits the `ErrorType` from `self`. If the number of seconds is `0`, the reconnect is synchronous, otherwise it will occur in `context` using `invokeAsync`.
public func retry<U>(_ initialState: U, context: Exec = .direct, shouldRetry: @escaping (inout U, Error) -> DispatchTimeInterval?) -> Signal<T> {
let (input, signal) = Signal<T>.create()
do {
try join(to: input, onError: RetryRecovery(shouldRetry: shouldRetry, state: initialState, context: context).retryRejoin)
} catch {
input.send(error: error)
}
return signal
}
/// Implementation of [Reactive X operator "retry"](http://reactivex.io/documentation/operators/retry.html) where retries occur until the error is not `SignalError.Closed` or `count` number of retries has occurred.
///
/// - Note: a ReactiveX "resubscribe" is interpreted as a disconnect and reconnect, which will trigger reactivation iff the preceding nodes have behavior that supports that.
///
/// - parameter count: the maximum number of retries
/// - parameter delaySeconds: the number of seconds between retries
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter shouldRetry: a function that, when passed the current state value and the `ErrorType` that closed `self`, returns an `Optional<Double>`.
/// - returns: a signal that emits the values from `self` until an error is received and then, if fewer than `count` retries have occurred, disconnects from `self`, delays by `delaySeconds` and reconnects to `self` (triggering re-activation), otherwise if `count` retries have occurred, emits the `ErrorType` from `self`. If the number of seconds is `0`, the reconnect is synchronous, otherwise it will occur in `context` using `invokeAsync`.
public func retry(count: Int, delayInterval: DispatchTimeInterval, context: Exec = .direct) -> Signal<T> {
return retry(0, context: context) { (retryCount: inout Int, e: Error) -> DispatchTimeInterval? in
if e as? SignalError == .closed {
return nil
} else if retryCount < count {
retryCount += 1
return delayInterval
} else {
return nil
}
}
}
/// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by running an `offset` function.
///
/// - parameter initialState: a user state value passed into the `offset` function
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter offset: a function that, when passed the current state value and the latest value from `self`, returns the number of seconds that the value should be delayed (values less or equal to 0 are sent immediately).
/// - returns: a mirror of `self` where values are offset according to `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last).
public func delay<U>(withState initialState: U, closesImmediate: Bool = false, context: Exec = .direct, offset: @escaping (inout U, T) -> DispatchTimeInterval) -> Signal<T> {
return delay(withState: initialState, closesImmediate: closesImmediate, context: context) { (state: inout U, value: T) -> Signal<()> in
return Signal<()>.timer(interval: offset(&state, value), context: context)
}
}
/// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is constant.
///
/// - parameter seconds: the delay for each value
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - returns: a mirror of `self` where values are delayed by `seconds` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last).
public func delay(interval: DispatchTimeInterval, closesImmediate: Bool = false, context: Exec = .direct) -> Signal<T> {
return delay(withState: interval, closesImmediate: closesImmediate, context: context) { (s: inout DispatchTimeInterval, v: T) -> DispatchTimeInterval in s }
}
/// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by the duration of a signal returned from `offset`.
///
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter offset: a function that, when passed the latest value from `self`, returns a `Signal`.
/// - returns: a mirror of `self` where values are delayed by the duration of signals returned from `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last).
public func delay<U>(closesImmediate: Bool = false, context: Exec = .direct, offset: @escaping (T) -> Signal<U>) -> Signal<T> {
return delay(withState: (), closesImmediate: closesImmediate, context: context) { (state: inout (), value: T) -> Signal<U> in return offset(value) }
}
/// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by the duration of a signal returned from `offset`.
///
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter offset: a function that, when passed the latest value from `self`, returns a `Signal`.
/// - returns: a mirror of `self` where values are delayed by the duration of signals returned from `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last).
public func delay<U, V>(withState initialState: V, closesImmediate: Bool, context: Exec = .direct, offset: @escaping (inout V, T) -> Signal<U>) -> Signal<T> {
return valueDurations(withState: initialState, closesImmediate: closesImmediate, context: context, duration: offset).transform(withState: [Int: T]()) { (values: inout [Int: T], r: Result<(Int, T?)>, n: SignalNext<T>) in
switch r {
case .success(let index, .some(let t)): values[index] = t
case .success(let index, .none): _ = values[index].map { n.send(value: $0) }
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "activation" (not a concept that directly exists in ReactiveX but similar to doOnSubscribe).
///
/// - parameter context: where the handler will be invoked
/// - parameter handler: invoked when self is activated
///
/// - returns: a signal that emits the same outputs as self
public func onActivate(context: Exec = .direct, handler: @escaping () -> ()) -> Signal<T> {
let signal = Signal<T>.generate { input in
if let i = input {
do {
handler()
try self.join(to: i)
} catch {
i.send(error: error)
}
}
}
return signal
}
/// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "deactivation" (not a concept that directly exists in ReactiveX but similar to doOnUnsubscribe).
///
/// - parameter context: where the handler will be invoked
/// - parameter handler: invoked when self is deactivated
///
/// - returns: a signal that emits the same outputs as self
public func onDeactivate(context: Exec = .direct, f: @escaping () -> ()) -> Signal<T> {
let signal = Signal<T>.generate { input in
if let i = input {
do {
try self.join(to: i)
} catch {
i.send(error: error)
}
} else {
f()
}
}
return signal
}
/// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "result" (equivalent to doOnEach).
///
/// - parameter context: where the handler will be invoked
/// - parameter handler: invoked when a result is emitted
///
/// - returns: a signal that emits the same outputs as self
public func onResult(context: Exec = .direct, handler: @escaping (Result<T>) -> ()) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) in
handler(r)
n.send(result: r)
}
}
/// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "values" (equivalent to doOnNext).
///
/// - parameter context: where the handler will be invoked
/// - parameter handler: invoked when a values is emitted
///
/// - returns: a signal that emits the same outputs as self
public func onValue(context: Exec = .direct, handler: @escaping (T) -> ()) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v):
handler(v)
n.send(value: v)
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "errors" (equivalent to doOnTerminate).
///
/// - parameter context: where the handler will be invoked
/// - parameter handler: invoked when an error is emitted
///
/// - returns: a signal that emits the same outputs as self
public func onError(context: Exec = .direct, handler: @escaping (Error) -> ()) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v):
n.send(value: v)
case .failure(let e):
handler(e)
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "materialize"](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
///
/// WARNING: in CwlSignal, this operator will emit a `SignalError.cancelled` into the output signal immediately after emitting the first wrapped error. Within the "first error closes signal" behavior of CwlSignal, this is the only behavior that makes sense, however, it does limit the usefulness of `materialize` to constructions where the `materialize` signal immediately outputs into a `SignalMergeSet` (including abstractions built on top, like `switchLatest` or child signals of a `flatMap`) that ignores the actual close of the source signal.
///
/// - parameter context: the `Exec` where timed reconnection will occcur (default: .Default).
/// - parameter offset: a function that, when passed the latest value from `self`, returns a `Signal`.
/// - returns: a mirror of `self` where values are delayed by the duration of signals returned from `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last).
public func materialize() -> Signal<Result<T>> {
return transform { r, n in
n.send(value: r)
if r.isError {
n.send(error: SignalError.cancelled)
}
}
}
/// Implementation of [Reactive X operator "dematerialize"](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
///
/// NOTE: ideally, this would not be a static function but a "same type" conditional extension. In a future Swift release this will probably change.
///
/// - parameter signal: a signal whose ValueType is a `Result` wrapped version of an underlying type
///
/// - returns: a signal whose ValueType is the unwrapped value from the input, with unwrapped errors sent as errors.
public static func dematerialize<T>(_ signal: Signal<Result<T>>) -> Signal<T> {
return signal.transform { (r: Result<Result<T>>, n: SignalNext<T>) in
switch r {
case .success(.success(let v)): n.send(value: v)
case .success(.failure(let e)): n.send(error: e)
case .failure(let e): n.send(error: e)
}
}
}
}
extension Signal {
/// - Note: the [Reactive X operator "ObserveOn"](http://reactivex.io/documentation/operators/observeon.html) doesn't apply to CwlSignal.Signal since any CwlSignal.Signal that runs work can specify their own execution context and control scheduling in that way.
/// - Note: the [Reactive X operator "Serialize"](http://reactivex.io/documentation/operators/serialize.html) doesn't apply to CwlSignal.Signal since all CwlSignal.Signal instances are serialized and well-behaved.
/// - Note: the [Reactive X operator "Subscribe" and "SubscribeOn"](http://reactivex.io/documentation/operators/subscribe.html) are implemented as `subscribe`.
}
extension Signal {
/// Implementation of [Reactive X operator "TimeInterval"](http://reactivex.io/documentation/operators/timeinterval.html)
///
/// - parameter context: time between emissions will be calculated based on the timestamps from this context
///
/// - returns: a signal where the values are seconds between emissions from self
public func timeInterval(context: Exec = .direct) -> Signal<Double> {
let signal = Signal<()>.generate { input in
if let i = input {
do {
i.send(value: ())
try self.map { v in () }.join(to: i)
} catch {
i.send(error: error)
}
}
}.transform(withState: nil, context: context) { (lastTime: inout DispatchTime?, r: Result<()>, n: SignalNext<Double>) in
switch r {
case .success:
let currentTime = context.timestamp()
if let l = lastTime {
n.send(value: currentTime.since(l).toSeconds())
}
lastTime = currentTime
case .failure(let e): n.send(error: e)
}
}
return signal
}
/// Implementation of [Reactive X operator "Timeout"](http://reactivex.io/documentation/operators/timeout.html)
///
/// - parameter interval: the duration before a SignalError.timeout will be emitted
/// - parameter resetOnValue: if `true`, each value sent through the signal will reset the timer (making the timeout an "idle" timeout). If `false`, the timeout duration is measured from the start of the signal and is unaffected by whether values are received.
/// - parameter context: timestamps will be added based on the time in this context
///
/// - returns: a mirror of self unless a timeout occurs, in which case it will closed by a SignalError.timeout
public func timeout(interval: DispatchTimeInterval, resetOnValue: Bool = true, context: Exec = .direct) -> Signal<T> {
let (junction, signal) = Signal<()>.timer(interval: interval, context: context).junctionSignal()
return self.combine(second: signal, context: context) { (cr: EitherResult2<T, ()>, n: SignalNext<T>) in
switch cr {
case .result1(let r):
if resetOnValue {
junction.rejoin()
}
n.send(result: r)
case .result2: n.send(error: SignalError.timeout)
}
}
}
/// Implementation of [Reactive X operator "Timestamp"](http://reactivex.io/documentation/operators/timestamp.html)
///
/// - parameter context: used as the source of time
///
/// - returns: a signal where the values are a two element tuple, first element is self.ValueType, second element is the `DispatchTime` timestamp that this element was emitted from self.
public func timestamp(context: Exec = .direct) -> Signal<(T, DispatchTime)> {
return transform(context: context) { (r: Result<T>, n: SignalNext<(T, DispatchTime)>) in
switch r {
case .success(let v): n.send(value: (v, context.timestamp()))
case .failure(let e): n.send(error: e)
}
}
}
}
extension Signal {
/// - Note: the [Reactive X operator "Using"](http://reactivex.io/documentation/operators/using.html) doesn't apply to CwlSignal.Signal which uses standard Swift reference counted lifetimes. Resources should be captured by closures or `transform(withState:...)`.
}
extension Signal {
/// Implementation of [Reactive X operator "All"](http://reactivex.io/documentation/operators/all.html)
///
/// - parameter context: the `test` function will be run in this context
/// - parameter test: will be invoked for every value
///
/// - returns: a signal that emits true and then closes if every value emitted by self returned true from the `test` function and self closed normally, otherwise emits false and then closes
public func all(context: Exec = .direct, test: @escaping (T) -> Bool) -> Signal<Bool> {
return transform(context: context) { (r: Result<T>, n: SignalNext<Bool>) in
switch r {
case .success(let v) where !test(v):
n.send(value: false)
n.close()
case .failure(SignalError.closed):
n.send(value: true)
n.close()
case .failure(let e): n.send(error: e)
default: break;
}
}
}
/// Implementation of [Reactive X operator "Amb"](http://reactivex.io/documentation/operators/amb.html)
///
/// - parameter inputs: a set of inputs
///
/// - returns: connects to all inputs then emits the full set of values from the first of these to emit a value
public static func amb<S: Sequence>(inputs: S) -> Signal<T> where S.Iterator.Element == Signal<T> {
let (mergeSet, signal) = Signal<(Int, Result<T>)>.createMergeSet()
inputs.enumerated().forEach { s in
_ = try? mergeSet.add(s.element.transform { r, n in
n.send(value: (s.offset, r))
})
}
return signal.transform(withState: -1) { (first: inout Int, r: Result<(Int, Result<T>)>, n: SignalNext<T>) in
switch r {
case .success(let index, let underlying) where first < 0:
first = index
n.send(result: underlying)
case .success(let index, let underlying) where first < 0 || first == index: n.send(result: underlying)
case .failure(let e): n.send(error: e)
default: break
}
}
}
/// Implementation of [Reactive X operator "Some"](http://reactivex.io/documentation/operators/some.html)
///
/// - parameter context: context where `test` will run
/// - parameter test: invoked for every value emitted from self
///
/// - returns: a signal that emits true and then closes when a value emitted by self returns true from the `test` function, otherwise if no values from self return true, emits false and then closes
public func some(context: Exec = .direct, test: @escaping (T) -> Bool) -> Signal<Bool> {
return transform(context: context) { (r: Result<T>, n: SignalNext<Bool>) in
switch r {
case .success(let v) where test(v):
n.send(value: true)
n.close()
case .success:
break
case .failure(let e):
n.send(value: false)
n.send(error: e)
}
}
}
}
extension Signal where T: Equatable {
/// Implementation of [Reactive X operator "Some"](http://reactivex.io/documentation/operators/some.html)
///
/// - parameter value: every value emitted by self is tested for equality with this value
///
/// - returns: a signal that emits true and then closes when a value emitted by self tests as `==` to `value`, otherwise if no values from self test as equal, emits false and then closes
public func contains(value: T) -> Signal<Bool> {
return some { value == $0 }
}
}
extension Signal {
/// Implementation of [Reactive X operator "DefaultIfEmpty"](http://reactivex.io/documentation/operators/defaultifempty.html)
///
/// - parameter value: value to emit if self closes without a value
///
/// - returns: a signal that emits the same values as self or `value` if self closes without emitting a value
public func defaultIfEmpty(value: T) -> Signal<T> {
return transform(withState: false) { (started: inout Bool, r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v):
started = true
n.send(value: v)
case .failure(let e) where !started:
n.send(value: value)
n.send(error: e)
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "SwitchIfEmpty"](http://reactivex.io/documentation/operators/switchifempty.html)
///
/// - parameter alternate: content will be used if self closes without emitting a value
///
/// - returns: a signal that emits the same values as self or mirrors `alternate` if self closes without emitting a value
public func switchIfEmpty(alternate: Signal<T>) -> Signal<T> {
var fallback: Signal<T>? = alternate
let (input, signal) = Signal<T>.create { s -> Signal<T> in
s.map { v in
fallback = nil
return v
}
}
do {
try join(to: input) { (j: SignalJunction<T>, e: Error, i: SignalInput<T>) in
do {
if let f = fallback {
try f.join(to: i)
} else {
i.send(error: e)
}
} catch {
i.send(error: error)
}
}
} catch {
input.send(error: error)
}
return signal
}
}
extension Signal where T: Equatable {
/// Implementation of [Reactive X operator "SequenceEqual"](http://reactivex.io/documentation/operators/sequenceequal.html)
///
/// - parameter to: another signal whose contents will be compared to this signal
///
/// - returns: a signal that emits `true` if `self` and `to` are equal, `false` otherwise
public func sequenceEqual(to: Signal<T>) -> Signal<Bool> {
return combine(withState: (Array<T>(), Array<T>(), false, false), second: to) { (state: inout (lq: Array<T>, rq: Array<T>, lc: Bool, rc: Bool), r: EitherResult2<T, T>, n: SignalNext<Bool>) in
// state consists of lq (left queue), rq (right queue), lc (left closed), rc (right closed)
switch (r, state.lq.first, state.rq.first) {
case (.result1(.success(let left)), _, .some(let right)):
if left != right {
n.send(value: false)
n.close()
}
state.rq.removeFirst()
case (.result1(.success(let left)), _, _):
state.lq.append(left)
case (.result2(.success(let right)), .some(let left), _):
if left != right {
n.send(value: false)
n.close()
}
state.lq.removeFirst()
case (.result2(.success(let right)), _, _):
state.rq.append(right)
case (.result1(.failure(let e)), _, _):
state.lc = true
if state.rc {
if state.lq.count == state.rq.count {
n.send(value: true)
} else {
n.send(value: false)
}
n.send(error: e)
}
case (.result2(.failure(let e)), _, _):
state.rc = true
if state.lc {
if state.lq.count == state.rq.count {
n.send(value: true)
} else {
n.send(value: false)
}
n.send(error: e)
}
}
}
}
}
extension Signal {
/// Implementation of [Reactive X operator "SkipUntil"](http://reactivex.io/documentation/operators/skipuntil.html)
///
/// - parameter other: until this signal emits a value, all values from self will be dropped
///
/// - returns: a signal that mirrors `self` after `other` emits a value (but won't emit anything prior)
public func skipUntil<U>(_ other: Signal<U>) -> Signal<T> {
return combine(withState: false, second: other) { (started: inout Bool, cr: EitherResult2<T, U>, n: SignalNext<T>) in
switch cr {
case .result1(.success(let v)) where started: n.send(value: v)
case .result1(.success): break
case .result1(.failure(let e)): n.send(error: e)
case .result2(.success): started = true
case .result2(.failure): break
}
}
}
/// Implementation of [Reactive X operator "SkipWhile"](http://reactivex.io/documentation/operators/skipwhile.html)
///
/// - parameter context: execution context where `condition` will be run
/// - parameter condition: will be run for every value emitted from `self` until `condition` returns `true`
///
/// - returns: a signal that mirrors `self` dropping values until `condition` returns `true` for one of the values
public func skipWhile(context: Exec = .direct, condition: @escaping (T) -> Bool) -> Signal<T> {
return transform(withState: false, context: context) { (started: inout Bool, r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v) where !started && condition(v):
break
case .success(let v):
started = true
n.send(value: v)
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "SkipWhile"](http://reactivex.io/documentation/operators/skipwhile.html)
///
/// - parameter context: execution context where `condition` will be run
/// - parameter condition: will be run for every value emitted from `self` until `condition` returns `true`
///
/// - returns: a signal that mirrors `self` dropping values until `condition` returns `true` for one of the values
public func skipWhile<U>(withState initial: U, context: Exec = .direct, condition: @escaping (inout U, T) -> Bool) -> Signal<T> {
return transform(withState: (initial, false), context: context) { (started: inout (U, Bool), r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v) where !started.1 && condition(&started.0, v):
break
case .success(let v):
started.1 = true
n.send(value: v)
case .failure(let e):
n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "TakeUntil"](http://reactivex.io/documentation/operators/takeuntil.html)
///
/// - parameter other: after this signal emits a value, all values from self will be dropped
///
/// - returns: a signal that mirrors `self` until `other` emits a value (but won't emit anything after)
public func takeUntil<U>(_ other: Signal<U>) -> Signal<T> {
return combine(withState: false, second: other) { (started: inout Bool, cr: EitherResult2<T, U>, n: SignalNext<T>) in
switch cr {
case .result1(.success(let v)) where !started: n.send(value: v)
case .result1(.success): break
case .result1(.failure(let e)): n.send(error: e)
case .result2(.success): started = true
case .result2(.failure): break
}
}
}
/// Implementation of [Reactive X operator "TakeWhile"](http://reactivex.io/documentation/operators/takewhile.html)
///
/// - parameter context: execution context where `condition` will be run
/// - parameter condition: will be run for every value emitted from `self` until `condition` returns `true`
///
/// - returns: a signal that mirrors `self` dropping values after `condition` returns `true` for one of the values
public func takeWhile(context: Exec = .direct, condition: @escaping (T) -> Bool) -> Signal<T> {
return transform(context: context) { (r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v) where condition(v): n.send(value: v)
case .success: n.close()
case .failure(let e): n.send(error: e)
}
}
}
/// Implementation of [Reactive X operator "TakeWhile"](http://reactivex.io/documentation/operators/takewhile.html)
///
/// - parameter context: execution context where `condition` will be run
/// - parameter condition: will be run for every value emitted from `self` until `condition` returns `true`
///
/// - returns: a signal that mirrors `self` dropping values after `condition` returns `true` for one of the values
public func takeWhile<U>(withState initial: U, context: Exec = .direct, condition: @escaping (inout U, T) -> Bool) -> Signal<T> {
return transform(withState: initial, context: context) { (i: inout U, r: Result<T>, n: SignalNext<T>) in
switch r {
case .success(let v) where condition(&i, v): n.send(value: v)
case .success: n.close()
case .failure(let e): n.send(error: e)
}
}
}
/// A helper method used for mathematical operators. Performs a basic `fold` over the values emitted by `self` then passes the final result through another `finalize` function before emitting the result as a value in the returned signal.
///
/// - parameter initial: used to initialize the fold state
/// - parameter context: all functions will be invoked in this context
/// - parameter finalize: invoked when `self` closes, with the current fold state value
/// - parameter fold: invoked for each value emitted by `self` along with the current fold state value
///
/// - returns: a signal which emits the `finalize` result
public func foldAndFinalize<U, V>(_ initial: V, context: Exec = .direct, finalize: @escaping (V) -> U?, fold: @escaping (V, T) -> V) -> Signal<U> {
return transform(withState: initial, context: context) { (state: inout V, r: Result<T>, n: SignalNext<U>) in
switch r {
case .success(let v):
state = fold(state, v)
case .failure(let e):
if let v = finalize(state) {
n.send(value: v)
}
n.send(error: e)
}
}
}
}
extension Signal where T: BinaryInteger {
/// Implementation of [Reactive X operator "Average"](http://reactivex.io/documentation/operators/average.html)
///
/// - returns: a signal that emits a single value... the sum of all values emitted by `self`
public func average() -> Signal<T> {
return foldAndFinalize((0, 0), finalize: { (fold: (T, T)) -> T? in fold.0 > 0 ? fold.1 / fold.0 : nil }) { (fold: (T, T), value: T) -> (T, T) in
return (fold.0 + 1, fold.1 + value)
}
}
}
extension Signal {
/// Implementation of [Reactive X operator "Concat"](http://reactivex.io/documentation/operators/concat.html)
///
/// - parameter other: a second signal
///
/// - returns: a signal that emits all the values from `self` followed by all the values from `other` (including those emitted while `self` was still active)
public func concat(_ other: Signal<T>) -> Signal<T> {
return combine(withState: ([T](), nil, nil), second: other) { (state: inout (secondValues: [T], firstError: Error?, secondError: Error?), cr: EitherResult2<T, T>, n: SignalNext<T>) in
switch (cr, state.firstError) {
case (.result1(.success(let v)), _):
n.send(value: v)
case (.result1(.failure(let e1)), _):
for v in state.secondValues {
n.send(value: v)
}
if let e2 = state.secondError {
n.send(error: e2)
} else {
state.firstError = e1
}
case (.result2(.success(let v)), .none):
state.secondValues.append(v)
case (.result2(.success(let v)), .some):
n.send(value: v)
case (.result2(.failure(let e2)), .none):
state.secondError = e2
case (.result2(.failure(let e2)), .some):
n.send(error: e2)
}
}
}
/// Implementation of [Reactive X operator "Count"](http://reactivex.io/documentation/operators/count.html)
///
/// - returns: a signal that emits the number of values emitted by `self`
public func count() -> Signal<Int> {
return reduce(0) { (fold: (Int), value: T) -> Int in
return fold + 1
}
}
}
extension Signal where T: Comparable {
/// Implementation of [Reactive X operator "Min"](http://reactivex.io/documentation/operators/min.html)
///
/// - returns: the smallest value emitted by self
public func min() -> Signal<T> {
return foldAndFinalize(nil, finalize: { $0 }) { (fold: T?, value: T) -> T? in
return fold.map { value < $0 ? value : $0 } ?? value
}
}
/// Implementation of [Reactive X operator "Max"](http://reactivex.io/documentation/operators/max.html)
///
/// - returns: the largest value emitted by self
public func max() -> Signal<T> {
return foldAndFinalize(nil, finalize: { $0 }) { (fold: T?, value: T) -> T? in
return fold.map { value > $0 ? value : $0 } ?? value
}
}
}
extension Signal {
/// Implementation of [Reactive X operator "Reduce"](http://reactivex.io/documentation/operators/reduce.html)
///
/// - parameter initial: initialize the state value
/// - parameter context: the `fold` function will be invoked here
/// - parameter fold: invoked for every value emitted from self
///
/// - returns: emits the last emitted `fold` state value
public func reduce<U>(_ initial: U, context: Exec = .direct, fold: @escaping (U, T) -> U) -> Signal<U> {
return foldAndFinalize(initial, context: context, finalize: { $0 }) { (state: U, value: T) in
return fold(state, value)
}
}
}
extension Signal where T: Numeric {
/// Implementation of [Reactive X operator "Sum"](http://reactivex.io/documentation/operators/sum.html)
///
/// - returns: a signal that emits the sum of all values emitted by self
public func sum() -> Signal<T> {
return reduce(0) { (fold: T, value: T) -> T in
return fold + value
}
}
}
|
isc
|
c62384f83071f530d4f9719a38546b1d
| 47.289432 | 548 | 0.681346 | 3.490736 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Systems/ShortcutHandler.swift
|
1
|
2286
|
//
// ShortcutHandler.swift
// Freetime
//
// Created by Viktor Gardart on 2017-10-08.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import GitHubSession
import GitHawkRoutes
extension UIApplicationShortcutItem {
var params: [String: String] {
var params = [String: String]()
userInfo?.forEach {
if let value = $1 as? String {
params[$0] = value
}
}
return params
}
static func from<T: Routable>(
route: T,
localizedTitle: String,
localizedSubtitle: String? = nil,
icon: UIApplicationShortcutIcon? = nil
) -> UIApplicationShortcutItem {
return UIApplicationShortcutItem(
type: T.path,
localizedTitle: localizedTitle,
localizedSubtitle: localizedSubtitle,
icon: icon,
userInfo: route.encoded
)
}
}
struct ShortcutHandler {
static func configure(sessionUsernames: [String]) {
UIApplication.shared.shortcutItems = generateItems(sessionUsernames: sessionUsernames)
}
private static func generateItems(sessionUsernames: [String]) -> [UIApplicationShortcutItem] {
guard sessionUsernames.count > 0 else { return [] }
var items = [
UIApplicationShortcutItem.from(
route: SearchShortcutRoute(),
localizedTitle: Constants.Strings.search,
icon: UIApplicationShortcutIcon(templateImageName: "search")
),
UIApplicationShortcutItem.from(
route: BookmarkShortcutRoute(),
localizedTitle: Constants.Strings.bookmarks,
icon: UIApplicationShortcutIcon(templateImageName: "bookmark")
)
]
if sessionUsernames.count > 1 {
let username = sessionUsernames[1]
items.append(UIApplicationShortcutItem.from(
route: SwitchAccountShortcutRoute(username: username),
localizedTitle: NSLocalizedString("Switch Account", comment: ""),
localizedSubtitle: username,
icon: UIApplicationShortcutIcon(templateImageName: "organization")
))
}
return items
}
}
|
mit
|
69c700b84b22fcff6fa6817b2ffc51cc
| 28.675325 | 98 | 0.606127 | 5.573171 | false | false | false | false |
takezou621/customNavigationSample
|
customNavigationSample/UIColorExtension.swift
|
1
|
2387
|
//
// UIColorExtension.swift
// ExtensionProj
//
// Created by Takeshi Kawai on 2015/05/25.
// Copyright (c) 2015年 Takeshi Kawai. All rights reserved.
//
//
// UIColorExtension.swift
// mate001
//
// Created by KawaiTakeshi on 2015/05/18.
// Copyright (c) 2015年 Kawai Takeshi. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (count(hex)) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
println("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
|
apache-2.0
|
e1064bf538ee4165c16880a4702aab29
| 38.081967 | 109 | 0.478389 | 4.025338 | false | false | false | false |
rockbruno/swiftshield
|
Sources/SwiftShieldCore/Workspace.swift
|
1
|
742
|
import Foundation
struct Workspace: Hashable {
let workspaceFile: File
func xcodeProjFiles() throws -> [Project] {
let workspaceRoot = URL(fileURLWithPath: workspaceFile.path).deletingLastPathComponent().relativePath
let contentFile = File(path: workspaceFile.path + "/contents.xcworkspacedata")
let content = try contentFile.read()
let results = content.match(regex: "group:(.*\\.xcodeproj)")
var projects = [Project]()
for result in results {
let path = result.captureGroup(1, originalString: content)
let project = Project(xcodeProjFile: File(path: workspaceRoot + "/" + path))
projects.append(project)
}
return projects
}
}
|
gpl-3.0
|
43a6da23f5a61e8e64b093c80f9fd885
| 38.052632 | 109 | 0.649596 | 4.666667 | false | false | false | false |
adrfer/swift
|
test/attr/attr_override.swift
|
11
|
8478
|
// RUN: %target-parse-verify-swift
@override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}}
func virtualAttributeCanNotBeUsedInSource() {}
class MixedKeywordsAndAttributes {
// expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}}
override @inline(never) func f1() {}
}
class DuplicateOverrideBase {
func f1() {}
class func cf1() {}
class func cf2() {}
class func cf3() {}
class func cf4() {}
}
class DuplicateOverrideDerived : DuplicateOverrideBase {
override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
class A {
func f0() { }
func f1() { } // expected-note{{overridden declaration is here}}
var v1: Int { return 5 }
var v2: Int { return 5 } // expected-note{{overridden declaration is here}}
var v4: String { return "hello" }// expected-note{{attempt to override property here}}
var v5: A { return self }
var v6: A { return self }
var v7: A { // expected-note{{attempt to override property here}}
get { return self }
set { }
}
var v8: Int = 0 // expected-note {{attempt to override property here}}
var v9: Int { return 5 } // expected-note{{attempt to override property here}}
subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-note{{overridden declaration is here}}
get {
return "hello"
}
set {
}
}
subscript (i: Int8) -> A {
get { return self }
}
subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}}
get { return self }
set { }
}
func overriddenInExtension() {} // expected-note {{overridden declaration is here}}
}
class B : A {
override func f0() { }
func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
override func f2() { } // expected-error{{method does not override any method from its superclass}}
override var v1: Int { return 5 }
var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}
override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}}
// Covariance
override var v5: B { return self }
override var v6: B {
get { return self }
set { }
}
override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}}
get { return self }
set { }
}
// Stored properties
override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}}
override var v9: Int // expected-error{{cannot override with a stored property 'v9'}}
override subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }}
get {
return "hello"
}
set {
}
}
override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
// Covariant
override subscript (i: Int8) -> B {
get { return self }
}
override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}}
get { return self }
set { }
}
override init() { }
override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
}
extension B {
override func overriddenInExtension() {} // expected-error{{declarations in extensions cannot override yet}}
}
struct S {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
extension S {
override func ef() {} // expected-error{{method does not override any method from its superclass}}
}
enum E {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
protocol P {
override func f() // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}}
// Invalid 'override' on declarations inside closures.
var rdar16654075a = {
override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
var rdar16654075b = {
class A {
override func foo() {} // expected-error{{method does not override any method from its superclass}}
}
}
var rdar16654075c = { () -> () in
override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}}
()
}
var rdar16654075d = { () -> () in
class A {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
A().foo()
}
var rdar16654075e = { () -> () in
class A {
func foo() {}
}
class B : A {
override func foo() {}
}
A().foo()
}
class C {
init(string: String) { } // expected-note{{overridden declaration is here}}
required init(double: Double) { } // expected-note 3{{overridden required initializer is here}}
convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}}
}
class D1 : C {
override init(string: String) { super.init(string: string) }
required init(double: Double) { }
convenience init() { self.init(string: "hello") }
}
class D2 : C {
init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
// FIXME: Would like to remove the space after 'override' as well.
required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}}
override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class D3 : C {
override init(string: String) { super.init(string: string) }
override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}}
}
class D4 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required override init(string: String) { super.init(string: string) }
required init(double: Double) { }
}
class D5 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required convenience override init(string: String) { self.init(double: 5.0) }
required init(double: Double) { }
}
class D6 : C {
init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }}
}
// rdar://problem/18232867
class C_empty_tuple {
init() { }
}
class D_empty_tuple : C_empty_tuple {
override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class C_with_let {
let x = 42 // expected-note {{attempt to override property here}}
}
class D_with_let : C_with_let {
override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}}
}
|
apache-2.0
|
465b94e83e60fac05499afa1bc48b992
| 32.912 | 174 | 0.666195 | 3.853636 | false | false | false | false |
KhunLam/Swift_weibo
|
LKSwift_weibo/LKSwift_weibo/Classes/Module/Home/View/cell/LKStatusCell.swift
|
1
|
5168
|
//
// LKStatusCell.swift
// LKSwift_weibo
//
// Created by lamkhun on 15/11/3.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
let StatusCellMargin: CGFloat = 8
class LKStatusCell: UITableViewCell {
// MARK: - 属性
/// 配图宽度约束
var pictureViewWidthCon: NSLayoutConstraint?
/// 配图高度约束
var pictureViewHeightCon: NSLayoutConstraint?
// MARK: - 属性
/// 微博模型
var status: LKStatus? {
didSet {
// print("\(status?.idstr),父类监视器")
// 将模型赋值给 topView
topView.statusUser = status
// 设置微博内容
contentLabel.text = status?.text
// 将模型赋值给配图视图
pictureView.statusPicture = status
// 调用模型的计算尺寸的方法
let size = pictureView.calcViewSize()
// print("配图siez: \(size)")
// 重新设置配图的宽高约束
pictureViewWidthCon?.constant = size.width
pictureViewHeightCon?.constant = size.height
// TODO: 测试配图的高度
// let row = arc4random_uniform(1000) % 4
// pictureViewHeightCon?.constant = CGFloat(row) * 90
}
}
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
}
//MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareUI()
}
//MARK: -准备 UI
func prepareUI(){
//添加子控件
contentView.addSubview(topView)
contentView.addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottomView)
//添加约束
topView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width: UIScreen.width(), height: 53))
// 微博内容
contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil, offset: CGPoint(x: StatusCellMargin , y: StatusCellMargin))
// 设置宽度
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.width() - 2 * StatusCellMargin))
// 因为转发微博需要设置配图约束,不能再这里设置配图的约束,需要在创建一个cell继承CZStatusCell,添加上配图的约束
// // 微博配图
// let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 0, height: 0), offset: CGPoint(x: 0, y: StatusCellMargin))
//
// // 获取配图的宽高约束---赋值给属性
// pictureViewHeightCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
// pictureViewWidthCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
// 底部视图
bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.width(), height: 44), offset: CGPoint(x: -StatusCellMargin, y: StatusCellMargin))
// 添加contentView底部和contentLabel的底部重合 让内容View自动适应Label的高度
// contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
}
//MARK: -返回cell的高度
// 设置cell的模型,cell会根据模型,从新设置内容,更新约束.获取子控件的最大Y值
// 返回cell的高度
func rowHeight(status: LKStatus) -> CGFloat {
// 设置cell的模型
self.status = status
// 更新约束
layoutIfNeeded()
// 获取子控件的最大Y值
let maxY = CGRectGetMaxY(bottomView.frame)
return maxY
}
//MARK: -懒加载
lazy var topView:LKStatusTopView = LKStatusTopView()
/// 微博内容
lazy var contentLabel: UILabel = {
let label = UILabel(fonsize: 16, textColor: UIColor.blackColor())
// 显示多行
label.numberOfLines = 0
return label
}()
/// 微博配图
lazy var pictureView: LKStatusPictureView = LKStatusPictureView()
/// 底部视图
lazy var bottomView: LKStatusBottomView = LKStatusBottomView()
}
|
apache-2.0
|
e0dc705b345b98ddcdcd59568a17d738
| 30.134228 | 268 | 0.615219 | 4.548039 | false | false | false | false |
chanhx/iGithub
|
iGithub/ViewControllers/WebViewController.swift
|
2
|
7903
|
//
// WebViewController.swift
// iGithub
//
// Created by Chan Hocheung on 8/7/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
var webView = WKWebView()
var showNativeController = true
fileprivate var request: URLRequest?
fileprivate var progressView = UIProgressView(progressViewStyle: .bar)
fileprivate var toolbarWasHidden: Bool?
fileprivate var kvoContext: UInt8 = 0
fileprivate let keyPaths = ["title", "loading", "estimatedProgress"]
convenience init(address: String, userScript: WKUserScript? = nil) {
self.init(url: URL(string: address)!, userScript: userScript)
}
convenience init(url: URL, userScript: WKUserScript? = nil) {
self.init(request: URLRequest(url: url), userScript: userScript)
}
init(request: URLRequest, userScript: WKUserScript? = nil) {
super.init(nibName: nil, bundle: nil)
self.request = request
if let script = userScript {
let userContentController = WKUserContentController()
userContentController.addUserScript(script)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: CGRect.zero, configuration: configuration)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
webView.stopLoading()
webView.navigationDelegate = nil
progressView.removeFromSuperview()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
for keyPath in keyPaths {
webView.removeObserver(self, forKeyPath: keyPath)
}
}
override func viewDidLoad() {
super.viewDidLoad()
webView.allowsBackForwardNavigationGestures = true
webView.frame = view.bounds
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
self.view.addSubview(webView)
progressView.frame = CGRect(x: 0, y: 42, width: view.bounds.width, height: 2)
progressView.trackTintColor = UIColor.clear
self.navigationController?.navigationBar.addSubview(progressView)
updateToolbar()
for keyPath in keyPaths {
webView.addObserver(self, forKeyPath: keyPath, options: .new, context: &kvoContext)
}
if request != nil {
webView.load(request!)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if toolbarWasHidden == nil {
toolbarWasHidden = self.navigationController?.isToolbarHidden
}
navigationController?.isToolbarHidden = false
progressView.isHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.isToolbarHidden = toolbarWasHidden!
progressView.isHidden = true
}
func updateToolbar() {
let backItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: webView, action: #selector(WKWebView.goBack))
let forwardItem = UIBarButtonItem(image: UIImage(named: "forward"), style: .plain, target: webView, action: #selector(WKWebView.goForward))
let loadItem: UIBarButtonItem = {
if webView.isLoading {
return UIBarButtonItem(barButtonSystemItem: .stop, target: webView, action: #selector(WKWebView.stopLoading))
} else {
return UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(WKWebView.reload))
}
}()
let shareItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(WebViewController.share(_:)))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
backItem.isEnabled = webView.canGoBack
forwardItem.isEnabled = webView.canGoForward
self.setToolbarItems([flexibleSpace, backItem, flexibleSpace, forwardItem, flexibleSpace, loadItem, flexibleSpace, shareItem, flexibleSpace],
animated: false)
}
@objc func share(_ button: UIBarButtonItem) {
var items = [Any]()
if webView.title != nil {
items.append(webView.title!)
}
if request?.url != nil {
items.append(request!.url!)
}
let activityVC = UIActivityViewController(activityItems: items, applicationActivities: [ActivitySafari()])
activityVC.popoverPresentationController?.barButtonItem = button
self.navigationController?.present(activityVC, animated: true, completion: nil)
}
// MARK: KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &kvoContext {
if keyPath == "title" {
navigationItem.title = webView.title
} else if keyPath == "loading" {
updateToolbar()
UIApplication.shared.isNetworkActivityIndicatorVisible = webView.isLoading
} else if keyPath == "estimatedProgress" {
let progress = Float(webView.estimatedProgress)
let animated = progress > progressView.progress
UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseOut, animations: {
self.progressView.setProgress(progress, animated: animated)
if self.webView.estimatedProgress >= 1 {
self.progressView.alpha = 0
}
}) { _ in
self.progressView.alpha = self.webView.estimatedProgress >= 1 ? 0 : 1
}
}
}
}
}
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
guard showNativeController, let vc = URLRouter.nativeViewController(forURL: url) else {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
self.navigationController?.pushViewController(vc, animated: true)
}
}
class ActivitySafari: UIActivity {
fileprivate var url: URL!
open override var activityType : UIActivity.ActivityType? {
return UIActivity.ActivityType("me.hochueng.activity.WebViewController")
}
override var activityTitle : String? {
return "Open in Safari"
}
override var activityImage : UIImage? {
return UIImage(named: "safari")
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
for item in activityItems {
if item is URL && UIApplication.shared.canOpenURL(item as! URL) {
return true
}
}
return true
}
override func prepare(withActivityItems activityItems: [Any]) {
for item in activityItems {
if item is URL {
url = item as! URL
}
}
}
override func perform() {
let completed = UIApplication.shared.openURL(url)
activityDidFinish(completed)
}
}
|
gpl-3.0
|
96cfe05db6f902fb5054ddf53dbe2cf0
| 34.434978 | 157 | 0.615034 | 5.624199 | false | false | false | false |
KoheiHayakawa/KHAForm
|
KHAForm/KHAFormViewController.swift
|
1
|
13879
|
//
// KHAFormController.swift
// KHAForm
//
// Created by Kohei Hayakawa on 2/20/15.
// Copyright (c) 2015 Kohei Hayakawa. All rights reserved.
//
import UIKit
public protocol KHAFormViewDataSource {
func formCellsInForm(form: KHAFormViewController) -> [[KHAFormCell]]
}
public
class KHAFormViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate, KHAFormViewDataSource, KHASelectionFormViewDelegate {
private var cells = [[KHAFormCell]]()
private var datePickerIndexPath: NSIndexPath?
private var customInlineCellIndexPath: NSIndexPath?
private var lastIndexPath: NSIndexPath? // For selection form cell
// Form is always grouped tableview
convenience public init() {
self.init(style: .Grouped)
}
override public func viewDidLoad() {
super.viewDidLoad()
// init form structure
reloadForm()
}
public func reloadForm() {
cells = formCellsInForm(self)
tableView.reloadData()
}
/*! Determine form structure by using two-dimensional array.
First index determines section and second index determines row.
This method must be overridden in subclass.
*/
public func formCellsInForm(form: KHAFormViewController) -> [[KHAFormCell]] {
return cells
}
public func formCellForIndexPath(indexPath: NSIndexPath) -> KHAFormCell {
var before = false
if hasInlineDatePicker() {
before = (datePickerIndexPath?.row < indexPath.row) && (datePickerIndexPath?.section == indexPath.section)
}
else if hasInlineCustomCell() {
before = (customInlineCellIndexPath?.row < indexPath.row && customInlineCellIndexPath?.section == indexPath.section)
}
let row = (before ? indexPath.row - 1 : indexPath.row)
var cell = dequeueReusableFormCellWithType(.DatePicker)
if hasCustomCellAtIndexPath(indexPath) {
cell = cells[indexPath.section][row-1]
if let inlineCell = cell.customInlineCell where customInlineCellIndexPath == indexPath {
cell = inlineCell
}
}
else if (!hasPickerAtIndexPath(indexPath) || !hasCustomCellAtIndexPath(indexPath)) && indexPath != datePickerIndexPath {
cell = cells[indexPath.section][row]
}
return cell
}
public func dequeueReusableFormCellWithType(type: KHAFormCellType) -> KHAFormCell {
// Register the picker cell if form has a date cell and still not registered
if type == .Date && tableView.dequeueReusableCellWithIdentifier(type.cellID()) == nil {
tableView.registerClass(KHADatePickerFormCell.self, forCellReuseIdentifier: KHADatePickerFormCell.cellID)
}
// Register initialized cell if form doesn't have that cell
if let cell = tableView.dequeueReusableCellWithIdentifier(type.cellID()) as? KHAFormCell {
return cell
} else {
tableView.registerClass(type.cellClass(), forCellReuseIdentifier: type.cellID())
return tableView.dequeueReusableCellWithIdentifier(type.cellID()) as! KHAFormCell
}
}
// MARK: - UITableViewDataSource
override public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = formCellForIndexPath(indexPath)
return cell.bounds.height
}
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return cells.count
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hasInlineDatePickerAtSection(section) || hasCustomInlineCellAtSection(section) {
// we have a date picker, so allow for it in the number of rows in this section
return cells[section].count + 1
}
return cells[section].count;
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = formCellForIndexPath(indexPath)
if cell is KHATextFieldFormCell {
cell.textField.delegate = self
} else if cell is KHATextViewFormCell {
cell.textView.delegate = self
} else if cell is KHADatePickerFormCell {
let dateCell = formCellForIndexPath(NSIndexPath(forRow: indexPath.row-1, inSection: indexPath.section))
cell.datePicker.datePickerMode = dateCell.datePickerMode
cell.datePicker.minuteInterval = dateCell.datePicker.minuteInterval
cell.datePicker.addTarget(self, action: #selector(KHAFormViewController.didDatePickerValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
return cell
}
// MARK: - UITableViewDelegate
override public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! KHAFormCell
if cell is KHADateFormCell {
displayInlineDatePickerForRowAtIndexPath(indexPath)
} else if cell is KHASelectionFormCell {
lastIndexPath = indexPath
let selectionFormViewController = cell.selectionFormViewController
selectionFormViewController.delegate = self
navigationController?.pushViewController(selectionFormViewController, animated: true)
}
else if cell.customInlineCell != nil {
displayCustomInlineCellForRowAtIndexPath(indexPath)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
view.endEditing(true)
}
// MARK: - DatePicker
/*! Updates the UIDatePicker's value to match with the date of the cell above it.
*/
public func updateDatePicker() {
if let indexPath = datePickerIndexPath {
if let associatedDatePickerCell = tableView.cellForRowAtIndexPath(indexPath) {
let cell = cells[indexPath.section][indexPath.row - 1] as! KHADateFormCell
(associatedDatePickerCell as! KHADatePickerFormCell).datePicker.setDate(cell.date, animated: false)
}
}
}
private func hasInlineDatePickerAtSection(section: Int) -> Bool {
if hasInlineDatePicker() {
return datePickerIndexPath?.section == section
}
return false
}
private func hasCustomInlineCellAtSection(section: Int)-> Bool {
if hasInlineCustomCell() {
return customInlineCellIndexPath?.section == section
}
return false
}
/*! Determines if the given indexPath points to a cell that contains the UIDatePicker.
@param indexPath The indexPath to check if it represents a cell with the UIDatePicker.
*/
private func hasPickerAtIndexPath(indexPath: NSIndexPath) -> Bool {
return hasInlineDatePicker() && (datePickerIndexPath?.row == indexPath.row) && (datePickerIndexPath?.section == indexPath.section)
}
private func hasCustomCellAtIndexPath(indexPath: NSIndexPath)->Bool {
return hasInlineCustomCell() && (customInlineCellIndexPath?.row == indexPath.row) && (customInlineCellIndexPath?.section == indexPath.section)
}
/*! Determines if the UITableViewController has a UIDatePicker in any of its cells.
*/
private func hasInlineDatePicker() -> Bool {
return datePickerIndexPath != nil
}
private func hasInlineCustomCell()->Bool {
return customInlineCellIndexPath != nil
}
/*! Adds or removes a UIDatePicker cell below the given indexPath.
@param indexPath The indexPath to reveal the UIDatePicker.
*/
private func toggleDatePickerForSelectedIndexPath(indexPath: NSIndexPath) {
tableView.beginUpdates()
let indexPaths = [NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)]
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade)
tableView.endUpdates()
}
/*! Reveals the date picker inline for the given indexPath, called by "didSelectRowAtIndexPath".
@param indexPath The indexPath to reveal the UIDatePicker.
*/
private func displayInlineDatePickerForRowAtIndexPath(indexPath: NSIndexPath) {
// display the date picker inline with the table content
tableView.beginUpdates()
var before = false // indicates if the date picker is below "indexPath", help us determine which row to reveal
if hasInlineDatePicker() {
before = (datePickerIndexPath?.row < indexPath.row) && (datePickerIndexPath?.section == indexPath.section)
}
let sameCellClicked = ((datePickerIndexPath?.row == indexPath.row + 1) && (datePickerIndexPath?.section == indexPath.section))
// remove any date picker cell if it exists
if hasInlineDatePicker() {
tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: datePickerIndexPath!.row, inSection: datePickerIndexPath!.section)], withRowAnimation: .Fade)
datePickerIndexPath = nil
}
if !sameCellClicked {
// hide the old date picker and display the new one
let rowToReveal = (before ? indexPath.row - 1 : indexPath.row)
let indexPathToReveal = NSIndexPath(forRow: rowToReveal, inSection: indexPath.section)
toggleDatePickerForSelectedIndexPath(indexPathToReveal)
datePickerIndexPath = NSIndexPath(forRow: indexPathToReveal.row + 1, inSection: indexPath.section)
}
// always deselect the row containing the start or end date
tableView.deselectRowAtIndexPath(indexPath, animated:true)
tableView.endUpdates()
// inform our date picker of the current date to match the current cell
updateDatePicker()
}
private func displayCustomInlineCellForRowAtIndexPath(indexPath: NSIndexPath) {
tableView.beginUpdates()
var before = false
if hasInlineCustomCell() {
before = (customInlineCellIndexPath?.row < indexPath.row && customInlineCellIndexPath?.section == indexPath.section)
}
let sameCellClicked = ((customInlineCellIndexPath?.row == indexPath.row + 1 ) && customInlineCellIndexPath?.section == indexPath.section)
// remove any other custom cell if it exists
if let indexPath = customInlineCellIndexPath where hasInlineCustomCell() {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
customInlineCellIndexPath = nil
}
if !sameCellClicked {
// hide the old custom cell and display the new one
let rowToReveal = before ? indexPath.row-1 : indexPath.row
let indexPathToReveal = NSIndexPath(forRow: rowToReveal, inSection: indexPath.section)
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: indexPathToReveal.row+1, inSection: indexPathToReveal.section)], withRowAnimation: .Fade)
customInlineCellIndexPath = NSIndexPath(forRow: indexPathToReveal.row+1, inSection: indexPathToReveal.section)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
tableView.endUpdates()
}
private func removeAnyDatePickerCell() {
if hasInlineDatePicker() {
tableView.beginUpdates()
let indexPath = NSIndexPath(forRow: datePickerIndexPath!.row, inSection: datePickerIndexPath!.section)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
datePickerIndexPath = nil
// always deselect the row containing the start or end date
tableView.deselectRowAtIndexPath(indexPath, animated:true)
tableView.endUpdates()
// inform our date picker of the current date to match the current cell
updateDatePicker()
}
}
/*! User chose to change the date by changing the values inside the UIDatePicker.
@param sender The sender for this action: UIDatePicker.
*/
func didDatePickerValueChanged(sender: UIDatePicker) {
var targetedCellIndexPath: NSIndexPath?
if self.hasInlineDatePicker() {
// inline date picker: update the cell's date "above" the date picker cell
targetedCellIndexPath = NSIndexPath(forRow: datePickerIndexPath!.row - 1, inSection: datePickerIndexPath!.section)
} else {
// external date picker: update the current "selected" cell's date
if let selectedIndexPath = tableView.indexPathForSelectedRow {
targetedCellIndexPath = selectedIndexPath
}
}
// update the cell's date string
if let selectedIndexPath = targetedCellIndexPath {
let cell = tableView.cellForRowAtIndexPath(selectedIndexPath) as! KHADateFormCell
let targetedDatePicker = sender
cell.date = targetedDatePicker.date
}
}
// MARK: - Delegate
public func textFieldDidBeginEditing(textField: UITextField) {
removeAnyDatePickerCell()
}
public func textViewDidBeginEditing(textView: UITextView) {
removeAnyDatePickerCell()
}
func selectionFormDidChangeSelectedIndex(selectionForm: KHASelectionFormViewController) {
let cell = tableView.cellForRowAtIndexPath(lastIndexPath!) as! KHASelectionFormCell
cell.detailTextLabel?.text = selectionForm.selections[selectionForm.selectedIndex]
}
}
|
mit
|
4a450823e1f9e5589f7b46eb09e002e2
| 41.18541 | 163 | 0.668204 | 5.600888 | false | false | false | false |
WeMadeCode/ZXPageView
|
Example/Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UIImageExtensions.swift
|
1
|
9812
|
//
// UIImageExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(UIKit)
import UIKit
// MARK: - Properties
public extension UIImage {
/// SwifterSwift: Size in bytes of UIImage
var bytesSize: Int {
return jpegData(compressionQuality: 1)?.count ?? 0
}
/// SwifterSwift: Size in kilo bytes of UIImage
var kilobytesSize: Int {
return bytesSize / 1024
}
/// SwifterSwift: UIImage with .alwaysOriginal rendering mode.
var original: UIImage {
return withRenderingMode(.alwaysOriginal)
}
/// SwifterSwift: UIImage with .alwaysTemplate rendering mode.
var template: UIImage {
return withRenderingMode(.alwaysTemplate)
}
}
// MARK: - Methods
public extension UIImage {
/// SwifterSwift: Compressed UIImage from original UIImage.
///
/// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5).
/// - Returns: optional UIImage (if applicable).
func compressed(quality: CGFloat = 0.5) -> UIImage? {
guard let data = compressedData(quality: quality) else { return nil }
return UIImage(data: data)
}
/// SwifterSwift: Compressed UIImage data from original UIImage.
///
/// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5).
/// - Returns: optional Data (if applicable).
func compressedData(quality: CGFloat = 0.5) -> Data? {
return jpegData(compressionQuality: quality)
}
/// SwifterSwift: UIImage Cropped to CGRect.
///
/// - Parameter rect: CGRect to crop UIImage to.
/// - Returns: cropped UIImage
func cropped(to rect: CGRect) -> UIImage {
guard rect.size.width < size.width && rect.size.height < size.height else { return self }
guard let image: CGImage = cgImage?.cropping(to: rect) else { return self }
return UIImage(cgImage: image)
}
/// SwifterSwift: UIImage scaled to height with respect to aspect ratio.
///
/// - Parameters:
/// - toHeight: new height.
/// - opaque: flag indicating whether the bitmap is opaque.
/// - Returns: optional scaled UIImage (if applicable).
func scaled(toHeight: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toHeight / size.height
let newWidth = size.width * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, 0)
draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage scaled to width with respect to aspect ratio.
///
/// - Parameters:
/// - toWidth: new width.
/// - opaque: flag indicating whether the bitmap is opaque.
/// - Returns: optional scaled UIImage (if applicable).
func scaled(toWidth: CGFloat, opaque: Bool = false) -> UIImage? {
let scale = toWidth / size.width
let newHeight = size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, 0)
draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: Creates a copy of the receiver rotated by the given angle.
///
/// // Rotate the image by 180°
/// image.rotated(by: Measurement(value: 180, unit: .degrees))
///
/// - Parameter angle: The angle measurement by which to rotate the image.
/// - Returns: A new image rotated by the given angle.
@available(iOS 10.0, tvOS 10.0, watchOS 3.0, *)
func rotated(by angle: Measurement<UnitAngle>) -> UIImage? {
let radians = CGFloat(angle.converted(to: .radians).value)
let destRect = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: radians))
let roundedDestRect = CGRect(x: destRect.origin.x.rounded(),
y: destRect.origin.y.rounded(),
width: destRect.width.rounded(),
height: destRect.height.rounded())
UIGraphicsBeginImageContext(roundedDestRect.size)
guard let contextRef = UIGraphicsGetCurrentContext() else { return nil }
contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2)
contextRef.rotate(by: radians)
draw(in: CGRect(origin: CGPoint(x: -size.width / 2,
y: -size.height / 2),
size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: Creates a copy of the receiver rotated by the given angle (in radians).
///
/// // Rotate the image by 180°
/// image.rotated(by: .pi)
///
/// - Parameter radians: The angle, in radians, by which to rotate the image.
/// - Returns: A new image rotated by the given angle.
func rotated(by radians: CGFloat) -> UIImage? {
let destRect = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: radians))
let roundedDestRect = CGRect(x: destRect.origin.x.rounded(),
y: destRect.origin.y.rounded(),
width: destRect.width.rounded(),
height: destRect.height.rounded())
UIGraphicsBeginImageContext(roundedDestRect.size)
guard let contextRef = UIGraphicsGetCurrentContext() else { return nil }
contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2)
contextRef.rotate(by: radians)
draw(in: CGRect(origin: CGPoint(x: -size.width / 2,
y: -size.height / 2),
size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage filled with color
///
/// - Parameter color: color to fill image with.
/// - Returns: UIImage filled with given color.
func filled(withColor color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let mask = cgImage else { return self }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// SwifterSwift: UIImage tinted with color
///
/// - Parameters:
/// - color: color to tint image with.
/// - blendMode: how to blend the tint
/// - Returns: UIImage tinted with given color.
func tint(_ color: UIColor, blendMode: CGBlendMode) -> UIImage {
let drawRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
color.setFill()
context?.fill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: 1.0)
return UIGraphicsGetImageFromCurrentImageContext()!
}
/// SwifterSwift: UIImage with rounded corners
///
/// - Parameters:
/// - radius: corner radius (optional), resulting image will be round if unspecified
/// - Returns: UIImage with all corners rounded
func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
let maxRadius = min(size.width, size.height) / 2
let cornerRadius: CGFloat
if let radius = radius, radius > 0 && radius <= maxRadius {
cornerRadius = radius
} else {
cornerRadius = maxRadius
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(origin: .zero, size: size)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
// MARK: - Initializers
public extension UIImage {
/// SwifterSwift: Create UIImage from color and size.
///
/// - Parameters:
/// - color: image fill color.
/// - size: image size.
convenience init(color: UIColor, size: CGSize) {
UIGraphicsBeginImageContextWithOptions(size, false, 1)
defer {
UIGraphicsEndImageContext()
}
color.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
guard let aCgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
self.init()
return
}
self.init(cgImage: aCgImage)
}
}
#endif
|
mit
|
eab02d8afbee465d1cc26f27782e54c7
| 36.872587 | 266 | 0.627587 | 4.770914 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Services/JetpackBackupService.swift
|
2
|
1627
|
import Foundation
class JetpackBackupService {
private let managedObjectContext: NSManagedObjectContext
private lazy var service: JetpackBackupServiceRemote = {
let api = WordPressComRestApi.defaultApi(in: managedObjectContext,
localeKey: WordPressComRestApi.LocaleKeyV2)
return JetpackBackupServiceRemote(wordPressComRestApi: api)
}()
init(managedObjectContext: NSManagedObjectContext) {
self.managedObjectContext = managedObjectContext
}
func prepareBackup(for site: JetpackSiteRef,
rewindID: String? = nil,
restoreTypes: JetpackRestoreTypes? = nil,
success: @escaping (JetpackBackup) -> Void,
failure: @escaping (Error) -> Void) {
service.prepareBackup(site.siteID, rewindID: rewindID, types: restoreTypes, success: success, failure: failure)
}
func getBackupStatus(for site: JetpackSiteRef, downloadID: Int, success: @escaping (JetpackBackup) -> Void, failure: @escaping (Error) -> Void) {
service.getBackupStatus(site.siteID, downloadID: downloadID, success: success, failure: failure)
}
func getAllBackupStatus(for site: JetpackSiteRef, success: @escaping ([JetpackBackup]) -> Void, failure: @escaping (Error) -> Void) {
service.getAllBackupStatus(site.siteID, success: success, failure: failure)
}
func dismissBackupNotice(site: JetpackSiteRef, downloadID: Int) {
service.markAsDismissed(site.siteID, downloadID: downloadID, success: {}, failure: { _ in })
}
}
|
gpl-2.0
|
fdbbd4a50a58302f5fdd0f27b35ebd2e
| 41.815789 | 149 | 0.66933 | 5.068536 | false | false | false | false |
xdliu002/TAC_communication
|
iOS Animation/Demo2Finish/Demo2/ViewController.swift
|
1
|
8236
|
//
// ViewController.swift
// Demo
//
// Created by LRui on 16/4/18.
// Copyright © 2016年 lirui. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var background: UIImageView!
var welcome: UILabel!
var username: UITextField!
var password: UITextField!
var signin: UIButton!
var signinDisabled = false
var alert: UIView!
var alertLabel: UILabel!
var alertButton: UIButton!
var shadow: CALayer!
/* View Function */
override func viewDidLoad() {
super.viewDidLoad()
background = UIImageView(image: UIImage(named: "1.png"))
background.bounds = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(background)
welcome = UILabel()
welcome.text = "Welcome"
welcome.font = UIFont.systemFontOfSize(40)
welcome.textColor = UIColor.whiteColor()
welcome.bounds = CGRect(x: 0, y: 0, width: 200, height: 40)
welcome.textAlignment = .Center
self.view.addSubview(welcome)
username = UITextField()
username.delegate = self
username.font = UIFont.systemFontOfSize(20)
username.placeholder = "Username"
username.setValue(UIColor.whiteColor(), forKeyPath: "_placeholderLabel.textColor")
username.bounds = CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 40)
username.layer.cornerRadius = 20
username.layer.borderColor = UIColor.whiteColor().CGColor
username.layer.borderWidth = 2
username.textAlignment = .Center
username.textColor = UIColor.whiteColor()
self.view.addSubview(username)
password = UITextField()
password.delegate = self
password.font = UIFont.systemFontOfSize(20)
password.placeholder = "Username"
password.setValue(UIColor.whiteColor(), forKeyPath: "_placeholderLabel.textColor")
password.bounds = CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 40)
password.layer.cornerRadius = 20
password.layer.borderColor = UIColor.whiteColor().CGColor
password.layer.borderWidth = 2
password.textAlignment = .Center
password.textColor = UIColor.whiteColor()
self.view.addSubview(password)
signin = UIButton()
signin.titleLabel?.font = UIFont.systemFontOfSize(20)
signin.setTitle("SignIn", forState: .Normal)
signin.setTitleColor(UIColor.whiteColor(), forState: .Normal)
signin.bounds = CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 40)
signin.layer.cornerRadius = 20
signin.backgroundColor = UIColor ( red: 0.1956, green: 0.5155, blue: 1.0, alpha: 1.0 )
signin.addTarget(self, action: #selector(ViewController.login(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(signin)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
background.center.x = self.view.center.x
background.center.y = self.view.center.y
welcome.center = CGPoint(x: self.view.center.x, y: -80)
username.center.x = self.view.center.x - self.view.frame.width
username.center.y = welcome.center.y + 390
password.center.x = self.view.center.x - self.view.frame.width
password.center.y = username.center.y + 50
signin.center.x = self.view.center.x
signin.center.y = password.center.y + 130
signin.alpha = 0
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(2, delay: 0, options: .CurveEaseIn, animations: {
let scale = CGAffineTransformMakeScale(1.05, 1.05)
self.background.transform = scale
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0, options: .CurveEaseInOut, animations: {
self.welcome.center.y += 270
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0, options: .CurveEaseInOut, animations: {
self.username.center.x += self.view.frame.width
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.5, options: .CurveEaseInOut, animations: {
self.password.center.x += self.view.frame.width
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.5, options: .CurveEaseInOut, animations: {
self.signin.center.y -= 40
self.signin.alpha = 1
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
username.resignFirstResponder()
password.resignFirstResponder()
}
/* TextField Delegate */
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func login(sender: UIButton) {
if !signinDisabled {
shadow = CALayer()
shadow.bounds = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
shadow.position = self.view.center
shadow.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 ).CGColor
self.view.layer.addSublayer(shadow)
alert = UIView()
alert.bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
alert.center = self.view.center
alert.layer.cornerRadius = 10
alert.layer.backgroundColor = UIColor ( red: 1.0, green: 0.9954, blue: 0.5578, alpha: 1.0 ).CGColor
let scale1 = CGAffineTransformMakeScale(0.01, 0.01)
alert.transform = scale1
self.view.addSubview(alert)
alertLabel = UILabel()
alertLabel.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
alertLabel.font = UIFont.systemFontOfSize(30)
alertLabel.text = "Wrong!"
alertLabel.textColor = UIColor ( red: 0.3029, green: 0.4674, blue: 1.0, alpha: 1.0 )
alertLabel.textAlignment = .Center
alertLabel.center.x = alert.bounds.width / 2
alertLabel.center.y = alert.bounds.height / 2 - 40
alert.addSubview(alertLabel)
alertButton = UIButton()
alertButton.bounds = CGRect(x: 0, y: 0, width: 200, height: 50)
alertButton.backgroundColor = UIColor ( red: 0.644, green: 1.0, blue: 0.4997, alpha: 1.0 )
alertButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
alertButton.setTitle("OK", forState: .Normal)
alertButton.center.x = alert.bounds.width / 2
alertButton.center.y = alert.bounds.height / 2 + 75
alertButton.layer.cornerRadius = 10
alertButton.addTarget(self, action: #selector(ViewController.ok(_:)), forControlEvents: .TouchUpInside)
alert.addSubview(alertButton)
UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: .AllowUserInteraction, animations: {
let scale2 = CGAffineTransformMakeScale(1, 1)
self.alert.transform = scale2
}, completion: nil)
}
signinDisabled = !signinDisabled
}
func ok(sender: UIButton) {
UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: .AllowUserInteraction, animations: {
let scale = CGAffineTransformMakeScale(0.01, 0.01)
self.alert.transform = scale
self.shadow.opacity = 0
}) { (true) in
self.shadow.removeFromSuperlayer()
self.alert.removeFromSuperview()
}
signinDisabled = !signinDisabled
}
}
|
mit
|
da2877dea29c3d3d180134aaafd65a0d
| 40.371859 | 153 | 0.60877 | 4.49645 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Rules/Idiomatic/ExplicitACLRule.swift
|
1
|
7601
|
import Foundation
import SourceKittenFramework
private typealias SourceKittenElement = SourceKittenDictionary
struct ExplicitACLRule: OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "explicit_acl",
name: "Explicit ACL",
description: "All declarations should specify Access Control Level keywords explicitly.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("internal enum A {}\n"),
Example("public final class B {}\n"),
Example("private struct C {}\n"),
Example("internal enum A {\n internal enum B {}\n}"),
Example("internal final class Foo {}"),
Example("""
internal
class Foo {
private let bar = 5
}
"""),
Example("internal func a() { let a = }\n"),
Example("private func a() { func innerFunction() { } }"),
Example("private enum Foo { enum Bar { } }"),
Example("private struct C { let d = 5 }"),
Example("""
internal protocol A {
func b()
}
"""),
Example("""
internal protocol A {
var b: Int
}
"""),
Example("internal class A { deinit {} }"),
Example("extension A: Equatable {}"),
Example("extension A {}"),
Example("""
extension Foo {
internal func bar() {}
}
"""),
Example("""
internal enum Foo {
case bar
}
"""),
Example("""
extension Foo {
public var isValid: Bool {
let result = true
return result
}
}
"""),
Example("""
extension Foo {
private var isValid: Bool {
get {
return true
}
set(newValue) {
print(newValue)
}
}
}
""")
],
triggeringExamples: [
Example("↓enum A {}\n"),
Example("final ↓class B {}\n"),
Example("internal struct C { ↓let d = 5 }\n"),
Example("public struct C { ↓let d = 5 }\n"),
Example("func a() {}\n"),
Example("internal let a = 0\n↓func b() {}\n"),
Example("""
extension Foo {
↓func bar() {}
}
""")
]
)
private func findAllExplicitInternalTokens(in file: SwiftLintFile) -> [ByteRange] {
let contents = file.stringView
return file.match(pattern: "internal", with: [.attributeBuiltin]).compactMap {
contents.NSRangeToByteRange(start: $0.location, length: $0.length)
}
}
private func offsetOfElements(from elements: [SourceKittenElement], in file: SwiftLintFile,
thatAreNotInRanges ranges: [ByteRange]) -> [ByteCount] {
return elements.compactMap { element in
guard let typeOffset = element.offset else {
return nil
}
guard let kind = element.declarationKind,
!SwiftDeclarationKind.extensionKinds.contains(kind) else {
return nil
}
// find the last "internal" token before the type
guard let previousInternalByteRange = lastInternalByteRange(before: typeOffset, in: ranges) else {
return typeOffset
}
// the "internal" token correspond to the type if there're only
// attributeBuiltin (`final` for example) tokens between them
let length = typeOffset - previousInternalByteRange.location
let range = ByteRange(location: previousInternalByteRange.location, length: length)
let internalDoesntBelongToType = Set(file.syntaxMap.kinds(inByteRange: range)) != [.attributeBuiltin]
return internalDoesntBelongToType ? typeOffset : nil
}
}
func validate(file: SwiftLintFile) -> [StyleViolation] {
let implicitAndExplicitInternalElements = internalTypeElements(in: file.structureDictionary)
guard implicitAndExplicitInternalElements.isNotEmpty else {
return []
}
let explicitInternalRanges = findAllExplicitInternalTokens(in: file)
let violations = offsetOfElements(from: implicitAndExplicitInternalElements, in: file,
thatAreNotInRanges: explicitInternalRanges)
return violations.map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}
private func lastInternalByteRange(before typeOffset: ByteCount, in ranges: [ByteRange]) -> ByteRange? {
let firstPartition = ranges.prefix(while: { typeOffset > $0.location })
return firstPartition.last
}
private func internalTypeElements(in parent: SourceKittenElement) -> [SourceKittenElement] {
return parent.substructure.flatMap { element -> [SourceKittenElement] in
guard let elementKind = element.declarationKind,
elementKind != .varLocal, elementKind != .varParameter else {
return []
}
let isDeinit = elementKind == .functionMethodInstance && element.name == "deinit"
guard !isDeinit else {
return []
}
let isPrivate = element.accessibility?.isPrivate ?? false
let internalTypeElementsInSubstructure = elementKind.childsAreExemptFromACL || isPrivate ? [] :
internalTypeElements(in: element)
var isInExtension = false
if let kind = parent.declarationKind {
isInExtension = SwiftDeclarationKind.extensionKinds.contains(kind)
}
if element.accessibility == .internal || (element.accessibility == nil && isInExtension) {
return internalTypeElementsInSubstructure + [element]
}
return internalTypeElementsInSubstructure
}
}
}
private extension SwiftDeclarationKind {
var childsAreExemptFromACL: Bool {
switch self {
case .associatedtype, .enumcase, .enumelement, .functionAccessorAddress,
.functionAccessorDidset, .functionAccessorGetter, .functionAccessorMutableaddress,
.functionAccessorSetter, .functionAccessorWillset, .genericTypeParam, .module,
.precedenceGroup, .varLocal, .varParameter, .varClass,
.varGlobal, .varInstance, .varStatic, .typealias, .functionAccessorModify, .functionAccessorRead,
.functionConstructor, .functionDestructor, .functionFree, .functionMethodClass,
.functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix,
.functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .protocol, .opaqueType:
return true
case .class, .enum, .extension, .extensionClass, .extensionEnum,
.extensionProtocol, .extensionStruct, .struct:
return false
}
}
}
|
mit
|
142a733faac3e5bf34136b3076dc5c43
| 37.719388 | 113 | 0.560812 | 5.531341 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk
|
Source/Internal/CryptoSwift/UInt32+Extension.swift
|
1
|
1905
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications,
// and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif
protocol _UInt32Type {}
extension UInt32: _UInt32Type {}
/** array of bytes */
extension UInt32 {
@_specialize(where T == ArraySlice<UInt8>)
init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int {
self = UInt32(bytes: bytes, fromIndex: bytes.startIndex)
}
@_specialize(where T == ArraySlice<UInt8>)
init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int {
if bytes.isEmpty {
self = 0
return
}
let count = bytes.count
let val0 = !bytes.isEmpty ? UInt32(bytes[index.advanced(by: 0)]) << 24 : 0
let val1 = count > 1 ? UInt32(bytes[index.advanced(by: 1)]) << 16 : 0
let val2 = count > 2 ? UInt32(bytes[index.advanced(by: 2)]) << 8 : 0
let val3 = count > 3 ? UInt32(bytes[index.advanced(by: 3)]) : 0
self = val0 | val1 | val2 | val3
}
}
|
mit
|
f97631704c4cdb793a65cc9304c2c7c7
| 37.08 | 124 | 0.672794 | 3.83871 | false | false | false | false |
chromatic-seashell/weibo
|
新浪微博/新浪微博/classes/home/GDWStatus.swift
|
1
|
1676
|
//
// GDWStatus.swift
// 新浪微博
//
// Created by apple on 15/11/15.
// Copyright © 2015年 apple. All rights reserved.
//
import UIKit
class GDWStatus: NSObject {
/// 当前这条微博的发布时间
var created_at: String?
/// 来源
var source: String?
/// 字符串型的微博ID
var idstr: String?
/// 微博信息内容
var text: String?
/// 当前微博对应的用户
var user: GDWUser?
/// 存储所有配图字典
var pic_urls: [[String: AnyObject]]?
/// 转发微博
var retweeted_status: GDWStatus?
init(dict: [String: AnyObject])
{
super.init()
setValuesForKeysWithDictionary(dict)
}
// KVC的setValuesForKeysWithDictionary方法内部会调用下面这个方法
override func setValue(value: AnyObject?, forKey key: String) {
// 1.判断是否是用户
if key == "user"
{
user = GDWUser(dict: value as! [String: AnyObject])
return // 注意: 如果自己处理了, 那么就不需要父类处理了, 所以一定要写上return
}
// 2.判断是否是转发微博
if key == "retweeted_status"
{
retweeted_status = GDWStatus(dict: value as! [String: AnyObject])
return
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let property = ["created_at", "source", "idstr", "text"]
let dict = dictionaryWithValuesForKeys(property)
return "\(dict)"
}
}
|
apache-2.0
|
a88e1cc831ee3d50238f6ec26f3da586
| 21.765625 | 77 | 0.566232 | 3.927224 | false | false | false | false |
gongmingqm10/SwiftTraining
|
Calculator/Calculator/CalculateMgr.swift
|
1
|
3167
|
//
// CalculateMgr.swift
// Calculator
//
// Created by Ming Gong on 6/12/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import Foundation
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
func count() -> Int {
return items.count
}
func lastElement() -> T {
return items.last!
}
func isEmpty() -> Bool {
return items.isEmpty
}
}
class CalculateMgr: NSObject {
let OPERATOR_PLUS = "+"
let OPERATOR_MINUS = "-"
let OPERATOR_MULTI = "*"
let OPERATOR_DIVIDE = "/"
var numberStack = Stack<Float>()
var operatorStack = Stack<String>()
var isOperator = false
func clear() {
isOperator = false
numberStack = Stack<Float>()
operatorStack = Stack<String>()
}
func pushOperator(item: String) -> Float {
if isOperator {
operatorStack.pop()
}
var result: Float = numberStack.isEmpty() ? 0 : numberStack.lastElement()
if !(operatorStack.isEmpty() || isHigherPriority(item, operatorCompared: operatorStack.lastElement())) {
result = calculateResult()
numberStack.push(result)
}
operatorStack.push(item)
isOperator = true
return result
}
func pushNumber(number: Float) {
isOperator = false
numberStack.push(number)
}
func calculateResult() -> Float {
if numberStack.count() == 1 {
return numberStack.pop()
}
let firstNumber = numberStack.pop()
let secondNumber = numberStack.pop()
let currentOperator = operatorStack.pop()
if !operatorStack.isEmpty() && isHigherPriority(operatorStack.lastElement(), operatorCompared: currentOperator) {
let thirdNumber = numberStack.pop()
let result = expressionCalculate(thirdNumber, rightNumber: secondNumber, operatorStr: operatorStack.pop())
numberStack.push(result)
numberStack.push(firstNumber)
operatorStack.push(currentOperator)
} else {
let result = expressionCalculate(secondNumber, rightNumber: firstNumber, operatorStr: currentOperator)
numberStack.push(result)
}
return calculateResult()
}
private func isHigherPriority(operatorStr: String, operatorCompared: String) -> Bool {
return (operatorStr == OPERATOR_MULTI || operatorStr == OPERATOR_DIVIDE) && (operatorCompared == OPERATOR_PLUS || operatorCompared == OPERATOR_MINUS)
}
private func expressionCalculate(leftNumber: Float, rightNumber: Float, operatorStr: String) -> Float {
switch operatorStr {
case OPERATOR_MINUS:
return leftNumber - rightNumber
case OPERATOR_MULTI:
return leftNumber * rightNumber
case OPERATOR_DIVIDE:
return leftNumber / rightNumber
default:
return leftNumber + rightNumber
}
}
}
|
mit
|
cac1ffc19919cd582e1efdf7d239f752
| 27.790909 | 157 | 0.598231 | 4.581766 | false | false | false | false |
BrunoMazzo/CocoaHeadsApp
|
CocoaHeadsApp/Classes/SettingsViewController.swift
|
3
|
1015
|
import UIKit
@IBDesignable
class SettingsViewController: UIViewController {
weak var nibView :SettingsView!
let delegate: SettingsViewModelDelegate
init(delegate: SettingsViewModelDelegate) {
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
self.title = "Settings"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
if let selectedRow = self.nibView?.tableView.indexPathForSelectedRow {
self.nibView?.tableView.deselectRowAtIndexPath(selectedRow, animated: animated)
}
}
override func loadView() {
let viewModel = SettingsViewModel(delegate: self.delegate)
let view = SettingsView(viewModel: viewModel)
self.view = view
self.nibView = view
}
}
|
mit
|
23041d02154d1a3ea1b93677e02a685b
| 25.025641 | 91 | 0.630542 | 5.314136 | false | false | false | false |
mindbody/Conduit
|
Sources/Conduit/Auth/TokenStorage/TokenMigrator.swift
|
1
|
2903
|
//
// TokenMigrator.swift
// Conduit
//
// Created by Eneko Alonso on 2/20/19.
// Copyright © 2019 MINDBODY. All rights reserved.
//
import Foundation
/// Migrate tokens from source to destination
///
/// This migrator is useful to move tokens from one store to another (eg. Keychain to UserDefaults).
/// Another use case can be move tokens from one configuration to another (eg. Auth v1 to Auth v2).
///
/// - `source` and `destination` can have different `store` or the same.
/// - `source` and `destination` can have different `configuration` or the same.
///
/// - warning: If both `store` and `configuration` are the same for `source` and `destination`,
/// all stored tokens will be lost. This is a limitation from `OAuth2TokenStore` not
/// conforming to `Equatable`.
public struct TokenMigrator {
public let source: Configuration
public let destination: Configuration
/// Migrate tokens from `source` to `destinatiion`
/// - Parameters:
/// - source: Source configuration
/// - destination: Destination configuration
public init(source: Configuration, destination: Configuration) {
self.source = source
self.destination = destination
}
/// Migrate stored tokens for all authorization levels and types
public func migrateAllTokens() {
let allAuthorizations = [
OAuth2Authorization(type: .basic, level: .client),
OAuth2Authorization(type: .bearer, level: .client),
OAuth2Authorization(type: .basic, level: .user),
OAuth2Authorization(type: .bearer, level: .user)
]
allAuthorizations.forEach(migrateToken)
}
/// Migrate stored token for a give authorization level and type
/// - Parameter authorization: OAuth2 authorization
public func migrateToken(for authorization: OAuth2Authorization) {
if let token: BearerToken = source.tokenStore.tokenFor(client: source.clientConfiguration, authorization: authorization) {
destination.tokenStore.store(token: token, for: destination.clientConfiguration, with: authorization)
}
source.tokenStore.removeTokenFor(client: source.clientConfiguration, authorization: authorization)
}
}
// MARK: - Migration Configuration
extension TokenMigrator {
public struct Configuration {
public let tokenStore: OAuth2TokenStore
public let clientConfiguration: OAuth2ClientConfiguration
/// Migration configuration for a token store and OAuth2 client configuration
/// - Parameters:
/// - tokenStore: OAuth2 token store
/// - clientConfiguration: OAuth2 client configuration
public init(tokenStore: OAuth2TokenStore, clientConfiguration: OAuth2ClientConfiguration) {
self.tokenStore = tokenStore
self.clientConfiguration = clientConfiguration
}
}
}
|
apache-2.0
|
045baaca035724f3800e92a8c99a771a
| 38.753425 | 130 | 0.690903 | 4.820598 | false | true | false | false |
gregttn/GTToast
|
Example/GTToast/ViewController.swift
|
1
|
4426
|
//
// ViewController.swift
// GTToast
//
// Created by gregttn on 10/03/2015.
// Copyright (c) 2015 gregttn. All rights reserved.
//
import UIKit
import GTToast
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
fileprivate let animations = ["Alpha", "Scale", "Bottom Slide In", "Left Slide In", "Right Slide In", "Left to Right", "Right to Left"]
fileprivate var toast: GTToastView!
@IBOutlet weak var showButton: UIButton!
@IBOutlet weak var animationPicker: UIPickerView!
@IBOutlet weak var showImageSwitch: UISwitch!
@IBOutlet weak var textAlignment: UISegmentedControl!
@IBOutlet weak var imageAlignment: UISegmentedControl!
@IBOutlet weak var imgMarginTop: UITextField!
@IBOutlet weak var imgMarginLeft: UITextField!
@IBOutlet weak var imgMarginBottom: UITextField!
@IBOutlet weak var imgMarginRight: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
updateImageAlignmentDisplayed(GTToastAlignment.left)
}
@IBAction func showToast(_ sender: AnyObject) {
let selectedAnimation = animationPicker.selectedRow(inComponent: 0)
let config = GTToastConfig(
textAlignment: NSTextAlignment(rawValue: textAlignment.selectedSegmentIndex)!,
animation: GTToastAnimation(rawValue: selectedAnimation)!.animations(),
displayInterval: 4,
imageMargins: selectedMargins(),
imageAlignment: GTToastAlignment(rawValue: imageAlignment.selectedSegmentIndex)!
)
let image: UIImage? = showImageSwitch.isOn ? UIImage(named: "tick") : .none
toast = GTToast.create("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eleifend maximus malesuada. Quisque congue augue vel mauris molestie, nec egestas eros ultrices.",
config: config,
image: image)
toast.show()
}
@IBAction func hideToast(_ sender: AnyObject) {
if let toast = toast , toast.displayed {
toast.dismiss()
}
}
fileprivate func selectedMargins() -> UIEdgeInsets {
return UIEdgeInsets(
top: textFieldValueToCGFloat(imgMarginTop),
left: textFieldValueToCGFloat(imgMarginLeft),
bottom: textFieldValueToCGFloat(imgMarginBottom),
right: textFieldValueToCGFloat(imgMarginRight))
}
fileprivate func textFieldValueToCGFloat(_ textField: UITextField) -> CGFloat {
guard let value = textField.text, let number = NumberFormatter().number(from: value) else {
return 0
}
return CGFloat(number)
}
@IBAction func imageAlignmentSelected(_ sender: AnyObject) {
updateImageAlignmentDisplayed(GTToastAlignment(rawValue: imageAlignment.selectedSegmentIndex)!)
}
@IBAction func switchDefaultImageMargins(_ sender: AnyObject) {
let control = sender as! UISwitch
enableImageMarginTextFields(!control.isOn)
updateImageAlignmentDisplayed(GTToastAlignment(rawValue: imageAlignment.selectedSegmentIndex)!)
}
fileprivate func enableImageMarginTextFields(_ enabled: Bool) {
imgMarginTop.isEnabled = enabled
imgMarginLeft.isEnabled = enabled
imgMarginBottom.isEnabled = enabled
imgMarginRight.isEnabled = enabled
}
fileprivate func updateImageAlignmentDisplayed(_ alignment: GTToastAlignment) {
let insets = alignment.defaultInsets()
imgMarginTop.text = String(describing: insets.top)
imgMarginLeft.text = String(describing: insets.left)
imgMarginBottom.text = String(describing: insets.bottom)
imgMarginRight.text = String(describing: insets.right)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return animations.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return animations[row]
}
}
|
mit
|
c68049d1b94bb62d26a23108a65afbb9
| 36.193277 | 193 | 0.676457 | 5.225502 | false | false | false | false |
nthegedus/NHPageView
|
Classes/NHPageView/NHPageView.swift
|
1
|
12935
|
//
// NHPageView.swift
// NHPageView
//
// Created by Nathan Hegedus on 4/2/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
enum Alignment {
case Right
case Center
case Left
}
@objc protocol PageViewDelegate {
func pageViewItemSize(pageView: NHPageView) -> CGSize
func pageViewDidScroll(pageView: NHPageView) -> Void
func pageViewCurrentItemIndexDidChange(pageView: NHPageView) -> Void
func pageViewWillBeginDragging(pageView: NHPageView) -> Void
func pageViewDidEndDragging(pageView: NHPageView, willDecelerate decelarete:Bool) -> Void
func pageViewWillBeginDecelarating(pageView: NHPageView) -> Void
func pageViewDidEndDecelerating(pageView: NHPageView) -> Void
func pageViewDidEndScrollingAnimation(pageView: NHPageView) -> Void
func pageView(pageView: NHPageView, shouldSelectItemAtIndex index: NSInteger) -> Bool
func pageView(pageView: NHPageView, didSelectItemAtIndex index: NSInteger) -> Void
}
class NHPageView: UIView, UIScrollViewDelegate, UIGestureRecognizerDelegate {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: - Public Properties
var delegate: PageViewDelegate?
var scrollEnabled: Bool = true
var pagingEnabled: Bool = true
var delaysContentTouches: Bool = true
var bounces: Bool = true
var itemsPerPage: Int = 1;
var truncateFinalPage: Bool = false
var defersItemViewLoading: Bool = false
var vertical: Bool = false
var decelerationRate: CGFloat?
var scrollOffset: CGFloat?
var currentIndexItem: Int = 0
var numberOfItems: Int?
var itemSize: CGSize?
var itemsQueueArray: NSMutableArray = NSMutableArray()
var alignment: Alignment = .Center
var distanceBetweenViews: CGFloat = 20
// MARK: - Private Properties
private var scrollView: UIScrollView!
private var itensViewDict: NSMutableDictionary!
private var previousIndexItem: Int!
private var previousContentOffset: CGPoint!
// MARK: - Public Methods
func insertSubviews(viewsArray: Array<UIView>) {
self.configureView()
for view in self.scrollView.subviews {
view.removeFromSuperview()
}
self.itensViewDict = NSMutableDictionary()
self.numberOfItems = viewsArray.count
for var i = 0; i < self.numberOfItems; i++ {
var view: UIView = viewsArray[i]
view.tag = i
switch self.alignment {
case .Right:
view.frame.origin.x = (CGFloat(i)*self.distanceBetweenViews) + view.frame.size.width*CGFloat(i) + self.distanceBetweenViews
break
case .Center:
view.frame.origin.x = (scrollView.frame.size.width/2) + (view.frame.size.width/2)
view.frame.origin.x = self.getCenterPoint(view).x + (CGFloat(i)*self.distanceBetweenViews) + view.frame.size.width*CGFloat(i)
break
case .Left:
view.frame.origin.x = self.scrollView.frame.size.width + view.frame.size.width + self.distanceBetweenViews
view.frame.origin.x = self.getLeftCenter(view).x + (CGFloat(i)*self.distanceBetweenViews) + view.frame.size.width*CGFloat(i)
break
}
self.itemsQueueArray.addObject(view)
self.scrollView.addSubview(view)
self.scrollView.contentSize = CGSizeMake(view.frame.origin.x + (view.frame.size.width * 2), self.scrollView.contentSize.height)
}
self.itemSize = self.itemsQueueArray.firstObject!.frame.size
scrollToView(self.itemsQueueArray.firstObject as UIView)
}
func scrollToView(view: UIView) {
switch self.alignment {
case .Right:
self.scrollToRightViewContentOffSetWithView(view)
break
case .Center:
self.scrollToCenterViewContentOffSetWithView(view)
break
case .Left:
self.scrollToLeftViewContentOffSetWithView(view)
break
}
}
// MARK: - Private Methods
private func configureView() {
self.scrollView = UIScrollView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
self.scrollView.backgroundColor = UIColor.clearColor()
self.scrollView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
self.scrollView.autoresizesSubviews = true
self.scrollView.delegate = self
self.scrollView.delaysContentTouches = self.delaysContentTouches
self.scrollView.bounces = self.bounces
self.scrollView.alwaysBounceHorizontal = !self.vertical && self.bounces
self.scrollView.alwaysBounceVertical = self.vertical && self.bounces
self.scrollView.pagingEnabled = self.pagingEnabled
self.scrollView.scrollEnabled = self.scrollEnabled
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.scrollsToTop = false
self.scrollView.clipsToBounds = false
self.scrollView.pagingEnabled = false
self.decelerationRate = self.scrollView.decelerationRate
self.itensViewDict = NSMutableDictionary()
self.previousIndexItem = 0
self.previousContentOffset = self.scrollView.contentOffset
self.scrollOffset = 0.0
self.currentIndexItem = 0
self.numberOfItems = 0
var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("didTap:"))
tapGesture.delegate = self
self.scrollView.addGestureRecognizer(tapGesture)
self.clipsToBounds = true
self.insertSubview(self.scrollView, atIndex: 0)
}
func didTap(tapGesture: UITapGestureRecognizer) {
var point: CGPoint = tapGesture.locationInView(self.scrollView)
self.delegate?.pageView(self, didSelectItemAtIndex: self.currentIndexItem)
}
// private func findCurrentIndex (point: CGPoint) -> Int {
//
// var index = 0
//
// for var i = 0; i < self.itemsQueueArray.count; i++ {
//
// if CGRectIntersectsRect(CGRectMake(point.x, point.y, 1, 1), self.itemsQueueArray.objectAtIndex(i).frame) {
// index = i
// }
//
// }
//
// return index
// }
// MARK: - ScrollView Position Methods
private func findFirstOrLastView() {
var foundView: UIView!
if scrollView.contentOffset.x > self.scrollView.frame.size.width {
foundView = self.itemsQueueArray.lastObject as UIView
}else{
foundView = self.itemsQueueArray.firstObject as UIView
}
self.scrollToView(foundView)
}
private func scrollToRightView() {
var viewSelected: UIView!
for view in scrollView.subviews {
let scrollViewRightX: CGFloat = scrollView.contentOffset.x + self.distanceBetweenViews
let scrollFrame = CGRectMake(scrollViewRightX, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
if CGRectIntersectsRect(view.frame, scrollFrame) {
self.scrollToRightViewContentOffSetWithView(view as UIView)
viewSelected = view as UIView
return
}
}
if viewSelected == nil {
self.findFirstOrLastView()
}
}
private func scrollToRightViewContentOffSetWithView(view: UIView) {
var rightPoint: CGPoint = CGPointMake(view.frame.origin.x - self.distanceBetweenViews, self.scrollView.contentOffset.y)
self.currentIndexItem = self.itemsQueueArray.indexOfObject(view)
self.updateScrollViewContentOffSet(rightPoint)
}
private func scrollToCenterView() {
var viewSelected: UIView!
for view in scrollView.subviews {
let scrollViewCenterX: CGFloat = scrollView.frame.size.width/2 + scrollView.contentOffset.x
let scrollFrame = CGRectMake(scrollViewCenterX, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
if CGRectIntersectsRect(view.frame, scrollFrame) {
self.scrollToCenterViewContentOffSetWithView(view as UIView)
viewSelected = view as UIView
return
}
}
if viewSelected == nil {
self.findFirstOrLastView()
}
}
private func getCenterPoint(view: UIView) -> CGPoint {
var centerPoint: CGPoint = CGPointMake(view.frame.origin.x - (scrollView.frame.size.width/2) + (view.frame.size.width/2), self.scrollView.contentOffset.y)
return centerPoint
}
private func scrollToCenterViewContentOffSetWithView(view: UIView) {
var centerPoint = self.getCenterPoint(view)
self.currentIndexItem = self.itemsQueueArray.indexOfObject(view)
self.updateScrollViewContentOffSet(centerPoint)
}
private func scrollToLeftView() {
var viewSelected: UIView!
for view in scrollView.subviews {
let scrollViewLeftX: CGFloat = scrollView.contentOffset.x + self.scrollView.frame.size.width - view.frame.size.width - self.distanceBetweenViews
let scrollFrame = CGRectMake(scrollViewLeftX, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
if CGRectIntersectsRect(view.frame, scrollFrame) {
scrollToLeftViewContentOffSetWithView(view as UIView)
viewSelected = view as UIView
return
}
}
if viewSelected == nil {
self.findFirstOrLastView()
}
}
private func getLeftCenter(view: UIView) -> CGPoint {
var leftPoint: CGPoint = CGPointMake(view.frame.origin.x - self.scrollView.frame.size.width + view.frame.size.width + self.distanceBetweenViews, self.scrollView.contentOffset.y)
return leftPoint
}
private func scrollToLeftViewContentOffSetWithView(view: UIView) {
var leftPoint = self.getLeftCenter(view)
self.currentIndexItem = self.itemsQueueArray.indexOfObject(view)
self.updateScrollViewContentOffSet(leftPoint)
}
private func updateScrollViewContentOffSet(point: CGPoint) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.scrollView.setContentOffset(point, animated: false)
}) { (Bool) -> Void in
}
}
// MARK: - ScrollView Delegate
func scrollViewDidScroll(scrollView: UIScrollView) {
self.delegate?.pageViewDidScroll(self)
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.delegate?.pageViewWillBeginDecelarating(self)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// self.delegate?.pageViewDidEndDragging(self, willDecelerate: true)
//
// self.delegate?.pageViewWillBeginDecelarating(self)
// switch self.alignment {
//
// case .Right:
// self.scrollToRightView()
// break
//
// case .Center:
// self.scrollToCenterView()
// break
//
// case .Left:
// self.scrollToLeftView()
// break
//
// }
}
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
}
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
switch self.alignment {
case .Right:
self.scrollToRightView()
break
case .Center:
self.scrollToCenterView()
break
case .Left:
self.scrollToLeftView()
break
}
}
}
|
mit
|
e7a410b8cf11e579d9a4122080a8e1c6
| 29.944976 | 185 | 0.609896 | 5.122772 | false | false | false | false |
SwiftyVK/SwiftyVK
|
Library/UI/macOS/Share/SharePreferencesCell_macOS.swift
|
2
|
717
|
import Cocoa
final class SharePreferencesCellMacOS: NSView {
@IBOutlet private weak var nameLabel: NSTextField?
@IBOutlet private weak var stateSwitcher: JSSwitch?
private var preference: ShareContextPreference?
override func viewWillDraw() {
super.viewWillDraw()
nameLabel?.stringValue = preference?.name ?? ""
stateSwitcher?.on = preference?.active ?? false
}
func set(preference: ShareContextPreference) {
self.preference = preference
nameLabel?.stringValue = preference.name
stateSwitcher?.on = preference.active
}
@IBAction func stateChanged(_ sender: JSSwitch) {
preference?.active = sender.on
}
}
|
mit
|
aa44066087cc4d5468b3da096c8c007d
| 28.875 | 55 | 0.669456 | 5.085106 | false | false | false | false |
arvedviehweger/swift
|
stdlib/public/SDK/Foundation/URLComponents.swift
|
6
|
25936
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.
///
/// Its behavior differs subtly from the `URL` struct, which conforms to older RFCs. However, you can easily obtain a `URL` based on the contents of a `URLComponents` or vice versa.
public struct URLComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSURLComponents
internal var _handle: _MutableHandle<NSURLComponents>
/// Initialize with all components undefined.
public init() {
_handle = _MutableHandle(adoptingReference: NSURLComponents())
}
/// Initialize with the components of a URL.
///
/// If resolvingAgainstBaseURL is `true` and url is a relative URL, the components of url.absoluteURL are used. If the url string from the URL is malformed, nil is returned.
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {
guard let result = NSURLComponents(url: url, resolvingAgainstBaseURL: resolve) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Initialize with a URL string.
///
/// If the URLString is malformed, nil is returned.
public init?(string: String) {
guard let result = NSURLComponents(string: string) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Returns a URL created from the NSURLComponents.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public var url: URL? {
return _handle.map { $0.url }
}
// Returns a URL created from the NSURLComponents relative to a base URL.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public func url(relativeTo base: URL?) -> URL? {
return _handle.map { $0.url(relativeTo: base) }
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
@available(OSX 10.10, iOS 8.0, *)
public var string: String? {
return _handle.map { $0.string }
}
/// The scheme subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set the scheme with an invalid scheme string will cause an exception.
public var scheme: String? {
get { return _handle.map { $0.scheme } }
set { _applyMutation { $0.scheme = newValue } }
}
/// The user subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var user: String? {
get { return _handle.map { $0.user } }
set { _applyMutation { $0.user = newValue } }
}
/// The password subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var password: String? {
get { return _handle.map { $0.password } }
set { _applyMutation { $0.password = newValue } }
}
/// The host subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var host: String? {
get { return _handle.map { $0.host } }
set { _applyMutation { $0.host = newValue } }
}
/// The port subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set a negative port number will cause a fatal error.
public var port: Int? {
get { return _handle.map { $0.port?.intValue } }
set { _applyMutation { $0.port = newValue != nil ? newValue as NSNumber? : nil as NSNumber?} }
}
/// The path subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var path: String {
get {
guard let result = _handle.map({ $0.path }) else { return "" }
return result
}
set {
_applyMutation { $0.path = newValue }
}
}
/// The query subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var query: String? {
get { return _handle.map { $0.query } }
set { _applyMutation { $0.query = newValue } }
}
/// The fragment subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var fragment: String? {
get { return _handle.map { $0.fragment } }
set { _applyMutation { $0.fragment = newValue } }
}
/// The user subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlUserAllowed`).
public var percentEncodedUser: String? {
get { return _handle.map { $0.percentEncodedUser } }
set { _applyMutation { $0.percentEncodedUser = newValue } }
}
/// The password subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPasswordAllowed`).
public var percentEncodedPassword: String? {
get { return _handle.map { $0.percentEncodedPassword } }
set { _applyMutation { $0.percentEncodedPassword = newValue } }
}
/// The host subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlHostAllowed`).
public var percentEncodedHost: String? {
get { return _handle.map { $0.percentEncodedHost } }
set { _applyMutation { $0.percentEncodedHost = newValue } }
}
/// The path subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPathAllowed`).
public var percentEncodedPath: String {
get {
guard let result = _handle.map({ $0.percentEncodedPath }) else { return "" }
return result
}
set {
_applyMutation { $0.percentEncodedPath = newValue }
}
}
/// The query subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlQueryAllowed`).
public var percentEncodedQuery: String? {
get { return _handle.map { $0.percentEncodedQuery } }
set { _applyMutation { $0.percentEncodedQuery = newValue } }
}
/// The fragment subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlFragmentAllowed`).
public var percentEncodedFragment: String? {
get { return _handle.map { $0.percentEncodedFragment } }
set { _applyMutation { $0.percentEncodedFragment = newValue } }
}
@available(OSX 10.11, iOS 9.0, *)
private func _toStringRange(_ r : NSRange) -> Range<String.Index>? {
guard r.location != NSNotFound else { return nil }
let utf16Start = String.UTF16View.Index(_offset: r.location)
let utf16End = String.UTF16View.Index(_offset: r.location + r.length)
guard let s = self.string else { return nil }
guard let start = String.Index(utf16Start, within: s) else { return nil }
guard let end = String.Index(utf16End, within: s) else { return nil }
return start..<end
}
/// Returns the character range of the scheme in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfScheme: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfScheme })
}
/// Returns the character range of the user in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfUser: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfUser })
}
/// Returns the character range of the password in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfPassword: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPassword })
}
/// Returns the character range of the host in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfHost: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfHost })
}
/// Returns the character range of the port in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfPort: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPort })
}
/// Returns the character range of the path in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfPath: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPath })
}
/// Returns the character range of the query in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfQuery: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfQuery })
}
/// Returns the character range of the fragment in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(OSX 10.11, iOS 9.0, *)
public var rangeOfFragment: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfFragment })
}
/// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string.
///
/// Each `URLQueryItem` represents a single key-value pair,
///
/// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the `URLComponents` has an empty query component, returns an empty array. If the `URLComponents` has no query component, returns nil.
///
/// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. Passing an empty array sets the query component of the `URLComponents` to an empty string. Passing nil removes the query component of the `URLComponents`.
///
/// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
@available(OSX 10.10, iOS 8.0, *)
public var queryItems: [URLQueryItem]? {
get { return _handle.map { $0.queryItems } }
set { _applyMutation { $0.queryItems = newValue } }
}
public var hashValue: Int {
return _handle.map { $0.hash }
}
// MARK: - Bridging
fileprivate init(reference: NSURLComponents) {
_handle = _MutableHandle(reference: reference)
}
public static func ==(lhs: URLComponents, rhs: URLComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
extension URLComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let u = url {
return u.description
} else {
return self.customMirror.children.reduce("") {
$0.appending("\($1.label ?? ""): \($1.value) ")
}
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
if let s = self.scheme { c.append((label: "scheme", value: s)) }
if let u = self.user { c.append((label: "user", value: u)) }
if let pw = self.password { c.append((label: "password", value: pw)) }
if let h = self.host { c.append((label: "host", value: h)) }
if let p = self.port { c.append((label: "port", value: p)) }
c.append((label: "path", value: self.path))
if #available(OSX 10.10, iOS 8.0, *) {
if let qi = self.queryItems { c.append((label: "queryItems", value: qi)) }
}
if let f = self.fragment { c.append((label: "fragment", value: f)) }
let m = Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension URLComponents : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLComponents.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLComponents {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) -> Bool {
result = URLComponents(reference: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLComponents?) -> URLComponents {
var result: URLComponents?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSURLComponents : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLComponents)
}
}
/// A single name-value pair, for use with `URLComponents`.
@available(OSX 10.10, iOS 8.0, *)
public struct URLQueryItem : ReferenceConvertible, Hashable, Equatable {
public typealias ReferenceType = NSURLQueryItem
fileprivate var _queryItem : NSURLQueryItem
public init(name: String, value: String?) {
_queryItem = NSURLQueryItem(name: name, value: value)
}
fileprivate init(reference: NSURLQueryItem) { _queryItem = reference.copy() as! NSURLQueryItem }
fileprivate var reference : NSURLQueryItem { return _queryItem }
public var name : String {
get { return _queryItem.name }
set { _queryItem = NSURLQueryItem(name: newValue, value: value) }
}
public var value : String? {
get { return _queryItem.value }
set { _queryItem = NSURLQueryItem(name: name, value: newValue) }
}
public var hashValue: Int { return _queryItem.hash }
@available(OSX 10.10, iOS 8.0, *)
public static func ==(lhs: URLQueryItem, rhs: URLQueryItem) -> Bool {
return lhs._queryItem.isEqual(rhs as NSURLQueryItem)
}
}
@available(OSX 10.10, iOS 8.0, *)
extension URLQueryItem : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let v = value {
return "\(name)=\(v)"
} else {
return name
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let c: [(label: String?, value: Any)] = [
("name", name),
("value", value as Any),
]
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(OSX 10.10, iOS 8.0, *)
extension URLQueryItem : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLQueryItem.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLQueryItem {
return _queryItem
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) -> Bool {
result = URLQueryItem(reference: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLQueryItem?) -> URLQueryItem {
var result: URLQueryItem?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(OSX 10.10, iOS 8.0, *)
extension NSURLQueryItem : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLQueryItem)
}
}
|
apache-2.0
|
bca319d4a6340e500bb90fcef8ddfdae
| 53.7173 | 526 | 0.678208 | 4.801185 | false | false | false | false |
groue/GRMustache.swift
|
Sources/Localizer.swift
|
4
|
11927
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension StandardLibrary {
/// StandardLibrary.Localizer provides localization of Mustache sections
/// or data.
///
/// let localizer = StandardLibrary.Localizer(bundle: nil, table: nil)
/// template.register(localizer, forKey: "localize")
///
/// ### Localizing data:
///
/// `{{ localize(greeting) }}` renders `NSLocalizedString("Hello", comment: "")`,
/// assuming the `greeting` key resolves to the `Hello` string.
///
/// ### Localizing sections:
///
/// `{{#localize}}Hello{{/localize}}` renders `NSLocalizedString("Hello", comment: "")`.
///
/// ### Localizing sections with arguments:
///
/// `{{#localize}}Hello {{name}}{{/localize}}` builds the format string
/// `Hello %@`, localizes it with NSLocalizedString, and finally
/// injects the name with `String(format:...)`.
///
/// ### Localize sections with arguments and conditions:
///
/// `{{#localize}}Good morning {{#title}}{{title}}{{/title}} {{name}}{{/localize}}`
/// build the format string `Good morning %@" or @"Good morning %@ %@`,
/// depending on the presence of the `title` key. It then injects the name, or
/// both title and name, with `String(format:...)`, to build the final
/// rendering.
public final class Localizer : MustacheBoxable {
/// The bundle
public let bundle: Bundle
/// The table
public let table: String?
/// Creates a Localizer.
///
/// - parameter bundle: The bundle where to look for localized strings.
/// If nil, the main bundle is used.
/// - parameter table: The table where to look for localized strings.
/// If nil, the default `Localizable.strings` is used.
public init(bundle: Bundle? = nil, table: String? = nil) {
self.bundle = bundle ?? Bundle.main
self.table = table
}
/// `Localizer` adopts the `MustacheBoxable` protocol so that it can
/// feed Mustache templates.
///
/// You should not directly call the `mustacheBox` property.
public var mustacheBox: MustacheBox {
// Return a multi-facetted box, because Localizer interacts in
// various ways with Mustache rendering.
return MustacheBox(
// It has a value
value: self,
// Localizer can be used as a filter: {{ localize(x) }}:
filter: Filter(self.filter),
// Localizer performs custom rendering, so that it can localize
// the sections it is attached to: {{# localize }}Hello{{/ localize }}.
render: self.render,
// Localizer needs to observe the rendering of variables tags
// inside the section it is attached to: {{# localize }}Hello {{ name }}{{/ localize }}.
willRender: self.willRender,
didRender: self.didRender)
}
// =====================================================================
// MARK: - Not public
private var formatArguments: [String]?
// This function is used for evaluating `localize(x)` expressions.
private func filter(_ rendering: Rendering) throws -> Rendering {
return Rendering(localizedStringForKey(rendering.string), rendering.contentType)
}
// This functionis used to render a {{# localize }}Hello{{/ localize }} section.
private func render(_ info: RenderingInfo) throws -> Rendering {
// Perform a first rendering of the section tag, that will turn
// variable tags into a custom placeholder.
//
// "...{{name}}..." will get turned into "...GRMustacheLocalizerValuePlaceholder...".
//
// For that, we make sure we are notified of tag rendering, so that
// our willRender(tag: Tag, box:) method has the tags render
// GRMustacheLocalizerValuePlaceholder instead of the regular values.
//
// This behavior of willRender() is trigerred by the nil value of
// self.formatArguments:
formatArguments = nil
// Push self in the context stack in order to trigger our
// willRender() method.
let context = info.context.extendedContext(Box(self))
let localizableFormatRendering = try info.tag.render(context)
// Now perform a second rendering that will fill our
// formatArguments array with HTML-escaped tag renderings.
//
// Now our willRender() method will let the tags render regular
// values. Our didRender() method will grab those renderings,
// and fill self.formatArguments.
//
// This behavior of willRender() is not the same as the previous
// one, and is trigerred by the non-nil value of
// self.formatArguments:
formatArguments = []
// Render again
_ = try! info.tag.render(context)
let rendering: Rendering
if formatArguments!.isEmpty
{
// There is no format argument, which means no inner
// variable tag: {{# localize }}plain text{{/ localize }}
rendering = Rendering(localizedStringForKey(localizableFormatRendering.string), localizableFormatRendering.contentType)
}
else
{
// There are format arguments, which means inner variable
// tags: {{# localize }}...{{ name }}...{{/ localize }}.
//
// Take special precaution with the "%" character:
//
// When rendering {{#localize}}%d {{name}}{{/localize}},
// the localizable format we need is "%%d %@".
//
// Yet the localizable format we have built so far is
// "%d GRMustacheLocalizerValuePlaceholder".
//
// In order to get an actual format string, we have to:
// - turn GRMustacheLocalizerValuePlaceholder into %@
// - escape % into %%.
//
// The format string will then be "%%d %@", as needed.
let localizableFormat = localizableFormatRendering.string.replacingOccurrences(of: "%", with: "%%").replacingOccurrences(of: Placeholder.string, with: "%@")
// Now localize the format
let localizedFormat = localizedStringForKey(localizableFormat)
// Apply arguments
let localizedRendering = stringWithFormat(format: localizedFormat, argumentsArray: formatArguments!)
// And we have the final rendering
rendering = Rendering(localizedRendering, localizableFormatRendering.contentType)
}
// Clean up
formatArguments = nil
// Done
return rendering
}
private func willRender(_ tag: Tag, box: MustacheBox) -> MustacheBox {
switch tag.type {
case .variable:
// {{ value }}
//
// We behave as stated in the documentation of render():
if formatArguments == nil {
return Box(Placeholder.string)
} else {
return box
}
case .section:
// {{# value }}
// {{^ value }}
//
// We do not want to mess with Mustache handling of boolean and
// loop sections such as {{#true}}...{{/}}.
return box
}
}
private func didRender(_ tag: Tag, box: MustacheBox, string: String?) {
switch tag.type {
case .variable:
// {{ value }}
//
// We behave as stated in the documentation of render():
if formatArguments != nil {
if let string = string {
formatArguments!.append(string)
}
}
case .section:
// {{# value }}
// {{^ value }}
break
}
}
private func localizedStringForKey(_ key: String) -> String {
return bundle.localizedString(forKey: key, value:"", table:table)
}
private func stringWithFormat(format: String, argumentsArray args:[String]) -> String {
switch args.count {
case 0:
return String(format: format)
case 1:
return String(format: format, args[0])
case 2:
return String(format: format, args[0], args[1])
case 3:
return String(format: format, args[0], args[1], args[2])
case 4:
return String(format: format, args[0], args[1], args[2], args[3])
case 5:
return String(format: format, args[0], args[1], args[2], args[3], args[4])
case 6:
return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5])
case 7:
return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6])
case 8:
return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])
case 9:
return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8])
case 10:
return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9])
default:
fatalError("Not implemented: format with \(args.count) parameters")
}
}
struct Placeholder {
static let string = "GRMustacheLocalizerValuePlaceholder"
}
}
}
|
mit
|
6579048d66086559590a710513e08fb7
| 41.29078 | 172 | 0.52591 | 5.374493 | false | false | false | false |
ms06taku/ZoomLever
|
Example/ZoomLever/ViewController.swift
|
1
|
1020
|
//
// ViewController.swift
// ZoomLever
//
// Created by Taku Himeno on 06/17/2017.
// Copyright (c) 2017 Taku Himeno. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ZoomLeverDelegate {
@IBOutlet weak var zoomLever: ZoomLever!{
didSet{
zoomLever.delegate = self
}
}
@IBOutlet private weak var rateLabel: UILabel!{
didSet{
rateLabel.text = "0.0"
}
}
@IBOutlet private weak var valueLabel: UILabel!{
didSet{
valueLabel.text = "0.0"
}
}
// MARK: - view
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - delegate
func rateChanged(rate: CGFloat) {
rateLabel.text = String(format:"%0.1f", rate)
}
func valueChanged(value: CGFloat) {
valueLabel.text = String(format:"%0.1f", value)
}
}
|
mit
|
fcdec23f09dad46f2f468502c2b36df9
| 19.816327 | 59 | 0.571569 | 4.129555 | false | false | false | false |
daxiangfei/RTSwiftUtils
|
RTSwiftUtils/Extension/UIViewControllerExtension.swift
|
1
|
5949
|
//
// UIViewControllerExtension.swift
// RongTeng
//
// Created by rongteng on 16/3/28.
// Copyright © 2016年 Mike. All rights reserved.
//
import UIKit
extension UIViewController {
public func pushTo(_ vc:UIViewController) {
if self.navigationController?.viewControllers.count == 1 {
vc.hidesBottomBarWhenPushed = true
}
self.navigationController?.pushViewController(vc, animated: true)
}
public func popToVCAtIndex(_ index:NSInteger) {
guard (self.navigationController?.viewControllers.count)! > index else { return }
_ = self.navigationController?.popToViewController(
(self.navigationController?.viewControllers[index])!, animated: true)
}
@objc public func popToLastVC() {
_ = self.navigationController?.popViewController(animated: true)
}
@objc public func popToRootVC() {
_ = self.navigationController?.popToRootViewController(animated: true)
}
@objc public func dismissSelf(_ isAnimation:Bool = true) {
self.navigationController?.dismiss(animated: isAnimation, completion: nil)
}
///向上pop 减去几个
public func popToSubtraction(_ num:Int) {
guard self.navigationController != nil else{return}
let ind = self.navigationController!.popSubtractionIndex(num)
popToVCAtIndex(ind)
}
}
extension UIViewController {
///设置图片性质的导航栏左边 按钮及响应方法
public func decorateLeftNavImage(_ imageName:String,clickSelector:Selector) {
let image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)
let leftItem = UIBarButtonItem(image: image, style: .plain, target: self, action: clickSelector)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
negativeSpacer.width = 5
self.navigationItem.setLeftBarButtonItems([negativeSpacer,leftItem], animated: false)
}
//设置图片性质的导航栏右边 按钮及响应方法
public func decorateRightNavImage(_ imageName:String,clickSelector:Selector) -> UIButton {
let imageC = UIImage(named: imageName)
let rightbt = UIButton(type: .custom)
rightbt.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30))
rightbt.addTarget(self, action: clickSelector, for: .touchUpInside)
rightbt.setImage(imageC, for: .normal)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -5
let rightItem = UIBarButtonItem(customView: rightbt)
self.navigationItem.setRightBarButtonItems([negativeSpacer,rightItem], animated: false)
return rightbt
}
///设置view性质的导航栏右边
public func decorateRightNavView(_ view:UIView) {
let rightItem = UIBarButtonItem(customView: view)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -12
self.navigationItem.setRightBarButtonItems([negativeSpacer,rightItem], animated: false)
}
///设置文字性质的导航栏左边 按钮及响应方法
public func decorateLeftNavTitle(_ titleStr:String,clickSelector:Selector) -> UIBarButtonItem {
let leftItem = UIBarButtonItem(title: titleStr, style: .plain, target: self, action: clickSelector)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
negativeSpacer.width = 5
self.navigationItem.setLeftBarButtonItems([negativeSpacer,leftItem], animated: false)
return leftItem;
}
///设置文字性质的导航栏左边 按钮及响应方法
@discardableResult
public func decorateRightNavTitle(_ titleStr:String,clickSelector:Selector) -> UIView {
let bt = UIButton(type: .custom)
bt.decorateStyleOfBT(title: titleStr, textColor: .white, textFont: 14.ratioHeight, backGroundColor: .clear)
bt.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: titleStr.getWidth(maxWidth: 100, font: 14.ratioHeight), height: 44))
bt.addTarget(self, action: clickSelector, for: .touchUpInside)
let rightItem = UIBarButtonItem(customView: bt)
// let rightItem = UIBarButtonItem(title: titleStr, style: .plain, target: self, action: clickSelector)
// let titleAtt = [NSFontAttributeName:UIFont.systemFont(ofSize: 14.ratioHeight)]
// rightItem.setTitleTextAttributes(titleAtt, for: .normal)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = 5
self.navigationItem.setRightBarButtonItems([negativeSpacer,rightItem], animated: false)
return bt
}
///设置view性质的导航栏左边
public func decorateLiftNavView(_ view:UIView) {
let liftItem = UIBarButtonItem(customView: view)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = -8
self.navigationItem.setLeftBarButtonItems([negativeSpacer,liftItem], animated: false)
}
}
extension UINavigationController: UIGestureRecognizerDelegate {
public func popSubtractionIndex(_ num:Int) -> Int {
let stackCount = self.viewControllers.count
let realSub = num+1
let popIndex = stackCount >= realSub ? (stackCount-realSub) : 0
return popIndex
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return self.childViewControllers.count != 1
}
}
extension UIViewController {
/// 保留导航栏栈中的第一个和最后一个vc
public func navStackSaveFirstAndLast() {
guard let nav = self.navigationController else { return }
var vcs = nav.viewControllers
let firstVC = vcs.first
let lastVC = vcs.last
vcs.removeAll()
vcs.append(contentsOf: [firstVC!,lastVC!])
nav.setViewControllers(vcs, animated: false)
}
}
|
mit
|
2770843045262157cd397aa9201bfc02
| 33.39759 | 132 | 0.730823 | 4.375479 | false | false | false | false |
bradvandyk/OpenSim
|
OpenSim/URLHelper.swift
|
1
|
1484
|
//
// DeviceHelper.swift
// SimPholders
//
// Created by Luo Sheng on 11/9/15.
// Copyright © 2015 Luo Sheng. All rights reserved.
//
import Foundation
struct URLHelper {
static let devicesPathComponent = "Developer/CoreSimulator/Devices/"
static let applicationStatesComponent = "data/Library/FrontBoard/applicationState.plist"
static let containersComponent = "data/Containers/Data/Application"
static let deviceSetFileName = "device_set.plist"
static let deviceFileName = "device.plist"
static var deviceURL: NSURL {
get {
guard let libraryPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true).first else {
return NSURL()
}
return NSURL(fileURLWithPath: libraryPath).URLByAppendingPathComponent(devicesPathComponent)
}
}
static var deviceSetURL: NSURL {
return self.deviceURL.URLByAppendingPathComponent(deviceSetFileName)
}
static func deviceURLForUDID(UDID: String) -> NSURL {
return deviceURL.URLByAppendingPathComponent(UDID)
}
static func applicationStateURLForUDID(UDID: String) -> NSURL {
return deviceURLForUDID(UDID).URLByAppendingPathComponent(applicationStatesComponent)
}
static func containersURLForUDID(UDID: String) -> NSURL {
return deviceURLForUDID(UDID).URLByAppendingPathComponent(containersComponent, isDirectory: true)
}
}
|
mit
|
5c654264125158ede0c394f9fd7076a3
| 31.977778 | 126 | 0.703304 | 4.846405 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Album/TagSelector/TagSelectorCell.swift
|
1
|
1516
|
//
// TagSelectorCell.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 09/02/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import UIKit
import piwigoKit
class TagSelectorCell: UITableViewCell {
@IBOutlet weak private var tagLabel: UILabel!
// Configures the cell with a tag instance
func configure(with tag: Tag) {
// General settings
backgroundColor = UIColor.piwigoColorCellBackground()
tintColor = UIColor.piwigoColorOrange()
tagLabel.font = UIFont.piwigoFontNormal()
tagLabel.textColor = UIColor.piwigoColorLeftLabel()
// => pwg.tags.getList returns in addition: counter, url
let nber: Int64 = tag.numberOfImagesUnderTag
if (nber == Int64.zero) || (nber == Int64.max) {
// Unknown number of images
tagLabel.text = tag.tagName
} else {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let nberPhotos = (numberFormatter.string(from: NSNumber(value: nber)) ?? "0") as String
let nberImages: String = nber > 1 ?
String(format: NSLocalizedString("severalImagesCount", comment: "%@ photos"), nberPhotos) :
String(format: NSLocalizedString("singleImageCount", comment: "%@ photo"), nberPhotos)
tagLabel.text = "\(tag.tagName) (\(nberImages))"
}
}
override func prepareForReuse() {
tagLabel.text = ""
}
}
|
mit
|
0ae17be40e771bb6cfbdb575d0ef6d3d
| 32.644444 | 107 | 0.622193 | 4.519403 | false | false | false | false |
markedwardmurray/Starlight
|
Starlight/Starlight/Controllers/MainTableViewController.swift
|
1
|
13220
|
//
// ViewController.swift
// Starlight
//
// Created by Mark Murray on 11/17/16.
// Copyright © 2016 Mark Murray. All rights reserved.
//
import UIKit
import INTULocationManager
import Hex
import JSQWebViewController
enum SegmentIndex: Int {
case legislators, upcomingBills
}
enum MainTVCReuseIdentifier: String {
case legislatorCell, upcomingBillCell, billCell
}
class MainTableViewController: UITableViewController, UISearchBarDelegate {
@IBOutlet var searchBar: UISearchBar!
var segmentIndex: SegmentIndex = SegmentIndex.legislators
var legislators: [Legislator] = []
var billTypes: [BillType] = []
let locationManager = INTULocationManager.sharedInstance()
let geoCoder = CLGeocoder()
var location: CLLocation?
var placemark: CLPlacemark?
override func viewDidLoad() {
super.viewDidLoad()
let segmentedControl = UISegmentedControl(items: ["Legislators","Upcoming Bills"])
segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(sender:)), for: .valueChanged)
segmentedControl.tintColor = UIColor.white
segmentedControl.selectedSegmentIndex = 0
self.navigationItem.titleView = segmentedControl
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 100
self.loadLegislatorsWithCurrentLocation()
self.loadUpcomingBills()
}
func segmentedControlValueChanged(sender: UISegmentedControl) {
self.segmentIndex = SegmentIndex(rawValue: sender.selectedSegmentIndex)!
sender.tintColor = UIColor.white
sender.subviews[sender.selectedSegmentIndex].backgroundColor = UIColor.clear
switch self.segmentIndex {
case .legislators:
self.tableView.tableHeaderView = self.searchBar
case .upcomingBills:
self.tableView.tableHeaderView = nil
}
self.tableView.reloadData()
}
func loadLegislatorsWithCurrentLocation() {
locationManager.requestLocation(withDesiredAccuracy: INTULocationAccuracy.neighborhood, timeout: TimeInterval(5), delayUntilAuthorized: true) { (location, accuracy, status) -> Void in
print(status)
guard let location = location else {
self.showAlertWithTitle(title: "Error!", message: "Could not get your location")
return;
}
self.location = location
let lat = location.coordinate.latitude
let lng = location.coordinate.longitude
SunlightAPIClient().getLegislatorsWithLat(lat: lat, lng: lng, completion: { (legislatorsResult) in
self.updateWith(legislatorsResult: legislatorsResult)
})
self.geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if (error != nil || placemarks?.count == 0) {
self.navigationItem.title = "Could Not Geocode Coordinate"
} else if let placemark = placemarks?.first {
self.placemark = placemark;
self.searchBar.text = placemark.address
}
})
}
}
func updateWith(legislatorsResult: LegislatorsResult) {
switch legislatorsResult {
case .error(let error):
print(error)
self.showAlertWithTitle(title: "Error!", message: error.localizedDescription)
case .legislators(let legislators):
self.legislators = legislators
if self.segmentIndex == .legislators {
self.tableView.reloadData()
}
}
}
func loadUpcomingBills() {
SunlightAPIClient.sharedInstance.getUpcomingBills { (upcomingBillsResult) in
switch upcomingBillsResult {
case .error(let error):
print(error)
self.showAlertWithTitle(title: "Error!", message: error.localizedDescription)
case .upcomingBills(let upcomingBills):
self.billTypes = upcomingBills
if self.segmentIndex == .upcomingBills {
self.tableView.reloadData()
}
for upcomingBill in upcomingBills {
self.replaceWithBill(upcomingBill: upcomingBill)
}
}
}
}
func replaceWithBill(upcomingBill: UpcomingBill) {
let billId = upcomingBill.bill_id
SunlightAPIClient.sharedInstance.getBill(billId: billId, completion: { (billResult) in
switch billResult {
case .error(let error):
print(error)
if type(of: error) == SunlightError.self {
if let index = self.billTypes.index(where: { (billType) -> Bool in
return billType.bill_id == upcomingBill.bill_id
}) {
self.billTypes.remove(at: index)
if self.segmentIndex == .upcomingBills {
let indexPath = IndexPath(row: index, section: 0)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
} else {
self.showAlertWithTitle(title: "Error!", message: error.localizedDescription)
}
case .bill(var bill):
bill.upcomingBill = upcomingBill
guard let row = self.billTypes.index(where: { (billType) -> Bool in
return billType.bill_id == upcomingBill.bill_id
}) else {
print("upcoming bill not found in billTypes array")
return
}
self.billTypes[row] = bill
if self.segmentIndex == .upcomingBills {
let indexPath = IndexPath(row: row, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .left)
}
}
})
}
//MARK: UITableViewDataSource/Delegate
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.segmentIndex {
case .legislators:
return legislators.count
case .upcomingBills:
return billTypes.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch self.segmentIndex {
case .legislators:
let legislatorCell = tableView.dequeueReusableCell(withIdentifier: MainTVCReuseIdentifier.legislatorCell.rawValue)!
let legislator = legislators[indexPath.row]
legislatorCell.textLabel?.text = legislator.fullName
legislatorCell.detailTextLabel?.text = legislator.seatDescription
return legislatorCell
case .upcomingBills:
let billType = self.billTypes[indexPath.row]
if type(of: billType) == Bill.self {
let bill = billType as! Bill
let billCell = tableView.dequeueReusableCell(withIdentifier: MainTVCReuseIdentifier.billCell.rawValue)! as! BillTableViewCell
var shortTitleText = bill.bill_id
if let shortTitle = bill.short_title {
shortTitleText += " - " + shortTitle
}
billCell.popularTitleLabel.text = bill.popular_title
billCell.shortTitleLabel.text = shortTitleText
billCell.fullTitleLabel.text = bill.official_title
if bill.sponsorName.isEmpty == false {
var sponsorLabelText = "Sponsored by " + bill.sponsorName
if (bill.cosponsors_count > 0) {
sponsorLabelText += " and \(bill.cosponsors_count) others"
}
billCell.sponsorLabel.text = sponsorLabelText
} else {
billCell.sponsorLabel.text = nil
}
if let legislativeDay = bill.upcomingBill?.legislative_day {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dayText = dateFormatter.string(from: legislativeDay)
billCell.legislativeDayLabel.text = (bill.upcomingBill?.range.capitalized)! + " of " + dayText
} else {
billCell.legislativeDayLabel.text = "Undetermined Time Frame"
}
billCell.contextLabel.text = bill.upcomingBill?.context
if bill.last_version?.urls["pdf"] != nil {
billCell.accessoryType = .disclosureIndicator
} else {
billCell.accessoryType = .none
}
return billCell
}
else if type(of: billType) == UpcomingBill.self {
let upcomingBill = billType as! UpcomingBill
let upcomingBillCell = tableView.dequeueReusableCell(withIdentifier: MainTVCReuseIdentifier.upcomingBillCell.rawValue)!
upcomingBillCell.textLabel?.text = upcomingBill.bill_id;
return upcomingBillCell
}
else {
print("unrecognized BillType")
return UITableViewCell()
}
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
switch self.segmentIndex {
case .legislators:
let legislator = legislators[indexPath.row]
if (legislator.party == "D") {
cell.backgroundColor = UIColor.init(hex: "DAF0FF");
} else if (legislator.party == "R") {
cell.backgroundColor = UIColor.init(hex: "FFDFF3");
} else {
cell.backgroundColor = UIColor.white
}
break
case .upcomingBills:
break
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch self.segmentIndex {
case .legislators:
let legislator = legislators[indexPath.row]
guard let url = URL(string: "telprompt://" + legislator.phone) else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
break
case .upcomingBills:
let billType = self.billTypes[indexPath.row]
if type(of: billType) == Bill.self {
let bill = billType as! Bill
if let url = bill.last_version?.urls["pdf"] {
let webVC = WebViewController(url: url)
self.navigationController?.pushViewController(webVC, animated: true)
}
}
break
}
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: UISearchBarDelegate
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
searchBar.text = ""
if let location = self.location {
let lat = location.coordinate.latitude
let lng = location.coordinate.longitude
SunlightAPIClient().getLegislatorsWithLat(lat: lat, lng: lng, completion: { (legislatorsResult) in
self.updateWith(legislatorsResult: legislatorsResult)
if let placemark = self.placemark {
self.searchBar.text = placemark.address
}
})
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
geoCoder.geocodeAddressString(searchBar.text!, completionHandler: { (placemarks, error) in
guard error == nil else {
print(error!)
self.showAlertWithTitle(title: "Invalid Address", message: "Could not locate that address")
return;
}
guard placemarks?.first?.location != nil else {
self.showAlertWithTitle(title: "Invalid Address", message: "Could not locate that address")
return;
}
if let placemark = placemarks?.first {
let lat = placemark.location!.coordinate.latitude
let lng = placemark.location!.coordinate.longitude
SunlightAPIClient.sharedInstance.getLegislatorsWithLat(lat: lat, lng: lng, completion: { (legislatorsResult) in
self.updateWith(legislatorsResult: legislatorsResult)
self.searchBar.text = placemark.address
})
}
})
}
}
|
mit
|
cad27ce7355788e913d7ee650de5857d
| 39.179331 | 191 | 0.566533 | 5.308835 | false | false | false | false |
alexames/flatbuffers
|
swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift
|
4
|
947
|
import FlatBuffers
import Foundation
func run() {
// create a `FlatBufferBuilder`, which will be used to serialize objects
let builder = FlatBufferBuilder(initialSize: 1024)
let weapon1Name = builder.create(string: "Sword")
let weapon2Name = builder.create(string: "Axe")
// start creating the weapon by calling startWeapon
let weapon1Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon1Name, &builder)
Weapon.add(damage: 3, &builder)
// end the object by passing the start point for the weapon 1
let sword = Weapon.endWeapon(&builder, start: weapon1Start)
let weapon2Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon2Name, &builder)
Weapon.add(damage: 5, &builder)
let axe = Weapon.endWeapon(&builder, start: weapon2Start)
// Create a FlatBuffer `vector` that contains offsets to the sword and axe
// we created above.
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
}
|
apache-2.0
|
e4b6421911d6306a804c5d4e58787196
| 35.423077 | 76 | 0.7434 | 3.881148 | false | false | false | false |
montehurd/apps-ios-wikipedia
|
Wikipedia/Code/SectionEditorViewController.swift
|
1
|
35552
|
@objc(WMFSectionEditorViewControllerDelegate)
protocol SectionEditorViewControllerDelegate: class {
func sectionEditorDidFinishEditing(_ sectionEditor: SectionEditorViewController, withChanges didChange: Bool)
func sectionEditorDidFinishLoadingWikitext(_ sectionEditor: SectionEditorViewController)
}
@objc(WMFSectionEditorViewController)
class SectionEditorViewController: UIViewController {
@objc weak var delegate: SectionEditorViewControllerDelegate?
@objc var section: MWKSection?
@objc var selectedTextEditInfo: SelectedTextEditInfo?
@objc var dataStore: MWKDataStore?
private var webView: SectionEditorWebView!
private let sectionFetcher = WikiTextSectionFetcher()
private var inputViewsController: SectionEditorInputViewsController!
private var messagingController: SectionEditorWebViewMessagingController!
private var menuItemsController: SectionEditorMenuItemsController!
private var navigationItemController: SectionEditorNavigationItemController!
lazy var readingThemesControlsViewController: ReadingThemesControlsViewController = {
return ReadingThemesControlsViewController.init(nibName: ReadingThemesControlsViewController.nibName, bundle: nil)
}()
private lazy var focusNavigationView: FocusNavigationView = {
return FocusNavigationView.wmf_viewFromClassNib()
}()
private var webViewTopConstraint: NSLayoutConstraint!
private var theme = Theme.standard
private var didFocusWebViewCompletion: (() -> Void)?
private var needsSelectLastSelection: Bool = false
@objc var editFunnel = EditFunnel.shared
var keyboardFrame: CGRect? {
didSet {
keyboardDidChangeFrame(from: oldValue, newKeyboardFrame: keyboardFrame)
}
}
private var isInFindReplaceActionSheetMode = false
private var wikitext: String? {
didSet {
setWikitextToWebViewIfReady()
}
}
private var isCodemirrorReady: Bool = false {
didSet {
setWikitextToWebViewIfReady()
}
}
private let findAndReplaceHeaderTitle = WMFLocalizedString("find-replace-header", value: "Find and replace", comment: "Find and replace header title.")
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.messagingController = SectionEditorWebViewMessagingController()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
init(messagingController: SectionEditorWebViewMessagingController = SectionEditorWebViewMessagingController()) {
self.messagingController = messagingController
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
loadWikitext()
navigationItemController = SectionEditorNavigationItemController(navigationItem: navigationItem)
navigationItemController.delegate = self
configureWebView()
apply(theme: theme)
WMFAuthenticationManager.sharedInstance.loginWithSavedCredentials { (_) in }
webView.scrollView.delegate = self
setupFocusNavigationView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIWindow.keyboardDidHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
selectLastSelectionIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
UIMenuController.shared.menuItems = menuItemsController.originalMenuItems
NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardDidHideNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
super.viewWillDisappear(animated)
}
@objc func keyboardDidHide() {
inputViewsController.resetFormattingAndStyleSubmenus()
}
@objc func keyboardWillChangeFrame(_ notification: Notification) {
if let window = view.window, let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
let windowFrame = window.convert(endFrame, from: nil)
keyboardFrame = window.convert(windowFrame, to: view)
}
}
private func keyboardDidChangeFrame(from oldKeyboardFrame: CGRect?, newKeyboardFrame: CGRect?) {
guard let newKeyboardFrame = newKeyboardFrame else {
webView.scrollView.contentInset.bottom = 0
return
}
if let oldKeyboardFrame = oldKeyboardFrame,
oldKeyboardFrame.height == newKeyboardFrame.height {
return
}
//inflate content inset if needed to get around adjustedContentInset bugs
if let findAndReplaceView = inputViewsController.findAndReplaceView,
((findAndReplaceView.isVisible ||
(isInFindReplaceActionSheetMode && newKeyboardFrame.height > 0)) &&
webView.scrollView.contentInset.bottom != newKeyboardFrame.height) {
webView.scrollView.contentInset.bottom = newKeyboardFrame.height
isInFindReplaceActionSheetMode = false
} else {
webView.scrollView.contentInset.bottom = 0
}
}
private func setupFocusNavigationView() {
let closeAccessibilityText = WMFLocalizedString("find-replace-header-close-accessibility", value: "Close find and replace", comment: "Accessibility label for closing the find and replace view.")
focusNavigationView.configure(titleText: findAndReplaceHeaderTitle, closeButtonAccessibilityText: closeAccessibilityText, traitCollection: traitCollection)
focusNavigationView.isHidden = true
focusNavigationView.delegate = self
focusNavigationView.apply(theme: theme)
focusNavigationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(focusNavigationView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: focusNavigationView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: focusNavigationView.trailingAnchor)
let topConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: focusNavigationView.topAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint])
}
private func showFocusNavigationView() {
navigationController?.setNavigationBarHidden(true, animated: false)
webViewTopConstraint.constant = -focusNavigationView.frame.height
focusNavigationView.isHidden = false
}
private func hideFocusNavigationView() {
webViewTopConstraint.constant = 0
focusNavigationView.isHidden = true
navigationController?.setNavigationBarHidden(false, animated: false)
}
private func configureWebView() {
guard let language = section?.article?.url.wmf_language else {
return
}
let configuration = WKWebViewConfiguration()
let schemeHandler = SchemeHandler.shared
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: schemeHandler.scheme)
let textSizeAdjustment = UserDefaults.wmf.wmf_articleFontSizeMultiplier().intValue
let contentController = WKUserContentController()
messagingController.textSelectionDelegate = self
messagingController.buttonSelectionDelegate = self
messagingController.alertDelegate = self
messagingController.scrollDelegate = self
let languageInfo = MWLanguageInfo(forCode: language)
let isSyntaxHighlighted = UserDefaults.wmf.wmf_IsSyntaxHighlightingEnabled
let setupUserScript = CodemirrorSetupUserScript(language: language, direction: CodemirrorSetupUserScript.CodemirrorDirection(rawValue: languageInfo.dir) ?? .ltr, theme: theme, textSizeAdjustment: textSizeAdjustment, isSyntaxHighlighted: isSyntaxHighlighted) { [weak self] in
self?.isCodemirrorReady = true
}
contentController.addUserScript(setupUserScript)
contentController.add(setupUserScript, name: setupUserScript.messageHandlerName)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorSearchMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.smoothScrollToYOffsetMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.replaceAllCountMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.didSetWikitextMessage)
configuration.userContentController = contentController
webView = SectionEditorWebView(frame: .zero, configuration: configuration)
webView.navigationDelegate = self
webView.isHidden = true // hidden until wikitext is set
webView.scrollView.keyboardDismissMode = .interactive
inputViewsController = SectionEditorInputViewsController(webView: webView, messagingController: messagingController, findAndReplaceDisplayDelegate: self)
inputViewsController.delegate = self
webView.inputViewsSource = inputViewsController
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: webView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: webView.trailingAnchor)
webViewTopConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: webView.topAnchor)
let bottomConstraint = view.bottomAnchor.constraint(equalTo: webView.bottomAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, webViewTopConstraint, bottomConstraint])
if let url = SchemeHandler.FileHandler.appSchemeURL(for: "codemirror/codemirror-index.html", fragment: "top") {
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: WKWebViewLoadAssetsHTMLRequestTimeout)
webView.load(request)
messagingController.webView = webView
menuItemsController = SectionEditorMenuItemsController(messagingController: messagingController)
menuItemsController.delegate = self
webView.menuItemsDataSource = menuItemsController
webView.menuItemsDelegate = menuItemsController
}
}
@objc var shouldFocusWebView = true {
didSet {
guard shouldFocusWebView else {
return
}
logSectionReadyToEdit()
focusWebViewIfReady()
}
}
private var didSetWikitextToWebView: Bool = false {
didSet {
guard shouldFocusWebView else {
return
}
focusWebViewIfReady()
}
}
private func selectLastSelectionIfNeeded() {
guard isCodemirrorReady,
shouldFocusWebView,
didSetWikitextToWebView,
needsSelectLastSelection,
wikitext != nil else {
return
}
messagingController.selectLastSelection()
messagingController.focusWithoutScroll()
needsSelectLastSelection = false
}
private func showCouldNotFindSelectionInWikitextAlert() {
editFunnel.logSectionHighlightToEditError(language: section?.articleLanguage)
let alertTitle = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-title", value:"The text that you selected could not be located", comment:"Title for alert informing user their text selection could not be located in the article wikitext.")
let alertMessage = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-message", value:"This might be because the text you selected is not editable (eg. article title or infobox titles) or the because of the length of the text that was highlighted", comment:"Description of possible reasons the user text selection could not be located in the article wikitext.")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: CommonStrings.okTitle, style:.default, handler: nil))
present(alert, animated: true, completion: nil)
}
private func setWikitextToWebViewIfReady() {
assert(Thread.isMainThread)
guard isCodemirrorReady, let wikitext = wikitext else {
return
}
setWikitextToWebView(wikitext) { [weak self] (error) in
if let error = error {
assertionFailure(error.localizedDescription)
} else {
DispatchQueue.main.async {
self?.didSetWikitextToWebView = true
if let selectedTextEditInfo = self?.selectedTextEditInfo {
self?.messagingController.highlightAndScrollToText(for: selectedTextEditInfo){ [weak self] (error) in
if let _ = error {
self?.showCouldNotFindSelectionInWikitextAlert()
}
}
}
}
}
}
}
private func focusWebViewIfReady() {
guard didSetWikitextToWebView else {
return
}
webView.isHidden = false
webView.becomeFirstResponder()
messagingController.focus {
assert(Thread.isMainThread)
self.delegate?.sectionEditorDidFinishLoadingWikitext(self)
guard let didFocusWebViewCompletion = self.didFocusWebViewCompletion else {
return
}
didFocusWebViewCompletion()
self.didFocusWebViewCompletion = nil
}
}
func setWikitextToWebView(_ wikitext: String, completionHandler: ((Error?) -> Void)? = nil) {
messagingController.setWikitext(wikitext, completionHandler: completionHandler)
}
private func loadWikitext() {
guard let section = section else {
assertionFailure("Section should be set by now")
return
}
if shouldFocusWebView {
let message = WMFLocalizedString("wikitext-downloading", value: "Loading content...", comment: "Alert text shown when obtaining latest revision of the section being edited")
WMFAlertManager.sharedInstance.showAlert(message, sticky: true, dismissPreviousAlerts: true)
}
sectionFetcher.fetch(section) { (result, error) in
DispatchQueue.main.async {
if let error = error {
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true)
}
return
}
guard
let results = result as? [String: Any],
let revision = results["revision"] as? String
else {
return
}
if let protectionStatus = section.article?.protection,
let allowedGroups = protectionStatus.allowedGroups(forAction: "edit") as? [String],
!allowedGroups.isEmpty {
let message: String
if allowedGroups.contains("autoconfirmed") {
message = WMFLocalizedString("page-protected-autoconfirmed", value: "This page has been semi-protected.", comment: "Brief description of Wikipedia 'autoconfirmed' protection level, shown when editing a page that is protected.")
} else if allowedGroups.contains("sysop") {
message = WMFLocalizedString("page-protected-sysop", value: "This page has been fully protected.", comment: "Brief description of Wikipedia 'sysop' protection level, shown when editing a page that is protected.")
} else {
message = WMFLocalizedString("page-protected-other", value: "This page has been protected to the following levels: %1$@", comment: "Brief description of Wikipedia unknown protection level, shown when editing a page that is protected. %1$@ will refer to a list of protection levels.")
}
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
} else {
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.dismissAlert()
}
}
self.wikitext = revision
}
}
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
delegate?.sectionEditorDidFinishEditing(self, withChanges: false)
return true
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: nil) { (_) in
self.inputViewsController.didTransitionToNewCollection()
self.focusNavigationView.updateLayout(for: newCollection)
}
}
// MARK: Event logging
private var loggedEditActions: NSMutableSet = []
private func logSectionReadyToEdit() {
guard !loggedEditActions.contains(EditFunnel.Action.ready) else {
return
}
editFunnel.logSectionReadyToEdit(from: editFunnelSource, language: section?.articleLanguage)
loggedEditActions.add(EditFunnel.Action.ready)
}
private var editFunnelSource: EditFunnelSource {
return selectedTextEditInfo == nil ? .pencil : .highlight
}
}
private var previousAdjustedContentInset = UIEdgeInsets.zero
extension SectionEditorViewController: UIScrollViewDelegate {
public func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
let newAdjustedContentInset = scrollView.adjustedContentInset
guard newAdjustedContentInset != previousAdjustedContentInset else {
return
}
previousAdjustedContentInset = newAdjustedContentInset
messagingController.setAdjustedContentInset(newInset: newAdjustedContentInset)
}
}
extension SectionEditorViewController: SectionEditorNavigationItemControllerDelegate {
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapProgressButton progressButton: UIBarButtonItem) {
messagingController.getWikitext { [weak self] (result, error) in
guard let self = self else { return }
if let error = error {
assertionFailure(error.localizedDescription)
return
} else if let wikitext = result {
if wikitext != self.wikitext {
guard let vc = EditPreviewViewController.wmf_initialViewControllerFromClassStoryboard() else {
return
}
self.inputViewsController.resetFormattingAndStyleSubmenus()
self.needsSelectLastSelection = true
vc.theme = self.theme
vc.section = self.section
vc.wikitext = wikitext
vc.delegate = self
vc.editFunnel = self.editFunnel
vc.loggedEditActions = self.loggedEditActions
vc.editFunnelSource = self.editFunnelSource
self.navigationController?.pushViewController(vc, animated: true)
} else {
let message = WMFLocalizedString("wikitext-preview-changes-none", value: "No changes were made to be previewed.", comment: "Alert text shown if no changes were made to be previewed.")
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
}
}
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapCloseButton closeButton: UIBarButtonItem) {
delegate?.sectionEditorDidFinishEditing(self, withChanges: false)
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapUndoButton undoButton: UIBarButtonItem) {
messagingController.undo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapRedoButton redoButton: UIBarButtonItem) {
messagingController.redo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapReadingThemesControlsButton readingThemesControlsButton: UIBarButtonItem) {
webView.resignFirstResponder()
inputViewsController.suppressMenus = true
showReadingThemesControlsPopup(on: self, responder: self, theme: theme)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerTextSelectionDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveTextSelectionChangeMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, isRangeSelected: Bool) {
if isRangeSelected {
menuItemsController.setEditMenuItems()
}
navigationItemController.textSelectionDidChange(isRangeSelected: isRangeSelected)
inputViewsController.textSelectionDidChange(isRangeSelected: isRangeSelected)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerButtonMessageDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveSelectButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
inputViewsController.buttonSelectionDidChange(button: button)
}
func sectionEditorWebViewMessagingControllerDidReceiveDisableButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
navigationItemController.disableButton(button: button)
inputViewsController.disableButton(button: button)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerAlertDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveReplaceAllMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, replacedCount: Int) {
let format = WMFLocalizedString("replace-replace-all-results-count", value: "{{PLURAL:%1$d|%1$d item replaced|%1$d items replaced}}", comment: "Alert view label that tells the user how many instances they just replaced via \"Replace all\". %1$d is replaced with the number of instances that were replaced.")
let alertText = String.localizedStringWithFormat(format, replacedCount)
wmf_showAlertWithMessage(alertText)
}
}
extension SectionEditorViewController: FindAndReplaceKeyboardBarDisplayDelegate {
func keyboardBarDidHide(_ keyboardBar: FindAndReplaceKeyboardBar) {
hideFocusNavigationView()
}
func keyboardBarDidShow(_ keyboardBar: FindAndReplaceKeyboardBar) {
showFocusNavigationView()
}
func keyboardBarDidTapReplaceSwitch(_ keyboardBar: FindAndReplaceKeyboardBar) {
let alertController = UIAlertController(title: findAndReplaceHeaderTitle, message: nil, preferredStyle: .actionSheet)
let replaceAllActionTitle = WMFLocalizedString("action-replace-all", value: "Replace all", comment: "Title of the replace all action.")
let replaceActionTitle = WMFLocalizedString("action-replace", value: "Replace", comment: "Title of the replace all action.")
let replaceAction = UIAlertAction(title: replaceActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceSingle)
}
let replaceAllAction = UIAlertAction(title: replaceAllActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceAll)
}
let cancelAction = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel, handler: nil)
alertController.addAction(replaceAction)
alertController.addAction(replaceAllAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = keyboardBar.replaceSwitchButton
alertController.popoverPresentationController?.sourceRect = keyboardBar.replaceSwitchButton.bounds
isInFindReplaceActionSheetMode = true
present(alertController, animated: true, completion: nil)
}
}
// MARK: - WKNavigationDelegate
extension SectionEditorViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
}
// MARK - EditSaveViewControllerDelegate
extension SectionEditorViewController: EditSaveViewControllerDelegate {
func editSaveViewControllerDidSave(_ editSaveViewController: EditSaveViewController) {
delegate?.sectionEditorDidFinishEditing(self, withChanges: true)
}
}
// MARK - EditPreviewViewControllerDelegate
extension SectionEditorViewController: EditPreviewViewControllerDelegate {
func editPreviewViewControllerDidTapNext(_ editPreviewViewController: EditPreviewViewController) {
guard let vc = EditSaveViewController.wmf_initialViewControllerFromClassStoryboard() else {
return
}
vc.section = self.section
vc.wikitext = editPreviewViewController.wikitext
vc.delegate = self
vc.theme = self.theme
vc.editFunnel = self.editFunnel
vc.editFunnelSource = editFunnelSource
vc.loggedEditActions = loggedEditActions
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension SectionEditorViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
webView.scrollView.backgroundColor = theme.colors.paperBackground
webView.backgroundColor = theme.colors.paperBackground
messagingController.applyTheme(theme: theme)
inputViewsController.apply(theme: theme)
navigationItemController.apply(theme: theme)
apply(presentationTheme: theme)
focusNavigationView.apply(theme: theme)
}
}
extension SectionEditorViewController: ReadingThemesControlsPresenting {
var shouldPassthroughNavBar: Bool {
return false
}
var showsSyntaxHighlighting: Bool {
return true
}
var readingThemesControlsToolbarItem: UIBarButtonItem {
return self.navigationItemController.readingThemesControlsToolbarItem
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
inputViewsController.suppressMenus = false
}
}
extension SectionEditorViewController: ReadingThemesControlsResponding {
func updateWebViewTextSize(textSize: Int) {
messagingController.scaleBodyText(newSize: String(textSize))
}
func toggleSyntaxHighlighting(_ controller: ReadingThemesControlsViewController) {
messagingController.toggleSyntaxColors()
}
}
extension SectionEditorViewController: FocusNavigationViewDelegate {
func focusNavigationViewDidTapClose(_ focusNavigationView: FocusNavigationView) {
hideFocusNavigationView()
inputViewsController.closeFindAndReplace()
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerScrollDelegate {
func sectionEditorWebViewMessagingController(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, didReceiveScrollMessageWithNewContentOffset newContentOffset: CGPoint) {
guard
presentedViewController == nil,
newContentOffset.x.isFinite,
newContentOffset.y.isFinite
else {
return
}
self.webView.scrollView.setContentOffset(newContentOffset, animated: true)
}
}
extension SectionEditorViewController: SectionEditorInputViewsControllerDelegate {
func sectionEditorInputViewsControllerDidTapMediaInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
let insertMediaViewController = InsertMediaViewController(articleTitle: section?.article?.displaytitle?.wmf_stringByRemovingHTML(), siteURL: section?.article?.url.wmf_site)
insertMediaViewController.delegate = self
insertMediaViewController.apply(theme: theme)
let navigationController = WMFThemeableNavigationController(rootViewController: insertMediaViewController, theme: theme)
navigationController.isNavigationBarHidden = true
present(navigationController, animated: true)
}
func showLinkWizard() {
guard let dataStore = dataStore else {
return
}
messagingController.getLink { link in
guard let link = link else {
assertionFailure("Link button should be disabled")
return
}
let siteURL = self.section?.article?.url.wmf_site
if link.exists {
guard let editLinkViewController = EditLinkViewController(link: link, siteURL: siteURL, dataStore: dataStore) else {
return
}
editLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: editLinkViewController, theme: self.theme)
navigationController.isNavigationBarHidden = true
self.present(navigationController, animated: true)
} else {
let insertLinkViewController = InsertLinkViewController(link: link, siteURL: siteURL, dataStore: dataStore)
insertLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: insertLinkViewController, theme: self.theme)
self.present(navigationController, animated: true)
}
}
}
func sectionEditorInputViewsControllerDidTapLinkInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: SectionEditorMenuItemsControllerDelegate {
func sectionEditorMenuItemsControllerDidTapLink(_ sectionEditorMenuItemsController: SectionEditorMenuItemsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: EditLinkViewControllerDelegate {
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFinishEditingLink displayText: String?, linkTarget: String) {
messagingController.insertOrEditLink(page: linkTarget, label: displayText)
dismiss(animated: true)
}
func editLinkViewControllerDidRemoveLink(_ editLinkViewController: EditLinkViewController) {
messagingController.removeLink()
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFailToExtractArticleTitleFromArticleURL articleURL: URL) {
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertLinkViewControllerDelegate {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?) {
messagingController.insertOrEditLink(page: page, label: label)
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertMediaViewControllerDelegate {
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didPrepareWikitextToInsert wikitext: String) {
dismiss(animated: true)
messagingController.getLineInfo { lineInfo in
guard let lineInfo = lineInfo else {
self.messagingController.replaceSelection(text: wikitext)
return
}
if !lineInfo.hasLineTokens && lineInfo.isAtLineEnd {
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.isAtLineEnd {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.hasLineTokens {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
self.messagingController.newlineAndIndent()
} else {
self.messagingController.replaceSelection(text: wikitext)
}
}
}
}
#if (TEST)
//MARK: Helpers for testing
extension SectionEditorViewController {
func openFindAndReplaceForTesting() {
inputViewsController.textFormattingProvidingDidTapFindInPage()
}
var webViewForTesting: WKWebView {
return webView
}
var findAndReplaceViewForTesting: FindAndReplaceKeyboardBar? {
return inputViewsController.findAndReplaceViewForTesting
}
}
#endif
|
mit
|
477c6479be74fb2951be9138fc1a44ad
| 45.352021 | 384 | 0.705136 | 6.442914 | false | false | false | false |
tgu/HAP
|
Sources/HAP/Accessories/ContactSensor.swift
|
1
|
817
|
extension Accessory {
open class ContactSensor: Accessory {
public let contactSensor = Service.ContactSensor()
public init(info: Service.Info, additionalServices: [Service] = []) {
super.init(info: info, type: .sensor, services: [contactSensor] + additionalServices)
}
}
}
public enum ContactSensorState: Int, CharacteristicValueType {
case detected = 0
case notDetected = 1
}
extension Service {
open class ContactSensor: Service {
public let contactSensorState = GenericCharacteristic<ContactSensorState>(
type: .contactSensorState,
value: .notDetected,
permissions: [.read, .events])
public init() {
super.init(type: .contactSensor, characteristics: [contactSensorState])
}
}
}
|
mit
|
b400315b0cc3da9fe4415ecc9fd5bac6
| 29.259259 | 97 | 0.647491 | 4.805882 | false | false | false | false |
FindGF/_BiliBili
|
WTBilibili/Category-分区/Controller/WTCategoryViewController.swift
|
1
|
4986
|
//
// WTCategoryViewController.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/5/3.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
// 分区控制器
import UIKit
private let categoryHeaderViewH: CGFloat = 54
private let categoryCellIdentifier = "categoryCellIdentifier"
class WTCategoryViewController: UIViewController {
// MARK: - 拖线的属性
/// 头部的View
@IBOutlet weak var headerView: UIView!
/// 标题
@IBOutlet weak var titleLabel: UILabel!
/// 底部的View
@IBOutlet weak var footerView: UIView!
/// collectionView
@IBOutlet weak var collectionView: UICollectionView!
/// 数据源
var userCenterItems = [WTUserCenterItem]()
/// 记录scrollView的contentOff的Y值
var endY: CGFloat = 0
// MARK: - 系统回调函数
override func viewDidLoad()
{
super.viewDidLoad()
// 设置View
setupView()
// 设置数据
setupData()
}
}
// MARK: - 自定义函数
extension WTCategoryViewController
{
// MARK: - 设置View
private func setupView()
{
navigationController?.setNavigationBarHidden(true, animated: false)
headerView.backgroundColor = WTMainColor
titleLabel.textColor = UIColor.whiteColor()
collectionView.backgroundColor = WTColor(r: 244, g: 244, b: 244)
collectionView.layer.cornerRadius = 5
// 调整collectionView的item的间距
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let margin = (WTScreenWidth - (layout.itemSize.width * CGFloat(3))) / CGFloat(6)
layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
}
// MARK: - 设置数据
private func setupData()
{
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_live", title: "直播", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_1", title: "番剧", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_1", title: "动画", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_3", title: "音乐", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_129", title: "舞蹈", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_4", title: "游戏", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_36", title: "科技", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_4", title: "生活", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_119", title: "鬼畜", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_4", title: "时尚", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_4", title: "娱乐", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_23", title: "电影", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_11", title: "电视剧", actionBlock: nil))
userCenterItems.append(WTUserCenterItem(imageName: "home_region_icon_11", title: "游戏中心", actionBlock: nil))
collectionView.reloadData()
}
}
// MARK: - UICollectionViewDataSource
extension WTCategoryViewController: UICollectionViewDataSource, UICollectionViewDelegate
{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return userCenterItems.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(categoryCellIdentifier, forIndexPath: indexPath) as! WTCategoryCell
cell.userCenterItem = userCenterItems[indexPath.row]
return cell
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0
{
UIView.animateWithDuration(0.1, animations: {
self.endY += (-scrollView.contentOffset.y) * 0.3
self.footerView.frame.origin.y = categoryHeaderViewH + self.endY
})
scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
UIView.animateWithDuration(0.3) {
self.footerView.frame.origin.y = categoryHeaderViewH
self.endY = 0
}
}
}
|
apache-2.0
|
a0668db3eb2f24c6f736506e4b8e78d8
| 36.178295 | 140 | 0.666945 | 4.493908 | false | false | false | false |
eofster/Telephone
|
UseCasesTestDoubles/RecordCountingPurchaseCheckUseCaseOutputSpy.swift
|
1
|
1280
|
//
// RecordCountingPurchaseCheckUseCaseOutputSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
public final class RecordCountingPurchaseCheckUseCaseOutputSpy {
public private(set) var didCallDidCheckPurchase = false
public private(set) var didCallDidFailCheckingPurchase = false
public private(set) var invokedCount: Int?
public init() {}
}
extension RecordCountingPurchaseCheckUseCaseOutputSpy: RecordCountingPurchaseCheckUseCaseOutput {
public func didCheckPurchase() {
didCallDidCheckPurchase = true
}
public func didFailCheckingPurchase(recordCount count: Int) {
didCallDidFailCheckingPurchase = true
invokedCount = count
}
}
|
gpl-3.0
|
0d9249082245a91aede867a67bb30360
| 32.631579 | 97 | 0.753521 | 4.531915 | false | false | false | false |
Ethenyl/JAMFKit
|
JamfKit/Tests/Models/MobileDevice/MobileDeviceGeneralTests.swift
|
1
|
15306
|
//
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
import XCTest
@testable import JamfKit
class MobileDeviceGeneralTests: XCTestCase {
// MARK: - Constants
let subfolder = "MobileDevice/"
let defaultIdentifier: UInt = 12345
let defaultName = "Mobile Device"
let defaultDisplayName = "Mobile Device"
let defaultDeviceName = "mobile_device"
let defaultAssetTag = "asset_tag"
let defaultCapacity: UInt = 1024
let defaultCapacityMb: UInt = 1024
let defaultAvailable: UInt = 1024
let defaultAvailableMb: UInt = 1024
let defaultPercentageUsed: UInt = 5
let defaultOsType = "iOS"
let defaultOsVersion = "10.3.2"
let defaultOsBuild = "14F89"
let defaultSerialNumber = "C02Q7KHTGFWF"
let defaultUdid = "270aae10800b6e61a2ee2bbc285eb967050b5984"
let defaultPhoneNumber = "123-555-6789"
let defaultIpAddress = "192.0.0.1"
let defaultWifiMacAddress = "E0:AC:CB:97:36:G4"
let defaultBluetoothMacAddress = "E0:AC:CB:97:36:G6"
let defaultModemFirmware = "2.61.00"
let defaultModel = "iPhone 6S"
let defaultModelIdentifier = "iPhone8,1"
let defaultModelNumber = "MKRY2LL"
let defaultModelDisplay = "iPhone 6S"
let defaultDeviceOwnershipLevel = "Institutional"
let defaultIsManaged = true
let defaultIsSupervised = true
let defaultExchangeActiveSyncDeviceIdentifier = "TUCLLFJHPL779ACL9DCJQFN39F"
let defaultShared = "shared"
let defaultTethered = "tethered"
let defaultBatteryLevel: UInt = 95
let defaultIsBluetoothCapable = true
let defaultIsDeviceLocatorServiceEnabled = true
let defaultIsDoNotDisturbEnabled = true
let defaultIsCloudBackupEnabled = true
let defaultIsLocationServicesEnabled = true
let defaultIsITunesStoreAccountActive = true
// MARK: - Tests
func testShouldNotInstantiateWithInvalidParameters() {
let actualValue = MobileDeviceGeneral(identifier: defaultIdentifier, name: "")
XCTAssertNil(actualValue)
}
func testShouldInitializeFromJSON() {
let payload = self.payload(for: "mobile_device_general_valid", subfolder: subfolder)!
let defaultLastInventoryUpdate = PreciseDate(json: payload, node: "last_inventory_update")
let defaultInitialEntryDate = PreciseDate(json: payload, node: "initial_entry_date")
let defaultLastEnrollment = PreciseDate(json: payload, node: "last_enrollment")
let defaultLastCloudBackupDate = PreciseDate(json: payload, node: "last_cloud_backup_date")
let defaultLastBackupTime = PreciseDate(json: payload, node: "last_backup_time")
let actualValue = MobileDeviceGeneral(json: payload)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
XCTAssertEqual(actualValue?.deviceName, defaultDeviceName)
XCTAssertEqual(actualValue?.assetTag, defaultAssetTag)
XCTAssertEqual(actualValue?.lastInventoryUpdate?.date, defaultLastInventoryUpdate?.date)
XCTAssertEqual(actualValue?.lastInventoryUpdate?.epoch, defaultLastInventoryUpdate?.epoch)
XCTAssertEqual(actualValue?.lastInventoryUpdate?.dateUTC, defaultLastInventoryUpdate?.dateUTC)
XCTAssertEqual(actualValue?.capacity, defaultCapacity)
XCTAssertEqual(actualValue?.capacityMb, defaultCapacityMb)
XCTAssertEqual(actualValue?.available, defaultAvailable)
XCTAssertEqual(actualValue?.availableMb, defaultAvailableMb)
XCTAssertEqual(actualValue?.percentageUsed, defaultPercentageUsed)
XCTAssertEqual(actualValue?.osType, defaultOsType)
XCTAssertEqual(actualValue?.osVersion, defaultOsVersion)
XCTAssertEqual(actualValue?.osBuild, defaultOsBuild)
XCTAssertEqual(actualValue?.serialNumber, defaultSerialNumber)
XCTAssertEqual(actualValue?.udid, defaultUdid)
XCTAssertNil(actualValue?.initialEntryDate?.date)
XCTAssertEqual(actualValue?.initialEntryDate?.epoch, defaultInitialEntryDate?.epoch)
XCTAssertEqual(actualValue?.initialEntryDate?.dateUTC, defaultInitialEntryDate?.dateUTC)
XCTAssertEqual(actualValue?.phoneNumber, defaultPhoneNumber)
XCTAssertEqual(actualValue?.ipAddress, defaultIpAddress)
XCTAssertEqual(actualValue?.wifiMacAddress, defaultWifiMacAddress)
XCTAssertEqual(actualValue?.bluetoothMacAddress, defaultBluetoothMacAddress)
XCTAssertEqual(actualValue?.modemFirmware, defaultModemFirmware)
XCTAssertEqual(actualValue?.model, defaultModel)
XCTAssertEqual(actualValue?.modelIdentifier, defaultModelIdentifier)
XCTAssertEqual(actualValue?.modelNumber, defaultModelNumber)
XCTAssertEqual(actualValue?.modelDisplay, defaultModelDisplay)
XCTAssertEqual(actualValue?.deviceOwnershipLevel, defaultDeviceOwnershipLevel)
XCTAssertNil(actualValue?.lastEnrollment?.date)
XCTAssertEqual(actualValue?.lastEnrollment?.epoch, defaultLastEnrollment?.epoch)
XCTAssertEqual(actualValue?.lastEnrollment?.dateUTC, defaultLastEnrollment?.dateUTC)
XCTAssertEqual(actualValue?.isManaged, defaultIsManaged)
XCTAssertEqual(actualValue?.isSupervised, defaultIsSupervised)
XCTAssertEqual(actualValue?.exchangeActiveSyncDeviceIdentifier, defaultExchangeActiveSyncDeviceIdentifier)
XCTAssertEqual(actualValue?.shared, defaultShared)
XCTAssertEqual(actualValue?.tethered, defaultTethered)
XCTAssertEqual(actualValue?.batteryLevel, defaultBatteryLevel)
XCTAssertEqual(actualValue?.isBluetoothCapable, defaultIsBluetoothCapable)
XCTAssertEqual(actualValue?.isDeviceLocatorServiceEnabled, defaultIsDeviceLocatorServiceEnabled)
XCTAssertEqual(actualValue?.isDoNotDisturbEnabled, defaultIsDoNotDisturbEnabled)
XCTAssertEqual(actualValue?.isCloudBackupEnabled, defaultIsCloudBackupEnabled)
XCTAssertNil(actualValue?.lastCloudBackupDate?.date)
XCTAssertEqual(actualValue?.lastCloudBackupDate?.epoch, defaultLastCloudBackupDate?.epoch)
XCTAssertEqual(actualValue?.lastCloudBackupDate?.dateUTC, defaultLastCloudBackupDate?.dateUTC)
XCTAssertEqual(actualValue?.isLocationServicesEnabled, defaultIsLocationServicesEnabled)
XCTAssertEqual(actualValue?.isITunesStoreAccountActive, defaultIsITunesStoreAccountActive)
XCTAssertNil(actualValue?.lastBackupTime?.date)
XCTAssertEqual(actualValue?.lastBackupTime?.epoch, defaultLastBackupTime?.epoch)
XCTAssertEqual(actualValue?.lastBackupTime?.dateUTC, defaultLastBackupTime?.dateUTC)
}
func testShouldInitializeFromIncompleteJSON() {
let payload = self.payload(for: "mobile_device_general_incomplete", subfolder: subfolder)!
let defaultLastInventoryUpdate = PreciseDate(json: payload, node: "last_inventory_update")
let defaultInitialEntryDate = PreciseDate(json: payload, node: "initial_entry_date")
let defaultLastEnrollment = PreciseDate(json: payload, node: "last_enrollment")
let defaultLastCloudBackupDate = PreciseDate(json: payload, node: "last_cloud_backup_date")
let defaultLastBackupTime = PreciseDate(json: payload, node: "last_backup_time")
let actualValue = MobileDeviceGeneral(json: payload)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
XCTAssertEqual(actualValue?.deviceName, "")
XCTAssertEqual(actualValue?.assetTag, "")
XCTAssertEqual(actualValue?.lastInventoryUpdate?.date, defaultLastInventoryUpdate?.date)
XCTAssertEqual(actualValue?.lastInventoryUpdate?.epoch, defaultLastInventoryUpdate?.epoch)
XCTAssertEqual(actualValue?.lastInventoryUpdate?.dateUTC, defaultLastInventoryUpdate?.dateUTC)
XCTAssertEqual(actualValue?.capacity, 0)
XCTAssertEqual(actualValue?.capacityMb, 0)
XCTAssertEqual(actualValue?.available, 0)
XCTAssertEqual(actualValue?.availableMb, 0)
XCTAssertEqual(actualValue?.percentageUsed, 0)
XCTAssertEqual(actualValue?.osType, "")
XCTAssertEqual(actualValue?.osVersion, "")
XCTAssertEqual(actualValue?.osBuild, "")
XCTAssertEqual(actualValue?.serialNumber, "")
XCTAssertEqual(actualValue?.udid, "")
XCTAssertNil(actualValue?.initialEntryDate?.date)
XCTAssertEqual(actualValue?.initialEntryDate?.epoch, defaultInitialEntryDate?.epoch)
XCTAssertEqual(actualValue?.initialEntryDate?.dateUTC, defaultInitialEntryDate?.dateUTC)
XCTAssertEqual(actualValue?.phoneNumber, "")
XCTAssertEqual(actualValue?.ipAddress, "")
XCTAssertEqual(actualValue?.wifiMacAddress, "")
XCTAssertEqual(actualValue?.bluetoothMacAddress, "")
XCTAssertEqual(actualValue?.modemFirmware, "")
XCTAssertEqual(actualValue?.model, "")
XCTAssertEqual(actualValue?.modelIdentifier, "")
XCTAssertEqual(actualValue?.modelNumber, "")
XCTAssertEqual(actualValue?.modelDisplay, "")
XCTAssertEqual(actualValue?.deviceOwnershipLevel, "")
XCTAssertNil(actualValue?.lastEnrollment?.date)
XCTAssertEqual(actualValue?.lastEnrollment?.epoch, defaultLastEnrollment?.epoch)
XCTAssertEqual(actualValue?.lastEnrollment?.dateUTC, defaultLastEnrollment?.dateUTC)
XCTAssertEqual(actualValue?.isManaged, false)
XCTAssertEqual(actualValue?.isSupervised, false)
XCTAssertEqual(actualValue?.exchangeActiveSyncDeviceIdentifier, "")
XCTAssertEqual(actualValue?.shared, "")
XCTAssertEqual(actualValue?.tethered, "")
XCTAssertEqual(actualValue?.batteryLevel, 0)
XCTAssertEqual(actualValue?.isBluetoothCapable, false)
XCTAssertEqual(actualValue?.isDeviceLocatorServiceEnabled, false)
XCTAssertEqual(actualValue?.isDoNotDisturbEnabled, false)
XCTAssertEqual(actualValue?.isCloudBackupEnabled, false)
XCTAssertNil(actualValue?.lastCloudBackupDate?.date)
XCTAssertEqual(actualValue?.lastCloudBackupDate?.epoch, defaultLastCloudBackupDate?.epoch)
XCTAssertEqual(actualValue?.lastCloudBackupDate?.dateUTC, defaultLastCloudBackupDate?.dateUTC)
XCTAssertEqual(actualValue?.isLocationServicesEnabled, false)
XCTAssertEqual(actualValue?.isITunesStoreAccountActive, false)
XCTAssertNil(actualValue?.lastBackupTime?.date)
XCTAssertEqual(actualValue?.lastBackupTime?.epoch, defaultLastBackupTime?.epoch)
XCTAssertEqual(actualValue?.lastBackupTime?.dateUTC, defaultLastBackupTime?.dateUTC)
}
func testShouldNotInitializeFromInvalidJSON() {
let payload = self.payload(for: "mobile_device_general_invalid", subfolder: subfolder)!
let site = MobileDeviceGeneral(json: payload)
XCTAssertNil(site)
}
func testShouldEncodeToJSON() {
let payload = self.payload(for: "mobile_device_general_valid", subfolder: subfolder)!
let actualValue = MobileDeviceGeneral(json: payload)
let encodedObject = actualValue?.toJSON()
XCTAssertNotNil(encodedObject)
XCTAssertEqual(encodedObject?.count, 48)
XCTAssertNotNil(encodedObject?[BaseObject.CodingKeys.identifier.rawValue])
XCTAssertNotNil(encodedObject?[BaseObject.CodingKeys.name.rawValue])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.DeviceNameKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.AssetTagNameKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastInventoryUpdateKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastInventoryUpdateKey + PreciseDate.EpochKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastInventoryUpdateKey + PreciseDate.UTCKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.CapacityKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.CapacityMbKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.AvailableKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.AvailableMbKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.PercentageUsedKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.OSTypeKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.OSVersionKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.OSBuildKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.SerialNumberKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.UDIDKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.InitialEntryDateKey + PreciseDate.EpochKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.InitialEntryDateKey + PreciseDate.UTCKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.PhoneNumberKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.IPAddressKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.WifiMacAddressKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.BluetoothMacAddressKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ModemFirmwareKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ModelKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ModelIdentifierKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ModelNumberKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ModelDisplayKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.DeviceOwnershipLevelKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastEnrollmentKey + PreciseDate.EpochKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastEnrollmentKey + PreciseDate.UTCKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ManagedKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.SupervisedKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ExchangeActiveSyncDeviceIdentifierKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.SharedKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.TetheredKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.BatteryLevelKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.BluetoothCapableKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.DeviceLocatorServiceEnabledKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.DoNotDisturbEnabledKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.CloudBackupEnabledKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastCloudBackupDateKey + PreciseDate.EpochKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastCloudBackupDateKey + PreciseDate.UTCKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LocationServicesEnabledKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.ITunesStoreAccountIsActiveKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastBackupTimeKey + PreciseDate.EpochKey])
XCTAssertNotNil(encodedObject?[MobileDeviceGeneral.LastBackupTimeKey + PreciseDate.UTCKey])
}
}
|
mit
|
f658702cf647dd5a141ea5e7c37971ab
| 58.552529 | 114 | 0.767331 | 5.2111 | false | false | false | false |
adamdebono/SwiftConstraints
|
Source/SwiftConstraints.swift
|
1
|
13219
|
import UIKit
/// Protocol for which constraints can be used with
public protocol AutoLayoutConstrained: class {
func addConstraint(_ constraint: NSLayoutConstraint)
}
// MARK: - Classes which conform to AutoLayoutConstrained
extension UIView: AutoLayoutConstrained {
public var safeConstraint: AutoLayoutConstrained {
if #available(iOS 11.0, tvOS 11.0, *) {
return self.safeAreaLayoutGuide
} else {
return self
}
}
}
@available(iOS 9.0, tvOS 9.0, *)
extension UILayoutGuide: AutoLayoutConstrained {
public func addConstraint(_ constraint: NSLayoutConstraint) {
self.owningView?.addConstraint(constraint)
}
}
// MARK: - Functionality
public extension AutoLayoutConstrained {
/// Adds a constraint to a subview.
///
/// This will order the views in the constraint so that a positive constant
/// will move towards the centre of the superview.
///
/// - parameter item: The other item participating in the constraint
/// - parameter attribute: The attribute of both views participating in the
/// constraint
/// - parameter relatedBy: The relation between the two attributes
/// - parameter multiplier: The multiplier applied to the constant
/// - parameter constant: The offset of item from the parent view
///
/// - returns: The added layout constraint
@discardableResult
func addConstraint(toItem item: AutoLayoutConstrained, attribute: NSLayoutConstraint.Attribute, relatedBy: NSLayoutConstraint.Relation = .equal, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
var firstView, secondView: AutoLayoutConstrained
switch attribute {
case .top, .leading, .centerX, .centerY:
firstView = item
secondView = self
default:
firstView = self
secondView = item
}
let constraint = NSLayoutConstraint(item: firstView, attribute: attribute, relatedBy: relatedBy, toItem: secondView, attribute: attribute, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.addConstraint(constraint)
return constraint
}
/// Adds constraints to make a subview fill the superview.
///
/// This adds leading, trailing, top and bottom constraints. The constant
/// specifies a padding on all sides, with positive values going inwards.
///
/// - parameter item: The other item participating in the constraint
/// - parameter constant: The amount of padding from the parent view
///
/// - returns: The added layout constraints
@discardableResult
func addConstraints(fillView item: AutoLayoutConstrained, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
constraints.append(self.addConstraint(toItem: item, attribute: .leading, constant: constant, priority: priority))
constraints.append(self.addConstraint(toItem: item, attribute: .trailing, constant: constant, priority: priority))
constraints.append(self.addConstraint(toItem: item, attribute: .top, constant: constant, priority: priority))
constraints.append(self.addConstraint(toItem: item, attribute: .bottom, constant: constant, priority: priority))
return constraints
}
/// Adds a constraint to two subviews.
///
/// This will order the views in the constraint so that a positive constant
/// will move the second subview in an inwards direction relative to the
/// first.
///
/// - parameter firstItem: The first item participating in the constraint
/// - parameter secondItem: the second item participating in the constraint
/// - parameter attribute: The attribute of both views participating in the
/// constraint
/// - parameter relatedBy: The relation between the two attributes
/// - parameter multiplier: The multiplier applied to the constant
/// - parameter constant: The offset of both participating view from each
/// other's attribute
///
/// - returns: The added layout constraint
@discardableResult
func addConstraint(withItems firstItem: AutoLayoutConstrained, andItem secondItem: AutoLayoutConstrained, attribute: NSLayoutConstraint.Attribute, relatedBy: NSLayoutConstraint.Relation = .equal, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
var firstView, secondView: AutoLayoutConstrained
switch attribute {
case .top, .left:
firstView = secondItem
secondView = firstItem
default:
firstView = firstItem
secondView = secondItem
}
let constraint = NSLayoutConstraint(item: firstView, attribute: attribute, relatedBy: relatedBy, toItem: secondView, attribute: attribute, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.addConstraint(constraint)
return constraint
}
/// Adds a constraint between two subviews.
///
/// This will order the views in the constraint so that a positive constant
/// will move both subviews apart.
///
/// - parameter item: The first item participating in the constraint
/// - parameter toItem: The second item participating in the constraint
/// - parameter axis: The axis which the items are aligned by
/// - parameter relatedBy: The relation between the attributes
/// - parameter multipler: The multiplier applied to the constant
/// - parameter constant: The space between the views
///
/// - returns: The added layout constraint
@discardableResult
func addConstraint(betweenItems item: AutoLayoutConstrained, toItem: AutoLayoutConstrained, axis: NSLayoutConstraint.Axis, relatedBy: NSLayoutConstraint.Relation = .equal, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
var firstAttribute, secondAttribute: NSLayoutConstraint.Attribute
switch axis {
case .horizontal:
firstAttribute = .left
secondAttribute = .right
case .vertical:
firstAttribute = .top
secondAttribute = .bottom
}
let constraint = NSLayoutConstraint(item: toItem, attribute: firstAttribute, relatedBy: relatedBy, toItem: item, attribute: secondAttribute, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.addConstraint(constraint)
return constraint
}
/// Add a constraint related to the view itself.
///
/// By default, this will use .notAnAttribute for the second item, which
/// behaves as setting the first attribute to the constant.
///
/// - parameter attribute: The attribute of the object to apply
/// - parameter toAttribute: The second attribute of the object to apply
/// - parameter relatedBy: The relation between the attributes
/// - parameter multiplier: The multipler applied to the constant
/// - parameter constant: The constant applied to the constraint
///
/// - returns: The added layout constraint
@discardableResult
func addConstraint(toSelf attribute: NSLayoutConstraint.Attribute, toAttribute: NSLayoutConstraint.Attribute = .notAnAttribute, relatedBy: NSLayoutConstraint.Relation = .equal, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> NSLayoutConstraint {
let toItem: AutoLayoutConstrained? = toAttribute == .notAnAttribute ? nil : self
let constraint = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relatedBy, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.addConstraint(constraint)
return constraint
}
/// Add constraints where all the items have the same dimension across an
/// axis.
///
/// - parameter items: The items to match dimensions on
/// - parameter axis: The axis to match dimensions on
///
/// - returns: The added layout constraints
@discardableResult
func addConstraints(equalDimensions items: [AutoLayoutConstrained], axis: NSLayoutConstraint.Axis, priority: UILayoutPriority = .required) -> [NSLayoutConstraint] {
guard let firstView = items.first else {
return []
}
let attribute: NSLayoutConstraint.Attribute
switch axis {
case .horizontal:
attribute = .width
case .vertical:
attribute = .height
}
var constraints: [NSLayoutConstraint] = []
for item in items {
if item !== firstView {
constraints.append(self.addConstraint(withItems: firstView, andItem: item, attribute: attribute, relatedBy: .equal, multiplier: 1, constant: 0, priority: priority))
}
}
return constraints
}
/// Add constraints where all the items are aligned to an attribute.
///
/// - parameter items: The items to align
/// - parameter attribute: The attribute to align the items to
///
/// - returns: The added layout constraints
@discardableResult
func addConstraints(alignItems items: [AutoLayoutConstrained], attribute: NSLayoutConstraint.Attribute, priority: UILayoutPriority = .required) -> [NSLayoutConstraint] {
guard let firstView = items.first else {
return []
}
var constraints: [NSLayoutConstraint] = []
for item in items {
if item !== firstView {
constraints.append(self.addConstraint(withItems: firstView, andItem: item, attribute: attribute, relatedBy: .equal, multiplier: 1, constant: 0, priority: priority))
}
}
return constraints
}
/// Add constraints to equally space subviews in a superview.
///
/// The constant will determine the spacing between each item. The leftView
/// and rightView, if given, will be used to align the left-most and right-
/// most items to.
///
/// - parameter items: The items to add space between
/// - parameter axis: The axis to align items on
/// - parameter leftView: The left view (or nil) to align the left-most
/// item to
/// - parameter rightView: The right view (or nil) to align the right-most
/// item to
/// - parameter constant: The amount of space between the views
///
/// - returns: The added layout constraints
@discardableResult
func addConstraints(equallySpaced items: [AutoLayoutConstrained], axis: NSLayoutConstraint.Axis, leftView: AutoLayoutConstrained? = nil, rightView: AutoLayoutConstrained? = nil, constant: CGFloat = 0, priority: UILayoutPriority = .required) -> [NSLayoutConstraint] {
guard let firstView = items.first, let lastView = items.last else {
return []
}
var constraints: [NSLayoutConstraint] = []
if let leftView = leftView {
constraints.append(self.addConstraint(betweenItems: leftView, toItem: firstView, axis: axis, relatedBy: .equal, multiplier: 1, constant: constant, priority: priority))
} else {
let attribute: NSLayoutConstraint.Attribute
switch axis {
case .horizontal:
attribute = .leading
case .vertical:
attribute = .top
}
constraints.append(self.addConstraint(toItem: firstView, attribute: attribute, relatedBy: .equal, multiplier: 1, constant: constant, priority: priority))
}
if let rightView = rightView {
constraints.append(self.addConstraint(betweenItems: lastView, toItem: rightView, axis: axis, relatedBy: .equal, multiplier: 1, constant: constant, priority: priority))
} else {
let attribute: NSLayoutConstraint.Attribute
switch axis {
case .horizontal:
attribute = .trailing
case .vertical:
attribute = .bottom
}
constraints.append(self.addConstraint(toItem: lastView, attribute: attribute, relatedBy: .equal, multiplier: 1, constant: constant, priority: priority))
}
var previousView: AutoLayoutConstrained? = nil
for item in items {
if let previousView = previousView {
constraints.append(self.addConstraint(betweenItems: previousView, toItem: item, axis: axis, relatedBy: .equal, multiplier: 1, constant: constant, priority: priority))
}
previousView = item
}
return constraints
}
}
|
mit
|
5147481c6958ba9b09c4e80144e2b3b3
| 45.545775 | 311 | 0.653529 | 5.430978 | false | false | false | false |
thelukester92/swift-engine
|
swift-engine/Game/Systems/PlayerOutputSystem.swift
|
1
|
1292
|
//
// PlayerOutputSystem.swift
// swift-engine
//
// Created by Luke Godfrey on 8/11/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import LGSwiftEngine
class PlayerOutputSystem: LGSystem
{
var entity: LGEntity!
var player: Player!
var sprite: LGSprite!
var body: LGPhysicsBody!
var animatable: LGAnimatable!
override func accepts(entity: LGEntity) -> Bool
{
return entity.has(Player) && entity.has(LGSprite) && entity.has(LGPhysicsBody)
}
override func add(entity: LGEntity)
{
self.entity = entity
player = entity.get(Player)
sprite = entity.get(LGSprite)
body = entity.get(LGPhysicsBody)
animatable = entity.get(LGAnimatable)
}
override func update()
{
let vel = body.velocity
if let follower = entity.get(LGFollower)
{
if let followingBody = follower.following?.get(LGPhysicsBody)
{
switch follower.followerType
{
case .Velocity(let lastVelocity):
vel.x -= lastVelocity.x
vel.y -= lastVelocity.y
case .Position:
break
}
}
}
if vel.y != 0
{
animatable.gotoAnimation("fall")
}
else if vel.x != 0
{
animatable.gotoAnimation("walk")
}
else
{
animatable.gotoAnimation("idle")
}
if vel.x != 0
{
sprite.scale.x = vel.x > 0 ? 1 : -1
}
}
}
|
mit
|
ee5ed9b022ce9b829be71c2a3b0d0c36
| 17.197183 | 80 | 0.646285 | 2.943052 | false | false | false | false |
cuzv/PullToRefresh
|
Sources/TopRefreshContainerView.swift
|
2
|
9345
|
//
// TopRefreshContainerView.swift
// PullToRefresh
//
// Created by Shaw on 6/17/15.
// Copyright © 2015 ReadRain. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
// MARK: - Const
public let DefaultDragToTriggerOffset: CGFloat = 80.0
// MARK: - TopRefreshContainerView
open class TopRefreshContainerView: RefreshContainerView, RefreshContainerViewSubclassDelegate {
open var scrollToTopAfterEndRefreshing: Bool = true
override open var state: RefreshContainerViewState {
didSet {
let previousState: RefreshContainerViewState = oldValue
if state == previousState {
return
}
setNeedsLayout()
layoutIfNeeded()
switch state {
case .triggered:
fallthrough
case .none:
resetScrollViewContentInsetWithCompletion(nil, animated: scrollToTopAfterEndRefreshing)
case .loading:
setScrollViewContentInsetForLoadingAnimated(true)
if previousState == .triggered {
previousContentHeight = scrollView.contentSize.height
previousContentOffY = scrollView.contentOffset.y
actionHandler?(scrollView)
}
}
}
}
private var automaticallyTurnOffAdjustsScrollViewInsetsWhenTranslucentNavigationBar: Bool = true
private var dragToTriggerOffset: CGFloat = DefaultDragToTriggerOffset
private var previousContentOffY: CGFloat = 0.0
private var previousContentHeight: CGFloat = 0.0
// MARK: Initializers
override init(height: CGFloat, scrollView: UIScrollView, pullToRefreshType: PullToRefreshType) {
super.init(height: height, scrollView: scrollView, pullToRefreshType: pullToRefreshType)
}
convenience init(height: CGFloat, scrollView: UIScrollView) {
self.init(height: height, scrollView: scrollView, pullToRefreshType: .loosenRefresh)
}
override init(frame: CGRect) {
fatalError("init(frame:) has not been implemented, use init(height:scrollView)")
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented, use init(height:scrollView)")
}
#if DEBUG
deinit {
debugPrint("\(#file):\(#line):\(type(of: self)):\(#function)")
}
#endif
// MARK: - Public override
override open func didMoveToSuperview() {
super.didMoveToSuperview()
if !automaticallyTurnOffAdjustsScrollViewInsetsWhenTranslucentNavigationBar {
return
}
guard let firstReponderViewController = firstResponderViewController else {
return
}
guard let navigationBar = firstReponderViewController.navigationController?.navigationBar else {
return
}
if navigationBar.isTranslucent &&
scrollView.contentInsetAdjustmentBehavior != .never &&
scrollView.superview == firstReponderViewController.view
{
scrollView.contentInsetAdjustmentBehavior = .never
var bottomAddition: CGFloat = 0
if let tabBar = firstReponderViewController.tabBarController?.tabBar , !tabBar.isHidden {
bottomAddition = tabBar.bounds.height
}
scrollView.contentInset = UIEdgeInsets(
top: scrollView.contentInset.top + navigationBar.frame.maxY,
left: scrollView.contentInset.left,
bottom: scrollView.contentInset.bottom + bottomAddition,
right: scrollView.contentInset.right
)
}
}
// MARK: - RefreshContainerViewSubclassDelegate
internal func resetFrame() -> Void {
let height = bounds.height
let width = scrollView.bounds.width
var newFrame = CGRect(x: -externalContentInset.left, y: -height, width: width, height: height)
if preserveContentInset {
newFrame = CGRect(x: 0.0, y: -height - externalContentInset.top, width: width, height: height)
}
frame = newFrame
}
internal func didSetEnable(_ enable: Bool) {
isHidden = !enable
}
// MARK: Observing
internal func observeValue(forContentInset inset: UIEdgeInsets) -> Void {
let doSomething: () -> Void = {
self.externalContentInset = inset
self.resetFrame()
}
guard let bottomRefreshContainerView = scrollView.bottomRefreshContainerView else {
doSomething()
return
}
if bottomRefreshContainerView.state == .none {
doSomething()
}
}
internal func scrollViewDidScroll(toContentOffSet offSet: CGPoint) -> Void {
if state == .loading {
var loadingInset = externalContentInset
var top = loadingInset.top + bounds.height
if isScrollViewIsTableViewAndHaveSections() &&
scrollView.contentOffset.y > -bounds.height {
if scrollView.contentOffset.y >= 0 {
top = loadingInset.top
} else {
top = abs(scrollView.contentOffset.y)
}
}
loadingInset.top = top
setScrollViewContentInset(loadingInset, forLoadingAnimated: false)
} else {
let dragging = -offSet.y - externalContentInset.top
if !scrollView.isDragging && state == .triggered {
changeState(.loading)
} else if dragging >= dragToTriggerOffset && scrollView.isDragging && state == .none {
changeState(.triggered)
} else if dragging < dragToTriggerOffset && state != .none {
changeState(.none)
}
if dragging >= 0 && state != .loading {
var progress: CGFloat = dragging * 1.0 / dragToTriggerOffset * 1.0
if progress > 1.0 {
progress = 1.0
}
self.delegate?.refreshContainerView?(self, didChangeTriggerStateProgress: progress)
}
}
}
// MARK: Refreshing
open func beginRefreshing() -> Void {
if !enable {
return
}
if state != .none {
return
}
changeState(.triggered)
DispatchQueue.main.async(execute: { () -> Void in
self.scrollView.setContentOffset(CGPoint(x: self.scrollView.contentOffset.x, y: -self.frame.height - self.externalContentInset.top), animated: true)
})
changeState(.loading)
}
open func endRefreshing() -> Void {
if state == .none {
return
}
changeState(.none)
if !scrollToTopAfterEndRefreshing {
let nowContentHeight = scrollView.contentSize.height
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: nowContentHeight - previousContentHeight + previousContentOffY)
return
}
let originalContentOffset = CGPoint(x: -externalContentInset.left, y: -externalContentInset.top)
DispatchQueue.main.async { () -> Void in
self.scrollView.setContentOffset(originalContentOffset, animated: false)
}
}
// MARK: - Private
private func isScrollViewIsTableViewAndHaveSections() -> Bool {
if let tableView = scrollView as? UITableView {
return tableView.numberOfSections > 1 ? true : false
}
return false
}
// MARK: UIScrollView
private func setScrollViewContentInsetForLoadingAnimated(_ animated: Bool) -> Void {
var loadingInset = externalContentInset
loadingInset.top += bounds.height
setScrollViewContentInset(loadingInset, forLoadingAnimated: animated)
}
private func setScrollViewContentInset(_ inset: UIEdgeInsets, forLoadingAnimated animated: Bool) -> Void {
setScrollViewContentInset(inset, forLoadingAnimated: animated, completion: nil)
}
}
|
mit
|
60b0f9e8bc9443115d6f6b068a12be41
| 35.787402 | 160 | 0.620826 | 5.40428 | false | false | false | false |
nmartinson/Bluetooth-Camera-Controller
|
BLE Test/TimeLapseController.swift
|
1
|
4178
|
//
// ControllerViewController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 11/25/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import UIKit
class TimeLapseController: UIViewController, UITextFieldDelegate {
var delegate:UARTViewControllerDelegate?
private let buttonPrefix = "!B"
@IBOutlet weak var minIntervalLabel: UILabel!
@IBOutlet weak var shutterButton: UIButton!
@IBOutlet weak var exposureLabel: UILabel!
@IBOutlet weak var exposureTextField: UITextField!
@IBOutlet weak var intervalLabel: UILabel!
@IBOutlet weak var intervalText: UITextField!
@IBOutlet weak var framesLabel: UILabel!
@IBOutlet weak var framesText: UITextField!
@IBOutlet weak var framesFired: UILabel!
var timer:NSTimer!
var shutterSpeed:Double = 1/60
var interval:Double = 15
var frames:Int = 100
var isShooting = false
var framesShot = 0
override func viewDidLoad() {
super.viewDidLoad()
var appDelegate = UIApplication.sharedApplication().delegate as! BLEAppDelegate
delegate = appDelegate.mainViewController!
intervalText.delegate = self
self.title = "Time Lapse"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
// Stop updates if we're returning to main view
timer.invalidate()
if self.isMovingFromParentViewController() {
//Stop receiving app active notification
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Shutter Button
@IBAction func shutterButtonPressed(sender:UIButton) {
if !isShooting
{
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "fireShutter", userInfo: nil, repeats: true)
sender.setTitle("Stop", forState: .Normal)
sender.backgroundColor = UIColor.redColor()
}
else
{
framesShot = 0
timer.invalidate()
sender.setTitle("Start", forState: .Normal)
sender.backgroundColor = UIColor.blueColor()
}
isShooting = !isShooting
}
func fireShutter()
{
framesShot++
if framesShot <= frames
{
framesFired.text = "Frames fired: \(framesShot)"
var str = NSString(string:buttonPrefix + TIMELAPSE + "1" ) // a = basic mode
var data = NSData(bytes: str.UTF8String, length: str.length)
delegate?.sendData(appendCRC(data))
str = NSString(string:buttonPrefix + TIMELAPSE + "0" ) // a = basic mode
data = NSData(bytes: str.UTF8String, length: str.length)
delegate?.sendData(appendCRC(data))
}
else
{
framesShot = 0
framesFired.text = "Frames fired: \(framesShot)"
timer.invalidate()
shutterButton.setTitle("Start", forState: .Normal)
shutterButton.backgroundColor = UIColor.blueColor()
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == exposureTextField {
shutterSpeed = (textField.text as NSString).doubleValue
exposureLabel.text = "Shutter speed: \(shutterSpeed) s"
}
else if textField == intervalText {
interval = (textField.text as NSString).doubleValue
intervalLabel.text = "Interval between frames: \(interval) s"
}
else if textField == framesText {
if textField.text != ""
{
frames = textField.text.toInt()!
}
framesLabel.text = "# of frames: \(frames)"
}
textField.resignFirstResponder()
return false
}
}
|
bsd-3-clause
|
6746dc5dafe93c198d67e4c29ab0c51e
| 33.254098 | 137 | 0.623025 | 4.961995 | false | false | false | false |
Ucself/JGCache
|
Example/JGCache/ViewController.swift
|
1
|
3938
|
//
// ViewController.swift
// JGCache
//
// Created by 李保君 on 10/31/2017.
// Copyright (c) 2017 李保君. All rights reserved.
//
import UIKit
import JGCache
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId")
switch indexPath.row {
case 0:
cell?.textLabel?.text = "write default"
case 1:
cell?.textLabel?.text = "get default"
case 2:
cell?.textLabel?.text = "remove default"
case 3:
cell?.textLabel?.text = "write for key Li"
case 4:
cell?.textLabel?.text = "get for key Li"
case 5:
cell?.textLabel?.text = "remove for key Li"
default:
break
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let userDefault = UserModel.init()
userDefault.id = "我是default的id"
userDefault.name = "我是default的name"
//写入缓存
if JGCacheManager.default.writeCacheModel(object: userDefault) {
print("👉userDefault write Successful")
}
else {
print("👉userDefault write failure")
}
case 1:
//读取缓存
if let userDefault = JGCacheManager.default.getCacheModel(class: UserModel.self) {
print("👉userDefault get id -> \(userDefault.id);name -> \(userDefault.name)")
}
else {
print("👉userDefault get nil")
}
case 2:
//移除缓存
if JGCacheManager.default.removeCacheModel(class: UserModel.self) {
print("👉userDefault remove Successful")
}
else {
print("👉userDefault remove failure")
}
case 3:
let userLi = UserModel.init()
userLi.id = "我是Li的id"
userLi.name = "我是Li的name"
//写入缓存
if JGCacheManager.default.writeCacheModel(object: userLi, cacheKey:"Li") {
print("👉for key Li write Successful")
}
else {
print("👉for key Li write failure")
}
case 4:
//读取缓存
if let userLi = JGCacheManager.default.getCacheModel(class: UserModel.self, cacheKey:"Li") {
print("👉for key Li get id -> \(userLi.id);name -> \(userLi.name)")
}
else {
print("👉for key Li get nil")
}
case 5:
//移除缓存
if JGCacheManager.default.removeCacheModel(class: UserModel.self, cacheKey:"Li") {
print("👉for key Li remove Successful")
}
else {
print("👉for key Li remove failure")
}
default:
break
}
}
@IBAction func writeButtonClick(_ sender: Any) {
_ = JGCacheManager.default.writeCacheModel(object: UserModel())
}
@IBAction func readButtonClick(_ sender: Any) {
if let user:UserModel = JGCacheManager.default.getCacheModel(class: UserModel.self) {
print("user.id -> \(user.id) \n user.name -> \(user.name)")
}
}
@IBAction func clearButtonClick(_ sender: Any) {
_ = JGCacheManager.default.removeCacheModel(class: UserModel.self)
}
}
|
mit
|
479a6ca4805ce6a57028cb85ea9cb73c
| 29.790323 | 104 | 0.525406 | 4.808564 | false | false | false | false |
Vostro162/VaporTelegram
|
Sources/App/InlineKeyboardButton.swift
|
1
|
3164
|
//
// InlineKeyboardButton.swift
// VaporTelegramBot
//
// Created by Marius Hartig on 08.05.17.
//
//
import Foundation
// This object represents one button of an inline keyboard. You must use exactly one of the optional fields.
public struct InlineKeyboardButton: Button {
// Label text on the button
public let text: String
// ToDo
//public let pay: Bool
// Optional. HTTP url to be opened when button is pressed
public let url: URL?
// Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
public let callbackData: String?
/*
*
* Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field.
* Can be empty, in which case just the bot’s username will be inserted.
* Note: This offers an easy way for users to start using your bot in inline mode when they are currently in a private chat with it.
* Especially useful when combined with switch_pm… actions – in this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen.
*
*/
public let switchInlineQuery: String?
/*
*
* Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty,
* in which case only the bot’s username will be inserted.
* This offers a quick way for the user to open your bot in inline mode in the same chat – good for selecting something from multiple options.
*
*/
public let switchInlineQueryCurrentChat: String?
/*
*
* Optional. Description of the game that will be launched when the user presses the button.
* NOTE: This type of button must always be the first button in the first row.
*
*/
public let callbackGame: CallbackGame?
public init(text: String, url: URL, switchInlineQuery: String? = nil, switchInlineQueryCurrentChat: String? = nil) {
self.text = text
self.url = url
self.callbackData = nil
self.switchInlineQuery = switchInlineQuery
self.switchInlineQueryCurrentChat = switchInlineQueryCurrentChat
self.callbackGame = nil
}
public init(text: String, callbackData: String, switchInlineQuery: String? = nil, switchInlineQueryCurrentChat: String? = nil) {
self.text = text
self.url = nil
self.callbackData = callbackData
self.switchInlineQuery = switchInlineQuery
self.switchInlineQueryCurrentChat = switchInlineQueryCurrentChat
self.callbackGame = nil
}
public init(text: String, callbackGame: CallbackGame, switchInlineQuery: String? = nil, switchInlineQueryCurrentChat: String? = nil) {
self.text = text
self.url = nil
self.callbackData = nil
self.switchInlineQuery = switchInlineQuery
self.switchInlineQueryCurrentChat = switchInlineQueryCurrentChat
self.callbackGame = callbackGame
}
}
|
mit
|
4856afb9314c768dfc05c6726793a661
| 37.888889 | 191 | 0.691111 | 4.618768 | false | false | false | false |
sviatoslav/EndpointProcedure
|
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/ProcedureResult.swift
|
2
|
6171
|
//
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
public enum Pending<T> {
case pending
case ready(T)
public var isPending: Bool {
guard case .pending = self else { return false }
return true
}
public var value: T? {
guard case let .ready(value) = self else { return nil }
return value
}
public init(_ value: T?) {
self = value.pending
}
}
extension Pending where T: Equatable {
static func == (lhs: Pending<T>, rhs: Pending<T>) -> Bool {
switch (lhs, rhs) {
case (.pending, .pending):
return true
case let (.ready(lhsValue), .ready(rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
}
public extension Optional {
var pending: Pending<Wrapped> {
switch self {
case .none:
return .pending
case let .some(value):
return .ready(value)
}
}
}
public protocol ProcedureResultProtocol {
associatedtype Value
var value: Value? { get }
var error: Error? { get }
}
extension Pending where T: ProcedureResultProtocol {
public var success: T.Value? {
return value?.value
}
public var error: Error? {
return value?.error
}
}
public enum ProcedureResult<T>: ProcedureResultProtocol {
case success(T)
case failure(Error)
public var value: T? {
guard case let .success(value) = self else { return nil }
return value
}
public var error: Error? {
guard case let .failure(error) = self else { return nil }
return error
}
}
extension ProcedureResult where T: Equatable {
static func == (lhs: ProcedureResult<T>, rhs: ProcedureResult<T>) -> Bool {
switch (lhs, rhs) {
case let (.success(lhsValue), .success(rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
}
public protocol InputProcedure: ProcedureProtocol {
associatedtype Input
var input: Pending<Input> { get set }
}
public protocol OutputProcedure: ProcedureProtocol {
associatedtype Output
var output: Pending<ProcedureResult<Output>> { get set }
}
public let pendingVoid: Pending<Void> = .ready(())
public let success: ProcedureResult<Void> = .success(())
public let pendingVoidResult: Pending<ProcedureResult<Void>> = .ready(success)
// MARK: - Extensions
public extension OutputProcedure {
func finish(withResult result: ProcedureResult<Output>) {
output = .ready(result)
finish(withError: output.error)
}
}
public extension ProcedureProtocol {
/**
Access the completed dependency Procedure before `self` is
started. This can be useful for transfering results/data between
Procedures.
- parameter dependency: any `Procedure` subclass.
- parameter block: a closure which receives `self`, the dependent
operation, and an array of `ErrorType`, and returns Void.
(The closure is automatically dispatched on the EventQueue
of the receiver, if the receiver is a Procedure or supports the
QueueProvider protocol).
- returns: `self` - so that injections can be chained together.
*/
@discardableResult func inject<Dependency: ProcedureProtocol>(dependency: Dependency, block: @escaping (Self, Dependency, [Error]) -> Void) -> Self {
precondition(dependency !== self, "Cannot inject result of self into self.")
dependency.addWillFinishBlockObserver(synchronizedWith: (self as? QueueProvider)) { [weak self] dependency, errors, _ in
if let strongSelf = self {
block(strongSelf, dependency, errors)
}
}
dependency.addDidCancelBlockObserver { [weak self] _, errors in
if let strongSelf = self {
strongSelf.cancel(withError: ProcedureKitError.dependency(cancelledWithErrors: errors))
}
}
add(dependency: dependency)
return self
}
}
public extension InputProcedure {
@discardableResult func injectResult<Dependency: OutputProcedure>(from dependency: Dependency, via block: @escaping (Dependency.Output) throws -> Input) -> Self {
return inject(dependency: dependency) { procedure, dependency, errors in
// Check if there are any errors first
guard errors.isEmpty else {
procedure.cancel(withError: ProcedureKitError.dependency(finishedWithErrors: errors)); return
}
// Check that we have a result ready
guard let result = dependency.output.value else {
procedure.cancel(withError: ProcedureKitError.requirementNotSatisfied()); return
}
// Check that the result was successful
guard let output = result.value else {
// If not, check for an error
if let error = result.error {
procedure.cancel(withError: ProcedureKitError.dependency(finishedWithErrors: [error]))
}
else {
procedure.cancel(withError: ProcedureKitError.requirementNotSatisfied())
}
return
}
// Given successfull output
do {
procedure.input = .ready(try block(output))
}
catch {
procedure.cancel(withError: ProcedureKitError.dependency(finishedWithErrors: [error]))
}
}
}
@discardableResult func injectResult<Dependency: OutputProcedure>(from dependency: Dependency) -> Self where Dependency.Output == Input {
return injectResult(from: dependency, via: { $0 })
}
@discardableResult func injectResult<Dependency: OutputProcedure>(from dependency: Dependency) -> Self where Dependency.Output == Optional<Input> {
return injectResult(from: dependency) { output in
guard let output = output else {
throw ProcedureKitError.requirementNotSatisfied()
}
return output
}
}
}
|
mit
|
ff55b789cf3c810a3b9b5f9253fac5e6
| 28.380952 | 166 | 0.620583 | 4.916335 | false | false | false | false |
CodePath2017Group4/travel-app
|
RoadTripPlanner/LandingPageViewController.swift
|
1
|
26475
|
//
// LandingPageViewController.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/10/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import CoreLocation
import AFNetworking
import YelpAPI
import CDYelpFusionKit
import Parse
class LandingPageViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
// @IBOutlet weak var tableView: UITableView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pagingView: UIView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var createTripButton: UIButton!
@IBOutlet weak var nearMeButton: UIButton!
@IBOutlet weak var alongTheRouteButton: UIButton!
@IBOutlet weak var currentCity: UILabel!
@IBOutlet weak var currentTemperature: UILabel!
@IBOutlet weak var temperatureImage: UIImageView!
let locationManager = CLLocationManager()
var weather: WeatherGetter!
@IBOutlet weak var gasImageView: UIImageView!
@IBOutlet weak var foodImageView: UIImageView!
@IBOutlet weak var poiImageView: UIImageView!
@IBOutlet weak var shoppingImageView: UIImageView!
@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelThree: UILabel!
@IBOutlet weak var labelFour: UILabel!
//drugstores, deptstores, flowers
//food - bakeries, bagels, coffee, donuts, foodtrucks
//hotels - bedbreakfast, campgrounds, guesthouses. hostels
//thingstodo
//arts - arcades, museums
// active - aquariums, zoos, parks, amusementparks
// nightlife
//poi // publicservicesgovt - civiccenter, landmarks,
//entertainmneet// arts - movietheaters, galleries, theater
// servicestations
let categoriesList = ["auto", "food, restaurant", "publicservicesgovt"/*poi*/,"shopping"/*shopping"*/, "hotels", "arts, active", "nightlife", "arts"]
var selectedType = [String] ()
var businesses: [CDYelpBusiness]!
var trips: [Trip]!
let testData = TestData()
override func viewDidLoad() {
super.viewDidLoad()
createTripButton.layer.cornerRadius = createTripButton.frame.height / 2
nearMeButton.layer.cornerRadius = createTripButton.frame.height / 2
alongTheRouteButton.layer.cornerRadius = createTripButton.frame.height / 2
nearMeButton.isHidden = true
alongTheRouteButton.isHidden = true
// tableView.rowHeight = UITableViewAutomaticDimension
//tableView.estimatedRowHeight = 192
//tableView.separatorStyle = .none
// let tripTableViewCellNib = UINib(nibName: Constants.NibNames.TripTableViewCell, bundle: nil)
// tableView.register(tripTableViewCellNib, forCellReuseIdentifier: Constants.ReuseableCellIdentifiers.TripTableViewCell)
let tripCollectionViewCellNib = UINib(nibName: Constants.NibNames.TripCollectionViewCell, bundle: nil)
collectionView.register(tripCollectionViewCellNib, forCellWithReuseIdentifier: Constants.ReuseableCellIdentifiers.TripCollectionViewCell)
collectionView.delegate = self
collectionView.dataSource = self
nearMeButton.isHidden = true
alongTheRouteButton.isHidden = true
getLocation()
weather = WeatherGetter(delegate: self)
trips = []
loadUpcomingTrips()
//1
//self.scrollView.frame = CGRect(x:0, y:0, width:self.view.frame.width, height:self.view.frame.height)
let scrollViewWidth: CGFloat = self.scrollView.frame.width
let scrollViewHeight: CGFloat = self.scrollView.frame.height
let lodgingImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
lodgingImageTap.numberOfTapsRequired = 1
gasImageView.isUserInteractionEnabled = true
//gasImageView.tag = 4
gasImageView.addGestureRecognizer(lodgingImageTap)
labelOne.text = "Lodging"
let thingsToDoImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
thingsToDoImageTap.numberOfTapsRequired = 1
foodImageView.isUserInteractionEnabled = true
//foodImageView.tag = 5
foodImageView.addGestureRecognizer(thingsToDoImageTap)
labelTwo.text = "Point of Interest"
let nightlifeImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
nightlifeImageTap.numberOfTapsRequired = 1
poiImageView.isUserInteractionEnabled = true
//poiImageView.tag = 6
poiImageView.addGestureRecognizer(nightlifeImageTap)
labelThree.text = "Nightlife"
let entertainmentImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
entertainmentImageTap.numberOfTapsRequired = 1
shoppingImageView.isUserInteractionEnabled = true
//shoppingImageView.tag = 7
shoppingImageView.addGestureRecognizer(entertainmentImageTap)
labelFour.text = "Enterntainment"
self.scrollView.addSubview(pagingView)
let gasImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
gasImageTap.numberOfTapsRequired = 1
gasImageView.isUserInteractionEnabled = true
gasImageView.tag = 0
gasImageView.addGestureRecognizer(gasImageTap)
labelOne.text = "Automotive"
let foodImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
foodImageTap.numberOfTapsRequired = 1
foodImageView.isUserInteractionEnabled = true
let foodImageFromFile = UIImage(named: "food")!
foodImageView.image = foodImageFromFile.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
foodImageView.tintColor = UIColor(red: 22/255, green: 134/255, blue: 36/255, alpha: 1)//.green*/
foodImageView.tag = 1
foodImageView.addGestureRecognizer(foodImageTap)
labelTwo.text = "Food"
let poiImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
poiImageTap.numberOfTapsRequired = 1
poiImageView.isUserInteractionEnabled = true
poiImageView.tag = 2
poiImageView.addGestureRecognizer(poiImageTap)
labelThree.text = "POI"
let shoppingImageTap = UITapGestureRecognizer(target: self, action: #selector(categoryTapped))
shoppingImageTap.numberOfTapsRequired = 1
shoppingImageView.isUserInteractionEnabled = true
shoppingImageView.tag = 3
shoppingImageView.addGestureRecognizer(shoppingImageTap)
labelFour.text = "Shopping"
self.scrollView.addSubview(pagingView)
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.width * 2, height:self.scrollView.frame.height)
self.scrollView.delegate = self
self.pageControl.currentPage = 1
navigationController?.navigationBar.tintColor = Constants.Colors.NavigationBarLightTintColor
let textAttributes = [NSForegroundColorAttributeName:Constants.Colors.NavigationBarLightTintColor]
navigationController?.navigationBar.titleTextAttributes = textAttributes
registerForNotifications()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
// Make the navigation bar completely transparent.
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
fileprivate func loadUpcomingTrips() {
ParseBackend.getTripsForUser(user: PFUser.current()!, areUpcoming: true, onlyConfirmed: true) { (trips, error) in
if error == nil {
if let t = trips {
log.info("Upcoming trip count \(t.count)")
self.trips = t
DispatchQueue.main.async {
//self.tableView.reloadData()
self.collectionView.reloadData()
}
}
} else {
log.error("Error loading upcoming trips: \(error!)")
}
}
}
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(tripWasModified(notification:)),
name: Constants.NotificationNames.TripModifiedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(tripDeleted(notification:)),
name: Constants.NotificationNames.TripDeletedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(tripCreated(notification:)),
name: Constants.NotificationNames.TripCreatedNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func tripCreated(notification: NSNotification) {
// Reload trips
loadUpcomingTrips()
}
func tripWasModified(notification: NSNotification) {
let info = notification.userInfo
let trip = info!["trip"] as! Trip
let tripId = trip.objectId
// Find the trip in the trips array.
log.info("Trip with id: \(String(describing: tripId)) has been modified.")
let matchingTrips = trips.filter { (trip) -> Bool in
return trip.objectId == tripId
}
if matchingTrips.count > 0 {
let match = matchingTrips.first!
let index = trips.index(of: match)
guard let idx = index else { return }
// replace the trip with the new trip
trips[idx] = trip
// reload the trips
collectionView.reloadData()
}
}
func tripDeleted(notification: NSNotification) {
// Reload trips
loadUpcomingTrips()
}
func categoryTapped(_ sender: UITapGestureRecognizer) {
let selectedIndex = sender.view?.tag
print("selectedIndex ===== > \(selectedIndex)")
let selectedImg = sender.view
if !selectedType.isEmpty {
//if selectedTypes.contains(categoriesList[selectedIndex!]) {
if categoriesList.contains(selectedType[0]) {
print("in first if")
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
gasImageView.alpha = 1
foodImageView.alpha = 1
poiImageView.alpha = 1
shoppingImageView.alpha = 1
createTripButton.isHidden = selectedType.isEmpty//false
nearMeButton.isHidden = !selectedType.isEmpty//true
alongTheRouteButton.isHidden = !selectedType.isEmpty//true
selectedType.removeAll()
}
else {
gasImageView.alpha = 0.5
foodImageView.alpha = 0.5
poiImageView.alpha = 0.5
shoppingImageView.alpha = 0.5
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
selectedType.removeAll()
selectedType.append(categoriesList[selectedIndex!])
}
}
else {
if gasImageView.tag != selectedIndex {
gasImageView.alpha = 0.5
}
if foodImageView.tag != selectedIndex {
foodImageView.alpha = 0.5
}
if poiImageView.tag != selectedIndex {
poiImageView.alpha = 0.5
}
if shoppingImageView.tag != selectedIndex {
shoppingImageView.alpha = 0.5
}
createTripButton.isHidden = selectedType.isEmpty//false
nearMeButton.isHidden = !selectedType.isEmpty//true
alongTheRouteButton.isHidden = !selectedType.isEmpty//true
selectedImg?.transform = CGAffineTransform(scaleX: 1,y: 1);
selectedImg?.alpha = 0.0
UIView.beginAnimations("button", context:nil)
UIView.setAnimationDuration(0.5)
selectedImg?.transform = CGAffineTransform(scaleX: 1.1,y: 1.1);
selectedImg?.alpha = 1.0
UIView.commitAnimations()
selectedType.append(categoriesList[selectedIndex!])
}
print("selectedType \(selectedType)")
}
func getLocation() {
guard CLLocationManager.locationServicesEnabled() else {
print("Location services are disabled on your device. In order to use this app, go to " +
"Settings → Privacy → Location Services and turn location services on.")
return
}
let authStatus = CLLocationManager.authorizationStatus()
guard authStatus == .authorizedWhenInUse else {
switch authStatus {
case .denied, .restricted:
print("This app is not authorized to use your location. In order to use this app, " +
"go to Settings → GeoExample → Location and select the \"While Using " +
"the App\" setting.")
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
default:
print("Oops! Shouldn't have come this far.")
}
return
}
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
// MARK: - Utility methods
// -----------------------
func showSimpleAlert(title: String, message: String) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)
let okAction = UIAlertAction(
title: "OK",
style: .default,
handler: nil
)
alert.addAction(okAction)
present(
alert,
animated: true,
completion: nil
)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("segue.identifier \(segue.identifier!)")
if segue.identifier! == "NearMe" {
let mapViewController = segue.destination as! MapViewController
mapViewController.businesses = businesses
mapViewController.searchTerm = selectedType
}
else if segue.identifier! == "CreateTrip" {
let createTripViewController = segue.destination as! CreateTripViewController
//createTripViewController.businesses = businesses
//createTripViewController.searchBar = searchBar
//mapViewController.filters = filters
// mapViewController.filters1 = filters1*/
}
else {
let createTripViewController = segue.destination as! CreateTripViewController
/* if let cell = sender as? BusinessCell {
let indexPath = tableView.indexPath(for: cell)
let selectedBusiness = businesses[(indexPath?.row)!]
if let detailViewController = segue.destination as? DetailViewController {
detailViewController.business = selectedBusiness
detailViewController.filters = filters
// detailViewController.filters1 = filters1
}
}*/
}
}
@IBAction func onCreateTrip(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//let createTripViewController = storyBoard.instantiateViewController(withIdentifier: "CreateTrip") as! UINavigationController
// self.navigationController?.pushViewController(createTripViewController.topViewController!, animated: true)
}
@IBAction func onNearMe(_ sender: Any) {
performSearch(selectedType)
}
@IBAction func onAlongTheRoute(_ sender: Any) {
}
final func performSearch(_ term: [String]) {
if !term.isEmpty {
YelpFusionClient.shared.searchQueryWith(location: locationManager.location!, term: term[0], completionHandler: {(businesses: [CDYelpBusiness]?, error: Error?) -> Void in
self.businesses = businesses
})
// working
/*YelpFusionClient.sharedInstance.searchQueryWith(location: locationManager.location!, term: term[0], completionHandler: {(businesses: [YLPBusiness]?, error: Error?) -> Void in
self.businesses = businesses
})*/
}
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension LandingPageViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trips.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// if indexPath.row == 0 || indexPath.row == 2 {
// return 30.0
// }
return 192
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// switch indexPath.row {
// case 0, 2 : let headerCell = tableView.dequeueReusableCell(withIdentifier: "TripHeaderCell", for: indexPath) as! UITableViewCell
// return headerCell
//
// case 1, 3 : let tripCell = tableView.dequeueReusableCell(withIdentifier: "TripCell", for: indexPath) as! TripCell
// tripCell.selectionStyle = .none
//
// return tripCell
// default: return UITableViewCell()
//
//
// }
let tripCell = tableView.dequeueReusableCell(withIdentifier: Constants.ReuseableCellIdentifiers.TripTableViewCell, for: indexPath) as! TripTableViewCell
tripCell.trip = trips[indexPath.row]
return tripCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Show the trip details view controller.
let trip = trips[indexPath.row]
log.info("Selected trip \(trip.name ?? "none")")
let tripDetailsVC = TripDetailsViewController.storyboardInstance()
tripDetailsVC?.trip = trip
navigationController?.pushViewController(tripDetailsVC!, animated: true)
}
}
// MARK: - CLLocationManagerDelegate
extension LandingPageViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last!
weather.getWeatherByCoordinates(latitude: newLocation.coordinate.latitude,
longitude: newLocation.coordinate.longitude)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
DispatchQueue.main.async() {
self.showSimpleAlert(title: "Can't determine your location",
message: "The GPS and other location services aren't responding.")
}
print("locationManager didFailWithError: \(error)")
}
}
// MARK: - WeatherGetterDelegate
extension LandingPageViewController: WeatherGetterDelegate {
func didGetWeather(weather: Weather) {
DispatchQueue.main.async {
self.currentCity.text = weather.city
self.currentTemperature.text = "\(Int(round(weather.tempFahrenheit)))° F"
let weatherIconID = weather.weatherIconID
if UIImage(named: weatherIconID) == nil {
let iconURL = URL(string: "http://openweathermap.org/img/w/\(weatherIconID)")
self.temperatureImage.setImageWith(iconURL!)
} else {
self.temperatureImage.image = UIImage(named: weatherIconID)
}
}
}
func didNotGetWeather(error: NSError) {
DispatchQueue.main.async() {
self.showSimpleAlert(title: "Can't get the weather", message: "The weather service isn't responding.")
}
}
}
// MARK: - UIScrollViewDelegate
extension LandingPageViewController : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
// Test the offset and calculate the current page after scrolling ends
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
// Change the indicator
self.pageControl.currentPage = Int(currentPage)
print("self.pageControl.currentPage ---=== \(self.pageControl.currentPage)")
// Change the text accordingly
if Int(currentPage) == 0{
//textView.text = "Sweettutos.com is your blog of choice for Mobile tutorials"
gasImageView?.image = UIImage(named: "gasstation")
labelOne.text = "Automotive"
gasImageView.tag = 0
foodImageView?.image = UIImage(named: "food")
let foodImageFromFile = UIImage(named: "food")!
foodImageView.image = foodImageFromFile.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
foodImageView.tintColor = UIColor(red: 22/255, green: 134/255, blue: 36/255, alpha: 1)//.green*/
labelTwo.text = "Food"
foodImageView.tag = 1
poiImageView.tag = 2
poiImageView?.image = UIImage(named: "poi")
labelThree.text = "POI"
poiImageView.tag = 2
shoppingImageView?.image = UIImage(named: "shopping")
labelFour.text = "Shopping"
shoppingImageView.tag = 3
}else if Int(currentPage) == 1{
gasImageView?.image = UIImage(named: "lodging")
labelOne.text = "Lodging"
gasImageView.tag = 4
foodImageView?.image = UIImage(named: "thingstodo")
labelTwo.text = "Things to Do"
foodImageView.tag = 5
poiImageView?.image = UIImage(named: "nightlife")
labelThree.text = "Nightlife"
poiImageView.tag = 6
shoppingImageView?.image = UIImage(named: "entertainment")
labelFour.text = "Enterntainment"
shoppingImageView.tag = 7
}
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension LandingPageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.ReuseableCellIdentifiers.TripCollectionViewCell, for: indexPath) as! TripCollectionViewCell
cell.backgroundColor = UIColor.darkGray
cell.trip = trips[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if trips.isEmpty {
print("trips == \(trips.count)")
let messageLabel = UILabel(frame: CGRect(x: 0,y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
messageLabel.text = "You dont have any upcoming trips."
messageLabel.textColor = UIColor.gray
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
self.collectionView.backgroundView = messageLabel
self.collectionView.backgroundView?.isHidden = false
} else {
self.collectionView.backgroundView?.isHidden = true
}
return trips.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
log.info("Selected cell at \(indexPath)")
let trip = trips[indexPath.row]
log.info("Selected trip \(trip.name ?? "none")")
let tripDetailsVC = TripDetailsViewController.storyboardInstance()
tripDetailsVC?.trip = trip
navigationController?.pushViewController(tripDetailsVC!, animated: true)
}
}
|
mit
|
e60197ce99c0ebf4f9b547a1716a209d
| 37.919118 | 188 | 0.609144 | 5.496366 | false | false | false | false |
huaf22/zhihuSwiftDemo
|
zhihuSwiftDemo/Views/WLYPullToRefreshPlugin.swift
|
1
|
4712
|
//
// WLYPullToRefreshPlugin.swift
// zhihuSwiftDemo
//
// Created by Afluy on 19/12/2016.
// Copyright © 2016 helios. All rights reserved.
//
import Foundation
import UIKit
protocol WLYPullToRefreshPluginDelegate {
func pullToRefreshScrollViewDidPull(scrollView: UIScrollView);
func pullToRefreshScrollViewDidTrigger(scrollView: UIScrollView);
func pullToRefreshScrollViewDidStopRefresh(scrollView: UIScrollView);
func pullToRefreshScrollViewDidScroll(scrollView: UIScrollView);
}
class WLYPullToRefreshPlugin: NSObject {
// MARK: Variables
private let ContentOffsetKeyPath = "contentOffset"
private let ContentSizeKeyPath = "contentSize"
private var KVOContext = "PullToRefreshKVOContext"
var triggerRefreshHeigh: CGFloat = 50.0
var delegate: WLYPullToRefreshPluginDelegate?
private enum PullToRefreshState {
case pulling
case triggered
case refreshing
case stop
}
private var scrollView: UIScrollView!
private var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero
private var state: PullToRefreshState = .pulling {
didSet {
if self.state == oldValue {
return
}
WLYLog.d("state: \(state)")
switch self.state {
case .stop:
self.scrollViewDidStopRefresh()
case .refreshing:
self.scrollViewDidRefresh()
case .pulling:
self.scrollViewDidPull()
case .triggered:
self.scrollViewDidTrigger()
}
}
}
init(_ scrollView: UIScrollView) {
super.init()
self.scrollView = scrollView
self.addObserver()
}
deinit {
self.removeObserver()
}
// MARK:- Private Methods
func pullToRefreshEnd(result success: Bool) {
self.scrollViewDidStopRefresh()
}
// MARK:- Public Methods
private func addObserver() {
self.scrollView.addObserver(self, forKeyPath: ContentOffsetKeyPath, options: .initial, context: &KVOContext)
// self.scrollView.addObserver(self, forKeyPath: ContentSizeKeyPath, options: .initial, context: &KVOContext)
}
private func removeObserver() {
self.scrollView.removeObserver(self, forKeyPath: ContentOffsetKeyPath, context: &KVOContext)
// self.scrollView.removeObserver(self, forKeyPath: ContentSizeKeyPath, context: &KVOContext)
}
private func scrollViewDidRefresh() {
scrollViewInsets = self.scrollView.contentInset
var insets = self.scrollView.contentInset
insets.top += self.triggerRefreshHeigh
//self.tableView.bounces = false
}
private func scrollViewDidStopRefresh() {
self.state = .pulling
//self.tableView.bounces = true
}
private func scrollViewDidPull() {
if let delegate = self.delegate {
delegate.pullToRefreshScrollViewDidPull(scrollView: scrollView)
}
}
private func scrollViewDidTrigger() {
if let delegate = self.delegate {
delegate.pullToRefreshScrollViewDidTrigger(scrollView: scrollView)
}
}
// MARK:- KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (context == &KVOContext && keyPath == ContentOffsetKeyPath) {
// super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
let offsetY = scrollView.contentOffset.y
if offsetY <= -self.scrollView.contentInset.top {
if offsetY < -self.scrollView.contentInset.top - self.triggerRefreshHeigh {
if scrollView.isDragging == false && self.state != .refreshing { //release the finger
self.state = .refreshing //startAnimating
} else if self.state != .refreshing { //reach the threshold
self.state = .triggered
}
} else if self.state == .triggered {
//starting point, start from pulling
self.state = .pulling
}
if self.state == .pulling {
self.scrollViewDidPull()
}
}
if let delegate = self.delegate {
delegate.pullToRefreshScrollViewDidScroll(scrollView: scrollView)
}
return
}
}
}
|
mit
|
a38cb17a3d6519125b6c95aa040fdb61
| 31.047619 | 151 | 0.599873 | 5.497083 | false | false | false | false |
Pencroff/ai-hackathon-2017
|
IOS APP/Pods/Cloudinary/Cloudinary/Features/ManagementApi/Results/CLDRenameResult.swift
|
1
|
6964
|
//
// CLDRenameResult.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
@objc open class CLDRenameResult: CLDBaseResult {
// MARK: - Getters
open var publicId: String? {
return getParam(.publicId) as? String
}
open var format: String? {
return getParam(.format) as? String
}
open var version: String? {
guard let version = getParam(.version) else {
return nil
}
return String(describing: version)
}
open var resourceType: String? {
return getParam(.resourceType) as? String
}
open var type: String? {
return getParam(.urlType) as? String
}
open var createdAt: String? {
return getParam(.createdAt) as? String
}
open var length: Double? {
return getParam(.length) as? Double
}
open var width: Int? {
return getParam(.width) as? Int
}
open var height: Int? {
return getParam(.height) as? Int
}
open var url: String? {
return getParam(.url) as? String
}
open var secureUrl: String? {
return getParam(.secureUrl) as? String
}
open var nextCursor: String? {
return getParam(.nextCursor) as? String
}
open var exif: [String : String]? {
return getParam(.exif) as? [String : String]
}
open var metadata: [String : String]? {
return getParam(.metadata) as? [String : String]
}
open var faces: AnyObject? {
return getParam(.faces)
}
open var colors: AnyObject? {
return getParam(.colors)
}
open var derived: CLDDerived? {
guard let derived = getParam(.derived) as? [String : AnyObject] else {
return nil
}
return CLDDerived(json: derived)
}
open var tags: [String]? {
return getParam(.tags) as? [String]
}
open var moderation: AnyObject? {
return getParam(.moderation)
}
open var context: AnyObject? {
return getParam(.context)
}
open var phash: String? {
return getParam(.phash) as? String
}
open var predominant: CLDPredominant? {
guard let predominant = getParam(.predominant) as? [String : AnyObject] else {
return nil
}
return CLDPredominant(json: predominant)
}
open var coordinates: CLDCoordinates? {
guard let coordinates = getParam(.coordinates) as? [String : AnyObject] else {
return nil
}
return CLDCoordinates(json: coordinates)
}
open var info: CLDInfo? {
guard let info = getParam(.info) as? [String : AnyObject] else {
return nil
}
return CLDInfo(json: info)
}
// MARK: - Private Helpers
fileprivate func getParam(_ param: RenameResultKey) -> AnyObject? {
return resultJson[String(describing: param)]
}
fileprivate enum RenameResultKey: CustomStringConvertible {
case nextCursor, derived, context, predominant, coordinates
var description: String {
switch self {
case .nextCursor: return "next_cursor"
case .derived: return "derived"
case .context: return "context"
case .predominant: return "predominant"
case .coordinates: return "coordinates"
}
}
}
}
// MARK: - CLDCoordinates
@objc open class CLDCoordinates: CLDBaseResult {
open var custom: AnyObject? {
return getParam(.custom)
}
open var faces: AnyObject? {
return getParam(.faces)
}
// MARK: Private Helpers
fileprivate func getParam(_ param: CLDCoordinatesKey) -> AnyObject? {
return resultJson[String(describing: param)]
}
fileprivate enum CLDCoordinatesKey: CustomStringConvertible {
case custom
var description: String {
switch self {
case .custom: return "custom"
}
}
}
}
// MARK: - CLDPredominant
@objc open class CLDPredominant: CLDBaseResult {
open var google: AnyObject? {
return getParam(.google)
}
// MARK: - Private Helpers
fileprivate func getParam(_ param: CLDPredominantKey) -> AnyObject? {
return resultJson[String(describing: param)]
}
fileprivate enum CLDPredominantKey: CustomStringConvertible {
case google
var description: String {
switch self {
case .google: return "google"
}
}
}
}
// MARK: - CLDDerived
@objc open class CLDDerived: CLDBaseResult {
open var transformation: String? {
return getParam(.transformation) as? String
}
open var format: String? {
return getParam(.format) as? String
}
open var length: Double? {
return getParam(.length) as? Double
}
open var identifier: String? {
return getParam(.id) as? String
}
open var url: String? {
return getParam(.url) as? String
}
open var secureUrl: String? {
return getParam(.secureUrl) as? String
}
// MARK: - Private Helpers
fileprivate func getParam(_ param: CLDDerivedKey) -> AnyObject? {
return resultJson[String(describing: param)]
}
fileprivate enum CLDDerivedKey: CustomStringConvertible {
case transformation, id
var description: String {
switch self {
case .transformation: return "transformation"
case .id: return "id"
}
}
}
}
|
mit
|
1c024b32cd1c702dacf46b35d526ac18
| 25.378788 | 86 | 0.590896 | 4.692722 | false | false | false | false |
tenebreux/realm-cocoa
|
RealmSwift-swift2.0/Tests/ObjectAccessorTests.swift
|
1
|
12075
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 XCTest
import RealmSwift
import Foundation
class ObjectAccessorTests: TestCase {
func setAndTestAllProperties(object: SwiftObject) {
object.boolCol = true
XCTAssertEqual(object.boolCol, true)
object.boolCol = false
XCTAssertEqual(object.boolCol, false)
object.intCol = -1
XCTAssertEqual(object.intCol, -1)
object.intCol = 0
XCTAssertEqual(object.intCol, 0)
object.intCol = 1
XCTAssertEqual(object.intCol, 1)
object.floatCol = 20
XCTAssertEqual(object.floatCol, 20 as Float)
object.floatCol = 20.2
XCTAssertEqual(object.floatCol, 20.2 as Float)
object.floatCol = 16777217
XCTAssertEqual(Double(object.floatCol), 16777216.0 as Double)
object.doubleCol = 20
XCTAssertEqual(object.doubleCol, 20)
object.doubleCol = 20.2
XCTAssertEqual(object.doubleCol, 20.2)
object.doubleCol = 16777217
XCTAssertEqual(object.doubleCol, 16777217)
object.stringCol = ""
XCTAssertEqual(object.stringCol, "")
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
object.stringCol = utf8TestString
XCTAssertEqual(object.stringCol, utf8TestString)
let data = "b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
object.binaryCol = data
XCTAssertEqual(object.binaryCol, data)
let date = NSDate(timeIntervalSinceReferenceDate: 2) as NSDate
object.dateCol = date
XCTAssertEqual(object.dateCol, date)
object.objectCol = SwiftBoolObject(value: [true])
XCTAssertEqual(object.objectCol!.boolCol, true)
}
func testStandaloneAccessors() {
let object = SwiftObject()
setAndTestAllProperties(object)
let optionalObject = SwiftOptionalObject()
setAndTestAllOptionalProperties(optionalObject)
}
func testPersistedAccessors() {
let realm = try! Realm()
realm.beginWrite()
let object = realm.create(SwiftObject)
let optionalObject = realm.create(SwiftOptionalObject)
setAndTestAllProperties(object)
setAndTestAllOptionalProperties(optionalObject)
try! realm.commitWrite()
}
func testIntSizes() {
let realm = realmWithTestPath()
let v8 = Int8(1) << 6
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
try! realm.write {
let obj = SwiftAllIntSizesObject()
let testObject: Void -> Void = {
obj.objectSchema.properties.map { $0.name }.forEach { obj[$0] = 0 }
obj["int8"] = Int(v8)
XCTAssertEqual((obj["int8"]! as! Int), Int(v8))
obj["int16"] = Int(v16)
XCTAssertEqual((obj["int16"]! as! Int), Int(v16))
obj["int32"] = Int(v32)
XCTAssertEqual((obj["int32"]! as! Int), Int(v32))
obj["int64"] = NSNumber(longLong: v64)
XCTAssertEqual((obj["int64"]! as! NSNumber), NSNumber(longLong: v64))
obj.objectSchema.properties.map { $0.name }.forEach { obj[$0] = 0 }
obj.setValue(Int(v8), forKey: "int8")
XCTAssertEqual((obj.valueForKey("int8")! as! Int), Int(v8))
obj.setValue(Int(v16), forKey: "int16")
XCTAssertEqual((obj.valueForKey("int16")! as! Int), Int(v16))
obj.setValue(Int(v32), forKey: "int32")
XCTAssertEqual((obj.valueForKey("int32")! as! Int), Int(v32))
obj.setValue(NSNumber(longLong: v64), forKey: "int64")
XCTAssertEqual((obj.valueForKey("int64")! as! NSNumber), NSNumber(longLong: v64))
obj.objectSchema.properties.map { $0.name }.forEach { obj[$0] = 0 }
obj.int8 = v8
XCTAssertEqual(obj.int8, v8)
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
}
testObject()
realm.add(obj)
testObject()
}
let obj = realm.objects(SwiftAllIntSizesObject).first!
XCTAssertEqual(obj.int8, v8)
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testLongType() {
let longNumber: Int64 = 17179869184
let intNumber: Int64 = 2147483647
let negativeLongNumber: Int64 = -17179869184
let updatedLongNumber: Int64 = 8589934592
let realm = realmWithTestPath()
realm.beginWrite()
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: longNumber)])
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: intNumber)])
realm.create(SwiftLongObject.self, value: [NSNumber(longLong: negativeLongNumber)])
try! realm.commitWrite()
let objects = realm.objects(SwiftLongObject)
XCTAssertEqual(objects.count, Int(3), "3 rows expected")
XCTAssertEqual(objects[0].longCol, longNumber, "2 ^ 34 expected")
XCTAssertEqual(objects[1].longCol, intNumber, "2 ^ 31 - 1 expected")
XCTAssertEqual(objects[2].longCol, negativeLongNumber, "-2 ^ 34 expected")
realm.beginWrite()
objects[0].longCol = updatedLongNumber
try! realm.commitWrite()
XCTAssertEqual(objects[0].longCol, updatedLongNumber, "After update: 2 ^ 33 expected")
}
func testListsDuringResultsFastEnumeration() {
let realm = realmWithTestPath()
let object1 = SwiftObject()
let object2 = SwiftObject()
let trueObject = SwiftBoolObject()
trueObject.boolCol = true
let falseObject = SwiftBoolObject()
falseObject.boolCol = false
object1.arrayCol.append(trueObject)
object1.arrayCol.append(falseObject)
object2.arrayCol.append(trueObject)
object2.arrayCol.append(falseObject)
try! realm.write {
realm.add(object1)
realm.add(object2)
}
let objects = realm.objects(SwiftObject)
let firstObject = objects.first
XCTAssertEqual(2, firstObject!.arrayCol.count)
let lastObject = objects.last
XCTAssertEqual(2, lastObject!.arrayCol.count)
// let generator = objects.generate()
// let next = generator.next()!
// XCTAssertEqual(next.arrayCol.count, 2)
for obj in objects {
XCTAssertEqual(2, obj.arrayCol.count)
}
}
func testSettingOptionalPropertyOnDeletedObjectsThrows() {
let realm = try! Realm()
try! realm.write {
let obj = realm.create(SwiftOptionalObject)
let copy = realm.objects(SwiftOptionalObject).first!
realm.delete(obj)
self.assertThrows(copy.optIntCol.value = 1)
self.assertThrows(copy.optIntCol.value = nil)
self.assertThrows(obj.optIntCol.value = 1)
self.assertThrows(obj.optIntCol.value = nil)
}
}
func setAndTestAllOptionalProperties(object: SwiftOptionalObject) {
object.optNSStringCol = ""
XCTAssertEqual(object.optNSStringCol!, "")
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
object.optNSStringCol = utf8TestString
XCTAssertEqual(object.optNSStringCol!, utf8TestString)
object.optNSStringCol = nil
XCTAssertNil(object.optNSStringCol)
object.optStringCol = ""
XCTAssertEqual(object.optStringCol!, "")
object.optStringCol = utf8TestString
XCTAssertEqual(object.optStringCol!, utf8TestString)
object.optStringCol = nil
XCTAssertNil(object.optStringCol)
let data = "b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
object.optBinaryCol = data
XCTAssertEqual(object.optBinaryCol!, data)
object.optBinaryCol = nil
XCTAssertNil(object.optBinaryCol)
let date = NSDate(timeIntervalSinceReferenceDate: 2) as NSDate
object.optDateCol = date
XCTAssertEqual(object.optDateCol!, date)
object.optDateCol = nil
XCTAssertNil(object.optDateCol)
object.optIntCol.value = Int.min
XCTAssertEqual(object.optIntCol.value!, Int.min)
object.optIntCol.value = 0
XCTAssertEqual(object.optIntCol.value!, 0)
object.optIntCol.value = Int.max
XCTAssertEqual(object.optIntCol.value!, Int.max)
object.optIntCol.value = nil
XCTAssertNil(object.optIntCol.value)
object.optInt16Col.value = Int16.min
XCTAssertEqual(object.optInt16Col.value!, Int16.min)
object.optInt16Col.value = 0
XCTAssertEqual(object.optInt16Col.value!, 0)
object.optInt16Col.value = Int16.max
XCTAssertEqual(object.optInt16Col.value!, Int16.max)
object.optInt16Col.value = nil
XCTAssertNil(object.optInt16Col.value)
object.optInt32Col.value = Int32.min
XCTAssertEqual(object.optInt32Col.value!, Int32.min)
object.optInt32Col.value = 0
XCTAssertEqual(object.optInt32Col.value!, 0)
object.optInt32Col.value = Int32.max
XCTAssertEqual(object.optInt32Col.value!, Int32.max)
object.optInt32Col.value = nil
XCTAssertNil(object.optInt32Col.value)
object.optInt64Col.value = Int64.min
XCTAssertEqual(object.optInt64Col.value!, Int64.min)
object.optInt64Col.value = 0
XCTAssertEqual(object.optInt64Col.value!, 0)
object.optInt64Col.value = Int64.max
XCTAssertEqual(object.optInt64Col.value!, Int64.max)
object.optInt64Col.value = nil
XCTAssertNil(object.optInt64Col.value)
object.optFloatCol.value = -FLT_MAX
XCTAssertEqual(object.optFloatCol.value!, -FLT_MAX)
object.optFloatCol.value = 0
XCTAssertEqual(object.optFloatCol.value!, 0)
object.optFloatCol.value = FLT_MAX
XCTAssertEqual(object.optFloatCol.value!, FLT_MAX)
object.optFloatCol.value = nil
XCTAssertNil(object.optFloatCol.value)
object.optDoubleCol.value = -DBL_MAX
XCTAssertEqual(object.optDoubleCol.value!, -DBL_MAX)
object.optDoubleCol.value = 0
XCTAssertEqual(object.optDoubleCol.value!, 0)
object.optDoubleCol.value = DBL_MAX
XCTAssertEqual(object.optDoubleCol.value!, DBL_MAX)
object.optDoubleCol.value = nil
XCTAssertNil(object.optDoubleCol.value)
object.optBoolCol.value = true
XCTAssertEqual(object.optBoolCol.value!, true)
object.optBoolCol.value = false
XCTAssertEqual(object.optBoolCol.value!, false)
object.optBoolCol.value = nil
XCTAssertNil(object.optBoolCol.value)
object.optObjectCol = SwiftBoolObject(value: [true])
XCTAssertEqual(object.optObjectCol!.boolCol, true)
object.optObjectCol = nil
XCTAssertNil(object.optObjectCol)
}
}
|
apache-2.0
|
69e5846c88b8147e2a1ac2f5f9fbfcb3
| 36.111455 | 97 | 0.63035 | 4.384418 | false | true | false | false |
hivinau/bioserenity
|
bios.cars/Cars.swift
|
1
|
6866
|
//
// Cars.swift
// bios.cars
//
// Created by iOS Developer on 20/07/2017.
// Copyright © 2017 fdapps. All rights reserved.
//
import UIKit
public class Cars: UIViewController {
private var container: UIView?
internal var socket: Socket?
internal var pageControl: UIPageControl?
internal lazy var carsDisplayer: CarsDisplayer = {
return CarsDisplayer()
}()
public init() {
super.init(nibName: nil, bundle: nil)
container = UIView()
pageControl = UIPageControl()
if let address = Config.value(forKey: "address") as? String,
let token = Config.value(forKey: "token") as? Int {
socket = Socket(hostAddress: address, userToken: token)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func loadView() {
super.loadView()
view.addSubview(container!)
view.insertSubview(pageControl!, aboveSubview: container!)
container?.translatesAutoresizingMaskIntoConstraints = false
pageControl?.translatesAutoresizingMaskIntoConstraints = false
let containerHorizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|[container]|",
options: [],
metrics: nil,
views: ["container": container!])
let containerTopConstraint = NSLayoutConstraint(item: container!,
attribute: .top,
relatedBy: .equal,
toItem: topLayoutGuide,
attribute: .bottom,
multiplier: 1.0,
constant: 0)
let containerBottomConstraint = NSLayoutConstraint(item: bottomLayoutGuide,
attribute: .top,
relatedBy: .equal,
toItem: container!,
attribute: .bottom,
multiplier: 1.0,
constant: 0)
let pageControlBottomConstraint = NSLayoutConstraint(item: pageControl!,
attribute: .bottom,
relatedBy: .equal,
toItem: container!,
attribute: .bottom,
multiplier: 1.0,
constant: 0)
let pageControlCenterXConstraint = NSLayoutConstraint(item: pageControl!,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1.0,
constant: 0)
let pageControlHeightConstraint = NSLayoutConstraint(item: pageControl!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 20.0)
var constraints = [NSLayoutConstraint]()
constraints += containerHorizontalConstraints
constraints.append(containerTopConstraint)
constraints.append(containerBottomConstraint)
constraints.append(pageControlBottomConstraint)
constraints.append(pageControlCenterXConstraint)
constraints.append(pageControlHeightConstraint)
view.addConstraints(constraints)
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
addChildController(carsDisplayer, sourceView: container!)
pageControl?.pageIndicatorTintColor = .gray
pageControl?.currentPageIndicatorTintColor = .green
pageControl?.numberOfPages = 0
pageControl?.currentPage = 0
carsDisplayer.carsDisplayerDelegate = self
socket?.delegate = self
socket?.connect()
}
deinit {
socket?.disconnect()
}
}
//Mark: notify position of car currently displayed
extension Cars: CarsDisplayerDelegate {
public func carsDisplayer(_ carsDisplayer: CarsDisplayer, showCarAt indexPath: IndexPath) {
pageControl?.currentPage = indexPath.row
}
}
//Mark: delegate methods called after socket connection
extension Cars: SocketDelegate {
public func socketStatusChanged(_ socket: Socket, isConnected: Bool) {
if !isConnected {
carsDisplayer.removeAll()
pageControl?.currentPage = 0
} else {
//load cars
socket.send()
}
}
public func socket(_ socket: Socket, didReceive content: Any) {
if let values = content as? [[String: Any]],
values.count > 0 {
var cars = [Car]()
values.forEach({
value in
let car = Car(brand: value["Brand"] as? String,
name: value["Name"] as? String,
speedMax: value["SpeedMax"] as? Int,
cv: value["Cv"] as? Int,
currentSpeed: value["CurrentSpeed"] as? Int)
cars.append(car)
})
pageControl?.numberOfPages = cars.count
pageControl?.currentPage = 0
cars.forEach({
car in
carsDisplayer.add(car: car)
})
}
}
}
|
apache-2.0
|
4c111ea40e651144217c4c2b3bcbbd1d
| 36.513661 | 95 | 0.439039 | 7.173459 | false | false | false | false |
PuneetPalSingh/ScuOffCampusApp
|
ScuOffCampusApp/SCHSignUpVC.swift
|
1
|
9734
|
//
// SCHSignUpVC.swift
// ScuOffCampusApp
//
// Created by Puneet Pal Singh on 5/20/16.
// Copyright © 2016 Puneet Pal Singh. All rights reserved.
//
import Foundation
import UIKit
import AFNetworking
class SCHSignUpVC: UIViewController {
@IBOutlet weak var firstNameTextField : UITextField!
@IBOutlet weak var lastNameTextField : UITextField!
@IBOutlet weak var emailTextField : UITextField!
@IBOutlet weak var passwordTextField : UITextField!
@IBOutlet weak var confirmedPasswordTextField : UITextField!
override func viewDidLoad() {
self.navigationItem.hidesBackButton = true
// Add Done Button For Keyboard
addToolBarToKeyboard(firstNameTextField);
addToolBarToKeyboard(lastNameTextField);
addToolBarToKeyboard(emailTextField);
addToolBarToKeyboard(passwordTextField);
addToolBarToKeyboard(confirmedPasswordTextField);
}
@IBAction func createAccountButtonPressed(sender: AnyObject) {
if isValidFirstName() {
if isValidLastName() {
if isValidEmail() {
if isValidPassword() {
createAccountWithFirstName(firstNameTextField.text!, lastName: lastNameTextField.text!, email: emailTextField.text!, password: passwordTextField.text!, confirmedPassword: confirmedPasswordTextField.text!, completion: {(success,response) in
print(success)
if success{
let response : Dictionary = response as! Dictionary<String,AnyObject>
let token : String = response["auth_token"] as! String
let userDetail : Dictionary = response["user"] as! Dictionary<String,AnyObject>
SCHKeyChainManager.saveKeyInKeychainWithKey("Token", value: token, withComplitionHandler:{(success) in
let tabBarVC = self.storyboard?.instantiateViewControllerWithIdentifier("TabBarVC") as! SCHTabBarVC
self.navigationController?.presentViewController(tabBarVC, animated: true, completion: nil)
})
print(token)
print(userDetail)
print("YES")
}
else{
let accountExistAlert : UIAlertController = UIAlertController(title: "Error", message: "User already exist with this email address. Try some other email address.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
accountExistAlert.addAction(OkAction)
self.presentViewController(accountExistAlert, animated: true, completion: nil)
}
})
}
}
}
}
}
@IBAction func SignInButtonPressed(sender: AnyObject) {
self.navigationController!.popViewControllerAnimated(true)
}
// Create Done Button For Keyboard
func addToolBarToKeyboard(textField : UITextField) -> Void {
let keyboardToolbar : UIToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace,target: nil, action: nil)
let doneBarButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done,target: self, action:#selector(SCHSignUpVC.endEditing))
doneBarButton.tintColor = UIColor (colorLiteralRed: 0.25, green: 0.5, blue: 0.0, alpha: 1.0)
keyboardToolbar.setItems([flexBarButton, doneBarButton], animated: true)
// Add New Keyboard With Done Button To TextFields
textField.inputAccessoryView = keyboardToolbar
}
func endEditing() -> Void {
firstNameTextField.resignFirstResponder()
lastNameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
confirmedPasswordTextField.resignFirstResponder()
}
func isValidFirstName() -> Bool {
if (firstNameTextField.text!.characters.count > 0) {
return true
}
else{
let noFirstNameAlertController : UIAlertController = UIAlertController(title: "Error", message: "Please enter your First Name.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
noFirstNameAlertController.addAction(OkAction)
self.presentViewController(noFirstNameAlertController, animated: true, completion: nil)
}
return false
}
func isValidLastName() -> Bool {
if (lastNameTextField.text!.characters.count > 0) {
return true
}
else{
let noFirstNameAlertController : UIAlertController = UIAlertController(title: "Error", message: "Please enter your Last Name.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
noFirstNameAlertController.addAction(OkAction)
self.presentViewController(noFirstNameAlertController, animated: true, completion: nil)
}
return false
}
func isValidEmail() -> Bool {
var flag : Bool = true
if (emailTextField.text!.characters.count > 0) {
if SCHUtilities.isValidEmailId(emailTextField.text) {
return true
}
else{
flag = true
}
}
if flag {
let noFirstNameAlertController : UIAlertController = UIAlertController(title: "Error", message: "Please enter valid email address.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
noFirstNameAlertController.addAction(OkAction)
self.presentViewController(noFirstNameAlertController, animated: true, completion: nil)
}
return false
}
func isValidPassword() -> Bool {
if passwordTextField.text?.characters.count < 8 {
let noFirstNameAlertController : UIAlertController = UIAlertController(title: "Error", message: "Please make sure your password contains more than 8 characters.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
noFirstNameAlertController.addAction(OkAction)
self.presentViewController(noFirstNameAlertController, animated: true, completion: nil)
}
else{
if (passwordTextField.text == confirmedPasswordTextField.text && passwordTextField.text?.characters.count > 0) {
return true
}
else{
let noFirstNameAlertController : UIAlertController = UIAlertController(title: "Error", message: "Please make sure your password and confirmation pasword matches.", preferredStyle: .Alert)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: {(action) in
})
noFirstNameAlertController.addAction(OkAction)
self.presentViewController(noFirstNameAlertController, animated: true, completion: nil)
}
}
return false
}
func createAccountWithFirstName(firstName : String, lastName : String, email : String, password : String, confirmedPassword : String, completion : (success : Bool, response : AnyObject)-> Void) -> Void {
let jsonString : String = "{\"user\": {\"firstname\": \"\(firstName)\",\"lastname\": \"\(lastName)\",\"email\": \"\(email)\",\"password\": \"\(password)\",\"password_confirmation\": \"\(confirmedPassword)\"}}"
let jsonData : NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do{
let parameters = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let url = kBaseUrl + "sign_up"
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.POST(url, parameters: parameters, progress: nil, success:{(task, response) in
completion(success: true,response: response!)
}, failure: {(task, error) in
completion(success: false,response: NSNull())
})
}
catch{
}
}
}
|
mit
|
275b04ab27c19dd6bc0bf10f58e69501
| 40.594017 | 263 | 0.562519 | 6.255141 | false | false | false | false |
glimpseio/ChannelZ
|
Tests/ChannelZTests/KeyPathTests.swift
|
1
|
81476
|
////
// FoundationTests.swift
// ChannelZ
//
// Created by Marc Prud'hommeaux on 2/5/15.
// Copyright (c) 2015 glimpse.io. All rights reserved.
//
#if !os(Linux)
import XCTest
import ChannelZ
import CoreData
class KeyPathTests : ChannelTestCase {
func assertMemoryBlock<T>(_ file: StaticString = #file, line: UInt = #line, check: @autoclosure ()->T, code: ()->()) where T: Equatable {
let start = check()
autoreleasepool(invoking: code)
let end = check()
XCTAssertEqual(start, end, "assertMemoryBlock failure", file: (file), line: line)
}
// func testMemory() {
// var strs: [String] = []
// var receipt: Receipt!
// assertMemoryBlock(check: ChannelThingsInstances) {
// let thing = ChannelThing()
// receipt = thing.stringish.sieve(!=).some().receive({ strs += [$0] })
// let strings: [String?] = ["a", "b", nil, "b", "b", "c"]
// for x in strings { thing.stringish ∞= x }
// XCTAssertFalse(receipt.cancelled)
// }
//
//// XCTAssertTrue(receipt.cancelled) // TODO: should receipts clear when sources are cancelled?
// XCTAssertEqual(["a", "b", "b", "c"], strs, "early sieve misses filter")
// receipt.cancel()
//
// }
/// Ensure that objects are cleaned up when receipts are explicitly canceled
func testKVOMemoryCleanupCanceled() {
assertMemoryBlock(check: StatefulObjectCount) {
let nsob = StatefulObject()
let intz = nsob.channelZKeyValue(\.int)
let rcpt = intz.receive({ _ in })
rcpt.cancel()
}
}
/// Ensure that objects are cleaned up even when receipts are not explicitly canceled
func testKVOMemoryCleanupUncanceled() {
assertMemoryBlock(check: StatefulObjectCount) {
let nsob = StatefulObject()
let intz = nsob.channelZKeyValue(\.int)
var count = 0
let rcpt = intz.receive({ _ in count += 1 })
XCTAssertEqual(1, count, "should have received an initial element")
withExtendedLifetime(rcpt) { }
}
}
func testSimpleFoundation() {
assertMemoryBlock(check: StatefulObjectCount) {
let nsob = StatefulObject()
let stringz = nsob[channel: \.reqnsstr].changes().subsequent() // also works
// FIXME
// let stringz = nsob.channelZKey(nsob.reqnsstr).sieve(!=).subsequent()
var strs: [NSString] = []
stringz.receive({ strs += [$0] })
// nsob.reqnsstr = "a"
// nsob.reqnsstr = "c"
stringz.rawValue = "a"
stringz.rawValue = "c"
XCTAssertEqual(2, strs.count)
stringz.rawValue = "d"
XCTAssertEqual(3, strs.count)
stringz.rawValue = "d"
XCTAssertEqual(3, strs.count) // change to self shouldn't up the count
withExtendedLifetime(nsob) { }
}
}
func testMultipleReceiversOnKeyValue() {
let holder = NumericHolderClass()
// let prop = holder.channelZKeyState(holder.intField)
let prop = holder[channel: \.intField]
var counts = (0, 0, 0)
prop.receive { _ in counts.0 += 1 }
XCTAssertEqual(1, counts.0)
XCTAssertEqual(0, counts.1)
XCTAssertEqual(0, counts.2)
prop.receive { _ in counts.1 += 1 }
XCTAssertEqual(1, counts.0)
XCTAssertEqual(1, counts.1)
XCTAssertEqual(0, counts.2)
prop.receive { _ in counts.2 += 1 }
XCTAssertEqual(1, counts.0)
XCTAssertEqual(1, counts.1)
XCTAssertEqual(1, counts.2)
holder.setValue(123, forKey: "intField")
XCTAssertEqual(2, counts.0)
XCTAssertEqual(2, counts.1)
XCTAssertEqual(2, counts.2)
prop.rawValue = 456
XCTAssertEqual(3, counts.0)
XCTAssertEqual(3, counts.1)
XCTAssertEqual(3, counts.2)
}
func testChannels() {
let observedBool = ∞=false=∞
var changeCount: Int = 0
let ob1 = observedBool.subsequent().receive { v in
changeCount = changeCount + 1
}
withExtendedLifetime(ob1) { }
XCTAssertEqual(0, changeCount)
observedBool ∞= true
XCTAssertEqual(1, changeCount)
observedBool ∞= true
XCTAssertEqual(1, changeCount)
observedBool ∞= false
observedBool ∞= false
XCTAssertEqual(2, changeCount)
// XCTAssertEqual(test, false)
#if DEBUG_CHANNELZ
let startObserverCount = ChannelZKeyValueObserverCount.get()
#endif
// autoreleasepool {
// // FIXME: crazy; if these are outsize the autoreleasepool, the increments fail
// var sz: Int = 0
// var iz: Int = 0
// var dz: Int = 0
//
// let state = StatefulObject()
//
// state.channelZKey(state.int).sieve(!=).receive { _ in iz += 1 }
//
// #if DEBUG_CHANNELZ
// XCTAssertEqual(ChannelZKeyValueObserverCount, startObserverCount + 1)
// #endif
//
// let sfo = state.channelZKey(state.optstr).sieve(!=)
// let strpath = "optstr"
// XCTAssertEqual(strpath, sfo.source.keyPath)
//
// state.channelZKey(state.dbl).sieve(!=).receive { _ in dz += 1 }
//
//
// assertChanges(iz, state.int += 1)
// assertRemains(iz, state.int = state.int + 0)
// assertChanges(iz, state.int = state.int + 1)
// assertRemains(iz, state.int = state.int + 1 - 1)
//
// sfo.receive { (value: String?) in sz += 1 }
//
// assertChanges(sz, state.optstr = "x")
// assertChanges(sz, state.optstr! += "yz")
//
// assertChanges(sz, state.setValue("", forKeyPath: strpath))
// assertRemains(sz, state.setValue("", forKeyPath: strpath))
// XCTAssertEqual("", state.optstr!)
// assertChanges(sz, state.setValue(nil, forKeyPath: strpath))
// assertRemains(sz, state.setValue(nil, forKeyPath: strpath))
// XCTAssertNil(state.optstr)
// assertChanges(sz, state.setValue("abc", forKeyPath: strpath))
// assertRemains(sz, state.setValue("abc", forKeyPath: strpath))
// XCTAssertEqual("abc", state.optstr!)
//
// assertChanges(sz, sfo ∞= "")
// assertRemains(sz, sfo ∞= "")
// XCTAssertEqual("", state.optstr!)
//
// assertChanges(sz, sfo ∞= nil)
// XCTAssertNil(state.optnsstr)
// assertRemains(sz, sfo ∞= nil)
// XCTAssertNil(state.optnsstr)
//
// assertChanges(sz, sfo ∞= "abc")
// assertRemains(sz, sfo ∞= "abc")
//
// assertChanges(sz, sfo ∞= "y")
// assertChanges(sz, state.setValue(nil, forKeyPath: strpath))
// assertRemains(sz, state.setValue(nil, forKeyPath: strpath))
//
// assertChanges(sz, sfo ∞= "y")
//
// assertChanges(sz, sfo ∞= nil)
// assertRemains(sz, sfo ∞= nil)
//
// assertRemains(sz, state.optstr = nil)
//
// assertChanges(sz, state.optstr = "")
// assertRemains(sz, state.optstr = "")
//
// assertChanges(sz, state.optstr = "foo")
//
// withExtendedLifetime(state) { } // need to hold on
//
// #if DEBUG_CHANNELZ
// XCTAssertEqual(ChannelZKeyValueObserverCount, startObserverCount + 1, "observers should still be around before cleanup")
// #endif
// }
#if DEBUG_CHANNELZ
XCTAssertEqual(ChannelZKeyValueObserverCount.get(), startObserverCount, "observers should have been cleared after cleanup")
#endif
}
func testMultipleSimpleChannels() {
// let intChannel = channelZPropertyValue(0).sieve(!=)
let intChannel = ∞=0=∞
var changeCount: Int = 0
let r1 = intChannel.receive { v in
changeCount = changeCount + 1
}
let r2 = intChannel.receive { v in
changeCount = changeCount + 1
}
changeCount = 0 // clear any initial assignations
XCTAssertEqual(0, changeCount)
intChannel.rawValue += 1
XCTAssertEqual(2, changeCount)
intChannel.rawValue = 1 // no change
XCTAssertEqual(2, changeCount)
intChannel.rawValue += 1
XCTAssertEqual(4, changeCount)
r1.cancel()
intChannel.rawValue += 1
XCTAssertEqual(5, changeCount)
r2.cancel()
intChannel.rawValue += 1
XCTAssertEqual(5, changeCount)
}
// func testMultipleKVOChannels() {
// let ob = NumericHolderClass()
//// let intChannel = ob.channelZKeyState(ob.intField).changes() // also works
// let intChannel = ob.channelZKey(ob.intField).sieve(!=)
//
// var changeCount: Int = 0
//
// let receiverCount = 10
// var receivers: [Receipt] = []
// for _ in 1...receiverCount {
// receivers.append(intChannel.receive { _ in
// changeCount += 1
// })
// }
//
// changeCount = 0 // clear any initial assignations
// XCTAssertEqual(0, changeCount)
//
// ob.intField += 1
// XCTAssertEqual(receiverCount, changeCount)
//
// let currentValue = ob.intField
// ob.intField = currentValue // no change
// XCTAssertEqual(receiverCount, changeCount)
//
// ob.intField += 1
// XCTAssertEqual(receiverCount * 2, changeCount)
//
//// receivers.first.cancel()
//// ob.intField += 1
//// XCTAssertEqual(5, changeCount)
////
//// receivers.last.cancel()
//// ob.intField += 1
//// XCTAssertEqual(5, changeCount)
//
//
// }
func testFilteredChannels() {
var strlen = 0
let sv = channelZPropertyValue("X")
let _ = sv.filter({ _ in true }).map({ $0.utf8.count })
let _ = sv.filter({ _ in true }).map({ $0.utf8.count })
let _ = sv.map({ $0.utf8.count })
_ = ∞=false=∞
let a = sv.filter({ _ in true }).map({ $0.utf8.count }).filter({ $0 % 2 == 1 })
_ = a.receive { strlen = $0 }
a ∞= "AAA"
XCTAssertEqual(3, strlen)
// TODO: need to re-implement .value for FieldChannels, etc.
// a ∞= (a.value + "ZZ")
// XCTAssertEqual(5, strlen)
// XCTAssertEqual("AAAZZ", a.value)
//
// a ∞= (a.value + "A")
// XCTAssertEqual("AAAZZA", a.value)
// XCTAssertEqual(5, strlen, "even-numbered increment should have been filtered")
//
// a ∞= (a.value + "A")
// XCTAssertEqual("AAAZZAA", a.value)
// XCTAssertEqual(7, strlen)
let x = channelZPropertyValue(1).subsequent().filter { $0 <= 10 }
var changeCount: Double = 0
var changeLog: String = ""
// track the number of changes using two separate subscriptions
x.receive { _ in changeCount += 0.5 }
x.receive { _ in changeCount += 0.5 }
let xfm = x.map( { String($0) })
_ = xfm.receive { s in changeLog += (changeLog.isEmpty ? "" : ", ") + s } // create a string log of all the changes
XCTAssertEqual(0, changeCount)
XCTAssertNotEqual(5, x.source.rawValue)
x ∞= 5
XCTAssertEqual(5, x.source.rawValue)
XCTAssertEqual(1, changeCount)
x ∞= 5
XCTAssertEqual(5, x.source.rawValue)
XCTAssertEqual(1, changeCount)
x ∞= 6
XCTAssertEqual(2, changeCount)
// now test the filter: only changes to numbers less than or equal to 10 should flow to the receivers
x ∞= 20
XCTAssertEqual(2, changeCount, "out of bounds change should not have fired listener")
x ∞= 6
XCTAssertEqual(3, changeCount, "in-bounds change should have fired listener")
for i in 1...100 {
x ∞= i
}
XCTAssertEqual(13, changeCount, "in-bounds change should have fired listener")
XCTAssertEqual("5, 6, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10", changeLog)
var tc = 0.0
let t = ∞(1.0)∞
t.filter({ $0.truncatingRemainder(dividingBy: 2.0) == 0.0 }).filter({ $0.truncatingRemainder(dividingBy: 9.0) == 0.0 }).receive({ n in tc += n })
// t.receive({ n in tc += n })
for i in 1...100 { t ∞= Double(i) }
// FIXME: seems to be getting released somehow
// XCTAssertEqual(270.0, tc, "sum of all numbers between 1 and 100 divisible by 2 and 9")
var lastt = ""
let tv = t.map({ v in v }).filter({ $0.truncatingRemainder(dividingBy: 2.0) == 0.0 }).map(-).map({ "Even: \($0)" })
tv.receive({ lastt = $0 })
for i in 1...99 { tv ∞= Double(i) }
XCTAssertEqual("Even: -98.0", lastt)
}
func testStructChannel() {
let ob = ∞(SwiftStruct(intField: 1, stringField: "x", enumField: .yes))∞
var changes = 0
// receive is the equivalent of ReactiveX's Subscribe
ob.subsequent().receive({ _ in changes += 1 })
XCTAssertEqual(changes, 0)
ob ∞= SwiftStruct(intField: 2, stringField: nil, enumField: .yes)
XCTAssertEqual(changes, 1)
ob ∞= SwiftStruct(intField: 2, stringField: nil, enumField: .yes)
XCTAssertEqual(changes, 2)
}
func testEquatableStructChannel() {
let ob = ∞=(SwiftEquatableStruct(intField: 1, stringField: "x", enumField: .yes))=∞
var changes = 0
ob.subsequent().receive({ _ in changes += 1 })
XCTAssertEqual(changes, 0)
ob ∞= SwiftEquatableStruct(intField: 2, stringField: nil, enumField: .yes)
XCTAssertEqual(changes, 1)
ob ∞= SwiftEquatableStruct(intField: 2, stringField: nil, enumField: .yes)
XCTAssertEqual(changes, 1)
ob ∞= SwiftEquatableStruct(intField: 2, stringField: nil, enumField: .no)
XCTAssertEqual(changes, 2)
ob ∞= SwiftEquatableStruct(intField: 3, stringField: "str", enumField: .yes)
XCTAssertEqual(changes, 3)
}
func testStuctChannels() {
let ob = SwiftObservables()
var stringChanges = 0
ob.stringField.subsequent().receive { _ in stringChanges += 1 }
XCTAssertEqual(0, stringChanges)
assertChanges(stringChanges, ob.stringField ∞= "x")
var enumChanges = 0
ob.enumField.subsequent().receive { _ in enumChanges += 1 }
XCTAssertEqual(0, enumChanges)
assertChanges(enumChanges, ob.enumField ∞= .maybeSo)
assertRemains(enumChanges, ob.enumField ∞= .maybeSo)
}
func testFieldChannel() {
let xs: Int = 1
// operator examples
let csource: ValueTransceiver<Int> = xs∞
let _: Channel<ValueTransceiver<Int>, Int> = ∞csource
let c = ∞xs∞
var changes = 0
c.receive { _ in changes += 1 }
XCTAssertEqual(1, changes)
assertChanges(changes, c ∞= c.source.rawValue + 1)
assertChanges(changes, c ∞= 2)
assertChanges(changes, c ∞= 2)
assertChanges(changes, c ∞= 9)
}
func testFieldSieve() {
let xs: Int = 1
// operator examples
let csource: ValueTransceiver<Int> = xs=∞
let _: Channel<ValueTransceiver<Int>, Int> = ∞=csource
let c = ∞=xs=∞
var changes = 0
c.receive { _ in changes += 1 }
XCTAssertEqual(1, changes)
assertChanges(changes, c ∞= c.source.rawValue + 1)
assertRemains(changes, c ∞= 2)
assertRemains(changes, c ∞= 2)
assertChanges(changes, c ∞= 9)
}
func testOptionalFieldSieve() {
let xs: Int? = nil
// operator examples
let csource: ValueTransceiver<Optional<Int>> = xs=∞
let _: Channel<ValueTransceiver<Optional<Int>>, Optional<Int>> = ∞=csource
let c = ∞=xs=∞
var changes = 0
c ∞> { _ in changes += 1 }
assertChanges(changes, c ∞= (2))
assertRemains(changes, c ∞= (2))
assertChanges(changes, c ∞= (nil))
// assertChanges(changes, c ∞= (nil)) // FIXME: nil to nil is a change?
assertChanges(changes, c ∞= (1))
assertRemains(changes, c ∞= (1))
assertChanges(changes, c ∞= (2))
}
func testKeyValueSieve() {
let state = StatefulObject()
let ckey = state§\.reqstr
let csource: KeyValueTransceiver<StatefulObject, String> = ckey=∞
let channel: KeyValueChannel<StatefulObject, String> = ∞=csource
let _: KeyValueChannel<StatefulObject, String> = ∞(state§\.reqstr)∞
let c2: KeyValueChannel<StatefulObject, String> = ∞=(state§\.reqstr)=∞
let c = c2
var changes = 0
channel ∞> { _ in changes += 1 }
XCTAssertEqual(1, changes)
assertRemains(changes, c ∞= ("")) // default to default should not change
assertChanges(changes, c ∞= ("A"))
assertRemains(changes, c ∞= ("A"))
assertChanges(changes, c ∞= ("B"))
}
func testKeyValueSieveUnretainedReceiver() {
let state = StatefulObject()
let c = state∞(\.reqstr)
var changes = 0
autoreleasepool {
let _ = c ∞> { _ in changes += 1 } // note we do not assign it locally, so it should immediately get cleaned up
XCTAssertEqual(1, changes)
}
// FIXME: not working in Swift 1.2; receiver block is called, but changes outside of autorelease block isn't updated
// assertChanges(changes, c ∞= ("A")) // unretained subscription should still listen
// assertChanges(changes, c ∞= ("")) // unretained subscription should still listen
return withExtendedLifetime(state) { } // need to retain so it doesn't get cleaned up
}
func testOptionalNSKeyValueSieve() {
let state = StatefulObject()
// var c: Channel<KeyValueOptionalTransceiver<NSString>, NSString?> = ∞=(state§\.optnsstr)=∞
// var c: Channel<KeyValueOptionalTransceiver<NSString>, NSString?> = state∞\.optnsstr
let c: KeyValueChannel<StatefulObject, NSString?> = (state∞\.optnsstr).changes(!=)
var seq: [NSString?] = []
var changes = 0
c ∞> { seq.append($0); changes += 1 }
changes = 0
seq = [] // clear initial values if any
for _ in 0...0 {
assertChanges(changes, c ∞= ("A"))
assertRemains(changes, c ∞= ("A"))
assertChanges(changes, c ∞= (nil))
assertChanges(changes, c ∞= ("B"))
assertChanges(changes, c ∞= (nil))
// this one is tricky, since with KVC, previous values are represented as NSNull(), which != nil
assertRemains(changes, c ∞= (nil))
assertChanges(changes, c ∞= ("C"))
XCTAssertEqual(5, seq.count, "unexpected sequence: \(seq)")
}
}
func testOptionalSwiftSieve() {
let state = StatefulObject()
let c = (state∞(\.optstr)).changes(!=)
var changes = 0
c ∞> { _ in changes += 1 }
for _ in 0...5 {
assertChanges(changes, c ∞= ("A"))
assertRemains(changes, c ∞= ("A"))
assertChanges(changes, c ∞= (nil))
assertChanges(changes, c ∞= ("B"))
assertRemains(changes, c ∞= ("B"))
assertChanges(changes, c ∞= (nil))
// this one is tricky, since with KVC, previous values are often cached as NSNull(), which != nil
assertRemains(changes, c ∞= (nil))
}
}
// func testDictionaryChannels() {
// let dict = NSMutableDictionary()
// var changes = 0
//
// // dict["foo"] = "bar"
//
// dict.channelZKey(dict["foo"] as? NSString, keyPath: "foo") ∞> { _ in changes += 1 }
//
// assertChanges(changes, dict["foo"] = "bar")
// assertChanges(changes, dict["foo"] = NSNumber(value: 1.234 as Float))
// assertChanges(changes, dict["foo"] = NSNull())
// assertChanges(changes, dict["foo"] = "bar")
// }
func testSimpleConduits() {
let n1 = ∞(Int(0))∞
let state = StatefulObject()
let n2 = state∞(\.num3)
let n3 = ∞(Int(0))∞
// bindz((n1, identity), (n2, identity))
// (n1, { $0 + 1 }) <~∞~> (n2, { $0.integerValue - 1 }) <~∞~> (n3, { $0 + 1 })
let n1_n2 = n1.map({ NSNumber(value: $0 + 1) }).conduit(n2.map({ $0.intValue - 1 }))
defer { n1_n2.cancel() }
let n2_n1 = (n2, { (x: NSNumber) in Optional<Int>.some(x.intValue - 1) }) <~∞~> (n3, { (x: Int) in Optional<NSNumber>.some(NSNumber(value: x + 1)) })
defer { n2_n1.cancel() }
n1 ∞= 2
XCTAssertEqual(2, n1∞?)
XCTAssertEqual(3, n2∞? )
XCTAssertEqual(2, n3∞?)
n2 ∞= 5
XCTAssertEqual(4, n1∞?)
XCTAssertEqual(5, n2∞? )
XCTAssertEqual(4, n3∞?)
n3 ∞= -1
XCTAssertEqual(-1, n1∞?)
XCTAssertEqual(0, n2∞?)
XCTAssertEqual(-1, n3∞?)
// make sure disconnecting the binding actually disconnects is
n1_n2.cancel()
n1 ∞= 20
XCTAssertEqual(20, n1∞?)
XCTAssertEqual(0, n2∞? )
XCTAssertEqual(-1, n3∞?)
}
func testSinkObservables() {
let channel = channelZSink(Int.self)
channel.source.receive(1)
var changes = 0
_ = channel.receive({ _ in changes += 1 })
XCTAssertEqual(0, changes)
assertChanges(changes, channel.source.receive(1))
// let sinkof = AnyReceiver(channel.source)
// sinkof.put(2)
// assertSingleChange(&changes, "sink wrapper around observable should have passed elements through to subscriptions")
//
// subscription.cancel()
// sinkof.put(2)
// XCTAssertEqual(0, changes, "canceled subscription should not be called")
}
// func testTransformableConduits() {
//
// let num = ∞(0)∞
// let state = StatefulObject()
// let strProxy = state∞(\.optstr)
// let dict = NSMutableDictionary()
//
// dict["stringKey"] = "foo"
// let dictProxy = dict.channelZKey(dict["stringKey"], keyPath: "stringKey")
//
// // bind the number value to a string equivalent
//// num ∞> { num in strProxy ∞= "\(num)" }
//// strProxy ∞> { str in num ∞= Int((str as NSString).intValue) }
//
// _ = (num, { "\($0)" }) <~∞~> (strProxy, { $0.flatMap { Int($0) } })
//
// _ = (strProxy, { $0 }) <~∞~> (dictProxy, { $0 as? String? })
//
//// let binding = bindz((strProxy, identity), (dictProxy, identity))
//// let binding = (strProxy, identity) <~∞~> (dictProxy, identity)
//
//// let sval = reflect(str.optstr)∞?
//// str.optstr = nil
//// dump(reflect(str.optstr)∞?)
//
// /* FIXME
//
// num ∞= 10
// XCTAssertEqual("10", state.optstr ?? "<nil>")
//
// state.optstr = "123"
// XCTAssertEqual(123, num∞?)
//
// num ∞= 456
// XCTAssertEqual("456", (dict["stringKey"] as? NSString) ?? "<nil>")
//
// dict["stringKey"] = "-98"
// XCTAssertEqual(-98, num∞?)
//
// // tests re-entrancy with inconsistent equivalencies
// dict["stringKey"] = "ABC"
// XCTAssertEqual(-98, num∞?)
//
// dict["stringKey"] = "66"
// XCTAssertEqual(66, num∞?)
//
// // nullifying should change the proxy
// dict.removeObjectForKey("stringKey")
// XCTAssertEqual(0, num∞?)
//
// // no change from num's value, so don't change
// num ∞= 0
// XCTAssertEqual("", dict["stringKey"] as NSString? ?? "<nil>")
//
// num ∞= 1
// XCTAssertEqual("1", dict["stringKey"] as NSString? ?? "<nil>")
//
// num ∞= 0
// XCTAssertEqual("0", dict["stringKey"] as NSString? ?? "<nil>")
// */
// }
func testEquivalenceConduits() {
/// Test equivalence conduits
let state = StatefulObject()
let qn1 = ∞(0)∞
// let qn2 = (observee: state, keyPath: "intField", value: state.int as NSNumber)===>
let qn2 = state∞(\.int)
let rcvr = qn1 <~∞~> qn2
defer { rcvr.cancel() }
qn1 ∞= (qn1∞? + 1)
XCTAssertEqual(1, state.int)
qn1 ∞= (qn1∞? - 1)
XCTAssertEqual(0, state.int)
qn1 ∞= (qn1∞? + 1)
XCTAssertEqual(1, state.int)
state.int += 10
XCTAssertEqual(11, qn1∞?)
qn1 ∞= (qn1∞? + 1)
XCTAssertEqual(12, state.int)
let qs1 = ∞("")∞
XCTAssertEqual("", qs1∞?)
_ = state∞(\.optstr)
// TODO: fix optonal bindings
// let qsb = qs1 <?∞?> qs2
//
// qs1.value += "X"
// XCTAssertEqual("X", state.optstr ?? "<nil>")
//
// qs1.value += "X"
// XCTAssertEqual("XX", state.optstr ?? "<nil>")
//
// /// Test that disconnecting the binding actually removes the observers
// qsb.cancel()
// qs1.value += "XYZ"
// XCTAssertEqual("XX", state.optstr ?? "<nil>")
}
func testOptionalToPrimitiveConduits() {
// reentrancy is expected here
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
/// Test equivalence bindings
let state = StatefulObject()
// FIXME: reentrancy errors; check the equatable stuff?
let obzn1 = state.channelZKeyValue(\.num1)
let obzn2 = state∞(\.num2)
let cndt1 = obzn1.conduit(obzn2)
// let cndt1 = obzn1.bind(obzn2)
defer { cndt1.cancel() }
state.num2 = 44.56
XCTAssert(state.num1 === state.num2, "change the other side")
XCTAssertNotNil(state.num1)
XCTAssertNotNil(state.num2)
state.num1 = 1
XCTAssert(state.num1 === state.num2, "change one side")
XCTAssertNotNil(state.num1)
XCTAssertNotNil(state.num2)
state.num2 = 12.34567
XCTAssert(state.num1 === state.num2, "change the other side")
XCTAssertNotNil(state.num1)
XCTAssertNotNil(state.num2)
state.num1 = 2
XCTAssert(state.num1 === state.num2, "change back the first side")
XCTAssertNotNil(state.num1)
XCTAssertNotNil(state.num2)
state.num1 = nil
XCTAssert(state.num1 === state.num2, "binding to nil")
XCTAssertNil(state.num2)
state.num1 = NSNumber(value: UInt32.random(in: 0...UInt32.max))
XCTAssert(state.num1 === state.num2, "binding to random")
XCTAssertNotNil(state.num2)
// binding optional num1 to non-optional num3
let obzn3 = state∞(\.num3)
let cndt2 = (obzn3, { $0 as NSNumber? }) <~∞~> (obzn1, { $0 })
defer { cndt2.cancel() }
state.num1 = 67823
XCTAssert(state.num1 === state.num3)
XCTAssertNotNil(state.num3)
state.num1 = nil
XCTAssertEqual(67823, state.num3)
XCTAssertNotNil(state.num3, "non-optional field should not be nil")
XCTAssertNil(state.num1)
// let obzd = state∞(\.dbl)
//
// let bind3 = obzn1.bind(obzd)
//
// state.dbl = 5
// XCTAssertEqual(state.dbl, state.num1?.doubleValue ?? -999)
//
// state.num1 = nil
// XCTAssertEqual(5, state.dbl, "niling optional field should not alter bound non-optional field")
//
// state.dbl += 1
// XCTAssertEqual(state.dbl, state.num1?.doubleValue ?? -999)
//
// state.num1 = 9.9
// XCTAssertEqual(9.9, state.dbl)
//
// // ensure that assigning nil to the num1 doesn't clobber the doubleField
// state.num1 = nil
// XCTAssertEqual(9.9, state.dbl)
//
// state.dbl = 9876
// XCTAssertEqual(9876, state.num1?.doubleValue ?? -999)
//
// state.num1 = 123
// XCTAssertEqual(123, state.dbl)
//
// state.num2 = 456 // num2 <~=~> num1 <?=?> doubleField
// XCTAssertEqual(456, state.dbl)
}
func testLossyConduits() {
// reentrancy is expected here
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
let state = StatefulObject()
// transfet between an int and a double field
let obzi = state∞(\.int)
let obzd = state∞(\.dbl)
let conduit = obzi <~∞~> obzd
defer { conduit.cancel() }
state.int = 1
XCTAssertEqual(1, state.int)
XCTAssertEqual(1.0, state.dbl)
state.dbl += 1
XCTAssertEqual(2, state.int)
XCTAssertEqual(2.0, state.dbl)
state.dbl += 0.8
XCTAssertEqual(2, state.int)
XCTAssertEqual(2.8, state.dbl)
state.int -= 1
XCTAssertEqual(1, state.int)
XCTAssertEqual(1.0, state.dbl)
}
func testHaltingConduits() {
// we expect the ChannelZReentrantReceptions to be incremented; clear it so we don't fail in tearDown
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
// create a binding from an int to a float; when the float is set to a round number, it changes the int, otherwise it halts
typealias T1 = Float
typealias T2 = Float
let x = ∞(T1(0))∞
let y = ∞(T2(0))∞
_ = (x, { $0 }) <~∞~> (y, { $0 == round($0) ? Optional<T1>.some(T1($0)) : Optional<T1>.none })
x ∞= 2
XCTAssertEqual(T1(2), x∞?)
XCTAssertEqual(T2(2.0), y∞?)
y ∞= 3
XCTAssertEqual(T1(3), x∞?)
XCTAssertEqual(T2(3.0), y∞?)
y ∞= 9.9
XCTAssertEqual(T1(3), x∞?)
XCTAssertEqual(T2(9.9), y∞?)
y ∞= 17
XCTAssertEqual(T1(17), x∞?)
XCTAssertEqual(T2(17.0), y∞?)
x ∞= (x∞? + 1)
XCTAssertEqual(T1(18), x∞?)
XCTAssertEqual(T2(18.0), y∞?)
y ∞= (y∞? + 0.5)
XCTAssertEqual(T1(18), x∞?)
XCTAssertEqual(T2(18.5), y∞?)
}
func testConversionConduits() {
// we expect the ChannelZReentrantReceptions to be incremented; clear it so we don't fail in tearDown
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
let num = ∞((Double(0.0)))∞
num ∞= 0
let decimalFormatter = NumberFormatter()
decimalFormatter.numberStyle = .decimal
let toDecimal: (Double)->(String?) = { decimalFormatter.string(from: NSNumber(value: $0)) }
let fromDecimal: (String?)->(Double?) = { $0 == nil ? nil : decimalFormatter.number(from: $0!)?.doubleValue }
let state1 = StatefulObject()
let state1s = state1∞\.optstr
let cndt1 = (num, { toDecimal($0) }) <~∞~> (state1s, fromDecimal)
defer { cndt1.cancel() }
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = .percent
let toPercent: (Double)->(NSString?) = { percentFormatter.string(from: NSNumber(value: $0)) as NSString? }
let fromPercent: (NSString?)->(Double?) = { percentFormatter.number(from: ($0 as String?) ?? "AAA")?.doubleValue }
let state2 = StatefulObject()
let state2s = state2∞(\.optnsstr)
let cndt2 = (num, toPercent) <~∞~> (state2s, fromPercent)
defer { cndt2.cancel() }
let spellingFormatter = NumberFormatter()
spellingFormatter.numberStyle = .spellOut
let state3 = StatefulObject()
let state3s = state3∞(\.reqstr)
let toSpelled: (Double)->(String?) = { spellingFormatter.string(from: NSNumber(value: $0)) }
let fromSpelled: (String)->(Double?) = { spellingFormatter.number(from: $0)?.doubleValue }
let cndt3 = (num, toSpelled) <~∞~> (state3s, fromSpelled)
defer { cndt3.cancel() }
num ∞= (num∞? + 1)
XCTAssertEqual(1, num∞?)
// XCTAssertEqual("1", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("100%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("one", state3.reqstr)
num ∞= (num∞? + 1)
XCTAssertEqual(2, num∞?)
// XCTAssertEqual("2", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("200%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("two", state3.reqstr)
state1.optstr = "3"
XCTAssertEqual(3, num∞?)
XCTAssertEqual("3", state1.optstr ?? "<nil>")
XCTAssertEqual("300%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("three", state3.reqstr)
state2.optnsstr = "400%"
XCTAssertEqual(4, num∞?)
// XCTAssertEqual("4", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("400%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("four", state3.reqstr)
state3.reqstr = "five"
XCTAssertEqual(5, num∞?)
// XCTAssertEqual("5", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("500%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("five", state3.reqstr)
state3.reqstr = "gibberish" // won't parse, so numbers should remain unchanged
XCTAssertEqual(5, num∞?)
// XCTAssertEqual("5", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("500%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("gibberish", state3.reqstr)
state2.optnsstr = nil
XCTAssertEqual(5, num∞?)
// XCTAssertEqual("5", state1.optstr ?? "<nil>") // FIXME
XCTAssertNil(state2.optnsstr)
XCTAssertEqual("gibberish", state3.reqstr)
num ∞= 5.4321
// XCTAssertEqual(5.4321, num∞?)
// XCTAssertEqual("5.432", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("543%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("five point four three two one", state3.reqstr)
state2.optnsstr = "18.3%"
// XCTAssertEqual(0.183, num∞?)
// XCTAssertEqual("0.183", state1.optstr ?? "<nil>") // FIXME
XCTAssertEqual("18%", state2.optnsstr ?? "<nil>")
XCTAssertEqual("zero point one eight three", state3.reqstr)
}
func testOptionalObservables() {
let state = StatefulObject()
#if DEBUG_CHANNELZ
// let startObserverCount = ChannelZKeyValueObserverCount.get()
#endif
var reqnsstr: NSString = ""
// TODO: observable immediately gets deallocated unless we hold on to it
// let a1a = state.observable(state.reqnsstr, keyPath: "reqnsstr").receive({ reqnsstr = $0 })
// FIXME: this seems to hold on to an extra allocation
// let a1 = sieve(state.observable(state.reqnsstr, keyPath: "reqnsstr"))
let a1 = state.channelZKeyValue(\.reqnsstr)
let a1a = a1.receive({ reqnsstr = $0 })
state.reqnsstr = "foo"
XCTAssert(reqnsstr == "foo", "failed: \(reqnsstr)")
// let preDetachCount = count(a1.subscriptions)
a1a.cancel()
// let postDetachCount = count(a1.subscriptions)
// XCTAssertEqual(postDetachCount, preDetachCount - 1, "canceling the subscription should have removed it from the subscription list")
state.reqnsstr = "foo1"
XCTAssertNotEqual(reqnsstr, "foo1", "canceled observable should not have fired")
var optnsstr: NSString?
let a2 = state∞(\.optnsstr)
a2.receive({ optnsstr = $0 })
XCTAssert(optnsstr == nil)
state.optnsstr = nil
XCTAssertNil(optnsstr)
state.optnsstr = "foo"
XCTAssert(optnsstr?.description == "foo", "failed: \(String(describing: optnsstr))")
state.optnsstr = nil
XCTAssertNil(optnsstr)
}
func testNumericConversion() {
// we expect the ChannelZReentrantReceptions to be incremented; clear it so we don't fail in tearDown
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
let fl: Float = convertNumericType(Double(2.34))
XCTAssertEqual(fl, Float(2.34))
let intN : Int = convertNumericType(Double(2.34))
XCTAssertEqual(intN, Int(2))
let uint64 : UInt64 = convertNumericType(Double(-2.34))
XCTAssertEqual(uint64, UInt64(2)) // conversion runs abs()
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.doubleField.conduit(c∞\.doubleField)) {
c.doubleField += 1
XCTAssertEqual(s.doubleField∞?, c.doubleField)
s.doubleField ∞= s.doubleField∞? + 1
XCTAssertEqual(s.doubleField∞?, c.doubleField)
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.floatField.conduit(c∞\.floatField)) {
c.floatField += 1
XCTAssertEqual(s.floatField∞?, c.floatField)
s.floatField ∞= s.floatField∞? + 1
XCTAssertEqual(s.floatField∞?, c.floatField)
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.intField.conduit(c∞\.intField)) {
c.intField += 1
XCTAssertEqual(s.intField∞?, c.intField)
s.intField ∞= s.intField∞? + 1
XCTAssertEqual(s.intField∞?, c.intField)
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.uInt32Field.conduit(c∞\.uInt32Field)) {
c.uInt32Field += 1
XCTAssertEqual(s.uInt32Field∞?, c.uInt32Field)
s.uInt32Field ∞= s.uInt32Field∞? + 1
// FIXME: this fails; maybe the Obj-C conversion is not exact?
// XCTAssertEqual(s.uInt32Field∞?, c.uInt32Field)
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.intField <~∞~> c∞\.numberField) {
c.numberField = NSNumber(value: c.numberField.intValue + 1)
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
s.intField ∞= s.intField∞? + 1
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
s.numberField <~∞~> c∞\.intField
c.intField += 1
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
s.numberField ∞= NSNumber(value:s.numberField∞?.intValue + 1)
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
s.numberField <~∞~> c∞\.doubleField
c.doubleField += 1
XCTAssertEqual(s.doubleField∞?, c.numberField.doubleValue)
s.numberField ∞= NSNumber(value: s.numberField∞?.doubleValue + 1)
XCTAssertEqual(s.doubleField∞?, c.numberField.doubleValue)
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
s.numberField <~∞~> c∞\.int8Field
// FIXME: crash!
// c.int8Field += 1
XCTAssertEqual(s.int8Field∞?, c.numberField.int8Value)
// s.numberField ∞= NSNumber(char: s.numberField.value.charValue + 1)
XCTAssertEqual(s.int8Field∞?, c.numberField.int8Value)
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
s.numberField <~∞~> c∞\.intField
c.intField += 1
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
s.numberField ∞= NSNumber(value: s.numberField∞?.intValue + 1)
XCTAssertEqual(s.intField∞?, c.numberField.intValue)
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.doubleField <~∞~> c∞\.floatField) {
c.floatField += 1
XCTAssertEqual(s.doubleField∞?, Double(c.floatField))
s.doubleField ∞= s.doubleField∞? + 1
XCTAssertEqual(s.doubleField∞?, Double(c.floatField))
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.doubleField <~∞~> c∞\.intField) {
c.intField += 1
XCTAssertEqual(s.doubleField∞?, Double(c.intField))
s.doubleField ∞= s.doubleField∞? + 1
XCTAssertEqual(s.doubleField∞?, Double(c.intField))
s.doubleField ∞= s.doubleField∞? + 0.5
XCTAssertNotEqual(s.doubleField∞?, Double(c.intField)) // will be rounded
}
}
autoreleasepool {
let s = NumericHolderStruct()
let c = NumericHolderClass()
withExtendedLifetime(s.decimalNumberField <~∞~> c∞\.numberField) {
c.numberField = NSNumber(value: c.numberField.intValue + 1)
XCTAssertEqual(s.decimalNumberField∞?, c.numberField)
s.decimalNumberField ∞= NSDecimalNumber(string: "9e12")
XCTAssertEqual(s.decimalNumberField∞?, c.numberField)
}
}
// autoreleasepool {
// let o = NumericHolderOptionalStruct()
// let c = NumericHolderClass()
// c∞\.dbl <~∞~> o∞\.dbl
// o.dbl ∞= 12.34
// XCTAssertEqual(12.34, c.dbl)
//
// // FIXME: crash (“could not set nil as the value for the key doubleField”), since NumericHolderClass.dbl cannot accept optionals; the conduit works because non-optionals are allowed to be cast to optionals
//// o.dbl ∞= nil
// }
}
func testValueToReference() {
let startCount = StatefulObjectCount
let countObs: () -> (Int) = { StatefulObjectCount - startCount }
var holder2: StatefulObjectHolder?
autoreleasepool {
XCTAssertEqual(0, countObs())
let ob = StatefulObject()
XCTAssertEqual(1, countObs())
_ = StatefulObjectHolder(ob: ob)
holder2 = StatefulObjectHolder(ob: ob)
XCTAssert(holder2 != nil)
}
XCTAssertEqual(1, countObs())
XCTAssert(holder2 != nil)
holder2 = nil
XCTAssertEqual(0, countObs())
}
/// Demonstrates using bindings with Core Data
func testManagedObjectContext() {
autoreleasepool {
do {
let attrName = NSAttributeDescription()
attrName.name = "fullName"
attrName.attributeType = .stringAttributeType
attrName.defaultValue = "John Doe"
attrName.isOptional = true
let attrAge = NSAttributeDescription()
attrAge.name = "age"
attrAge.attributeType = .integer16AttributeType
attrAge.isOptional = false
let personEntity = NSEntityDescription()
personEntity.name = "Person"
personEntity.properties = [attrName, attrAge]
personEntity.managedObjectClassName = NSStringFromClass(CoreDataPerson.self)
let model = NSManagedObjectModel()
model.entities = [personEntity]
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
_ = try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
let ctx = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
ctx.persistentStoreCoordinator = psc
var saveCount = 0
_ = ctx.channelZNotification(.NSManagedObjectContextDidSave).receive { _ in saveCount = saveCount + 1 }
var inserted = 0
ctx.channelZProcessedInserts().receive { inserted = $0.count }
var updated = 0
ctx.channelZProcessedUpdates().receive { updated = $0.count }
var deleted = 0
ctx.channelZProcessedDeletes().receive { deleted = $0.count }
var refreshed = 0
ctx.channelZProcessedRefreshes().receive { refreshed = $0.count }
var invalidated = 0
ctx.channelZProcessedInvalidates().receive { invalidated = $0.count }
XCTAssertEqual(0, refreshed)
XCTAssertEqual(0, invalidated)
let ob = NSManagedObject(entity: personEntity, insertInto: ctx)
// make sure we really created our managed object subclass
// XCTAssertEqual("ChannelZTests.CoreDataPerson_Person_", NSStringFromClass(type(of: ob)))
let person = ob as! CoreDataPerson
var ageChanges = 0, nameChanges = 0
// sadly, automatic keypath identification doesn't yet work for NSManagedObject subclasses
// person∞person.age ∞> { _ in ageChanges += 1 }
// person∞person.fullName ∞> { _ in nameChanges += 1 }
// @NSManaged fields can secretly be nil
person.channelZKeyValue(\.age) ∞> { _ in ageChanges += 1 }
person.channelZKeyValue(\.fullName) ∞> { _ in nameChanges += 1 }
person.fullName = "Edward Norton"
// “CoreData: error: Property 'setAge:' is a scalar type on class 'ChannelTests.CoreDataPerson' that does not match its Entity's property's scalar type. Dynamically generated accessors do not support implicit type coercion. Cannot generate a setter method for it.”
person.age = 65
// field tracking doesn't work either...
// XCTAssertEqual(1, nameChanges)
// XCTAssertEqual(1, ageChanges)
// ob.setValue("Bob Jones", forKey: "fullName")
// ob.setValue(65 as NSNumber, forKey: "age")
XCTAssertEqual(0, saveCount)
try ctx.save()
XCTAssertEqual(1, saveCount)
XCTAssertEqual(1, inserted)
XCTAssertEqual(0, updated)
XCTAssertEqual(0, deleted)
// ob.setValue("Frank Underwood", forKey: "fullName")
person.fullName = "Tyler Durden"
// XCTAssertEqual(2, nameChanges)
try ctx.save()
XCTAssertEqual(2, saveCount)
XCTAssertEqual(1, inserted)
XCTAssertEqual(0, updated)
XCTAssertEqual(0, deleted)
ctx.delete(ob)
try ctx.save()
XCTAssertEqual(3, saveCount)
XCTAssertEqual(0, inserted)
XCTAssertEqual(0, updated)
XCTAssertEqual(1, deleted)
ctx.undoManager = nil
ctx.reset()
} catch let error {
XCTFail("error: \(error)")
}
}
#if DEBUG_CHANNELZ
XCTAssertEqual(0, ChannelZKeyValueObserverCount.get(), "KV observers were not cleaned up")
#endif
}
func testDetachedReceiver() {
// fails in Travis run: /Users/travis/build/glimpseio/ChannelZ/Tests/ChannelZTests/KeyPathTests.swift:1392: error: -[ChannelZTests.KeyPathTests testDetachedReceiver] : failed: caught "NSInternalInconsistencyException", "An instance 0x7f852d040760 of class ChannelZTests.StatefulObject was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x7f852b5ab320> (
var subscription: Receipt?
autoreleasepool {
let state = StatefulObject()
subscription = state.channelZKeyValue(\.reqnsstr).receive({ _ in })
XCTAssertEqual(1, StatefulObjectCount)
}
XCTAssertEqual(0, StatefulObjectCount) // the object should not be retained by the subscription
subscription!.cancel() // ensure that the subscription doesn't try to access a bad pointer
}
func teststFieldRemoval() {
#if DEBUG_CHANNELZ
let startCount = ChannelZKeyValueObserverCount.get()
#endif
let startObCount = StatefulObjectCount
autoreleasepool {
var changes = 0
let ob = StatefulObject()
XCTAssertEqual(0, ob.int)
let channel = (ob ∞ \.int)
channel.subsequent().receive { _ in changes += 1 }
#if DEBUG_CHANNELZ
// XCTAssertEqual(Int64(1), ChannelZKeyValueObserverCount.get() - startCount)
#endif
XCTAssertEqual(0, changes)
ob.int += 1
XCTAssertEqual(1, changes)
ob.int += 1
XCTAssertEqual(2, changes)
}
#if DEBUG_CHANNELZ
XCTAssertEqual(Int64(0), ChannelZKeyValueObserverCount.get() - startCount)
#endif
XCTAssertEqual(0, StatefulObjectCount - startObCount)
}
func testManyKeyReceivers() {
#if DEBUG_CHANNELZ
let startCount = ChannelZKeyValueObserverCount.get()
let startObCount = StatefulObjectCount
autoreleasepool {
let ob = StatefulObject()
let channel = ob.channelZKeyValue(\.int).subsequent()
for count in 1...20 {
var changes = 0
for _ in 1...count {
// using the keypath name because it is faster than auto-identification
// (ob ∞ (ob.int)).receive { _ in changes += 1 }
channel.receive { _ in changes += 1 }
}
// XCTAssertEqual(Int64(1), ChannelZKeyValueObserverCount.get() - startCount)
XCTAssertEqual(0 * count, changes)
ob.int += 1
XCTAssertEqual(1 * count, changes)
ob.int += 1
XCTAssertEqual(2 * count, changes)
}
withExtendedLifetime(ob) { }
}
XCTAssertEqual(Int64(0), ChannelZKeyValueObserverCount.get() - startCount)
XCTAssertEqual(0, StatefulObjectCount - startObCount)
#endif
}
func testManyObserversOnBlockOperation() {
let state = StatefulObject()
XCTAssertEqual("ChannelZTests.StatefulObject", NSStringFromClass(type(of: state)))
state∞\.int ∞> { _ in }
// XCTAssertEqual("NSKVONotifying_ChannelZTests.StatefulObject", NSStringFromClass(type(of: state)))
let operation = Operation()
XCTAssertEqual("NSOperation", NSStringFromClass(type(of: operation)))
operation∞\.isCancelled ∞> { _ in }
operation∞(\.isCancelled, "cancelled") ∞> { _ in }
// XCTAssertEqual("NSKVONotifying_NSOperation", NSStringFromClass(type(of: operation)))
// progress is not automatically instrumented with NSKVONotifying_ (implying that it handles its own KVO)
let progress = Progress()
XCTAssertEqual("NSProgress", NSStringFromClass(type(of: progress)))
progress∞\.fractionCompleted ∞> { _ in }
progress∞(\.fractionCompleted, "fractionCompleted") ∞> { _ in }
XCTAssertEqual("NSProgress", NSStringFromClass(type(of: progress)))
for _ in 1...10 {
autoreleasepool {
let op = Operation()
let channel = op.channelZKeyValue(\.isCancelled, path: "cancelled")
var subscriptions: [Receipt] = []
for _ in 1...10 {
let subscription = channel ∞> { _ in }
subscriptions += [subscription as Receipt]
}
// we will crash if we rely on the KVO auto-removal here
for x in subscriptions { x.cancel() }
}
}
}
func testNSOperationObservers() {
for _ in 1...10 {
autoreleasepool {
let op = Operation()
XCTAssertEqual("NSOperation", NSStringFromClass(type(of: op)))
var ptrs: [UnsafeMutableRawPointer?] = []
for _ in 1...10 {
let ptr: UnsafeMutableRawPointer? = nil
ptrs.append(ptr)
op.addObserver(self, forKeyPath: "cancelled", options: .new, context: ptr)
}
// println("removing from: \(NSStringFromClass(op.dynamicType))")
for ptr in ptrs {
// changed in Swift 4
// XCTAssertEqual("NSKVONotifying_NSOperation", NSStringFromClass(type(of: op)))
op.removeObserver(self, forKeyPath: "cancelled", context: ptr)
}
// gets swizzled back to the original class when there are no more observers
XCTAssertEqual("NSOperation", NSStringFromClass(type(of: op)))
}
}
}
let AutoKeypathPerfomanceCount = 10
func testAutoKeypathPerfomanceWithoutName() {
let prog = Progress()
for _ in 1...AutoKeypathPerfomanceCount {
prog∞\.totalUnitCount ∞> { _ in }
}
}
func testAutoKeypathPerfomanceWithName() {
_ = Progress()
for _ in 1...AutoKeypathPerfomanceCount {
// prog∞(prog.totalUnitCount, "totalUnitCount") ∞> { _ in }
}
}
func testPullFiltered() {
let intField = ∞(Int(0))∞
_ = intField.map({ Int32($0) }).map({ Double($0) }).map({ Float($0) })
_ = intField.map({ Int32($0) }).map({ Double($0) }).map({ Float($0) })
let intToUIntChannel = intField.filter({ $0 >= 0 }).map({ UInt($0) })
var lastUInt = UInt(0)
intToUIntChannel.receive({ lastUInt = $0 })
intField ∞= 10
XCTAssertEqual(UInt(10), lastUInt)
XCTAssertEqual(Int(10), intToUIntChannel∞?)
intField ∞= -1
XCTAssertEqual(UInt(10), lastUInt, "changing a filtered value shouldn't pass down")
XCTAssertEqual(-1, intToUIntChannel∞?, "pulling a filtered field should yield nil")
}
// func testChannelSignatures() {
// let small = ∞(Int8(0))∞
// let larger = small.map({ Int16($0) }).map({ Int32($0) }).map({ Int64($0) })
// let largerz = larger
//
// let large = ∞(Int64(0))∞
// let smallerRaw = large.map({ Int32($0) }).map({ Int16($0) }).map({ Int8($0) })
//// let smallerClamped = large.map({ let ret: Int32 = $0 > Int64(Int32.max) ? Int32.max : $0 < Int64(Int32.min) ? Int32.min : Int32($0); return ret }).map({ let ret: Int16 = $0 > Int32(Int16.max) ? Int16.max : $0 < Int32(Int16.min) ? Int16.min : Int16($0); return ret }).map({ let ret: Int8 = $0 > Int16(Int8.max) ? Int8.max : $0 < Int16(Int8.min) ? Int8.min : Int8($0); return ret })
//
//// let smaller2 = large.filter({ $0 >= Int64(Int32.min) && $0 <= Int64(Int32.max) }).map({ Int32($0) }).filter({ $0 >= Int32(Int16.min) && $0 <= Int32(Int16.max) }).map({ Int16($0) }) // .filter({ $0 >= Int16(Int8.min) && $0 <= Int16(Int8.max) }).map({ Int8($0) })
// let smallerz = smallerRaw
//
// let link = conduit(largerz, smallerz)
//
// large ∞= 1
// XCTAssertEqual(large∞?, Int64(small∞?), "stable conduit")
//
// large ∞= Int64(Int8.max)
// XCTAssertEqual(large∞?, Int64(small∞?), "stable conduit")
//
// large ∞= Int64(Int8.max) + 1
// XCTAssertNotEqual(large∞?, Int64(small∞?), "unstable conduit")
//
// }
func testObservableCleanup() {
autoreleasepool {
var counter = 0, opened = 0, closed = 0, canUndo = 0, canRedo = 0, levelsOfUndo = 0
let undo = InstanceTrackingUndoManager()
undo.beginUndoGrouping()
XCTAssertEqual(1, InstanceTrackingUndoManagerInstanceCount)
undo∞\.canUndo ∞> { _ in canUndo += 1 }
undo∞\.canRedo ∞> { _ in canRedo += 1 }
undo∞\.levelsOfUndo ∞> { _ in levelsOfUndo += 1 }
undo∞\.undoActionName ∞> { _ in counter += 1 }
undo∞\.redoActionName ∞> { _ in counter += 1 }
undo.channelZNotification(.NSUndoManagerDidOpenUndoGroup).receive({ _ in opened += 1 })
undo.channelZNotification(.NSUndoManagerDidCloseUndoGroup).receive({ _ in closed += 1 })
counter = 0
XCTAssertEqual(0, counter)
XCTAssertEqual(0, opened)
assertChanges(opened, undo.beginUndoGrouping())
assertChanges(closed, undo.endUndoGrouping())
assertRemains(closed, undo.beginUndoGrouping())
assertRemains(opened, undo.endUndoGrouping())
undo.endUndoGrouping()
undo.undo() // final undo needed or else the NSUndoManager won't be release (by the run loop?)
XCTAssertEqual(1, InstanceTrackingUndoManagerInstanceCount)
}
XCTAssertEqual(0, InstanceTrackingUndoManagerInstanceCount)
}
func testOperationChannels() {
// wrap test in an XCTAssert because it will perform a try/catch
// file:///opt/src/impathic/glimpse/ChannelZ/ChannelTests/ChannelTests.swift: test failure: -[ChannelTests testOperationChannels()] failed: XCTAssertTrue failed: throwing "Cannot remove an observer <ChannelZ.TargetObserverRegister 0x10038d5b0> for the key path "isFinished" from <NSBlockOperation 0x1003854d0> because it is not registered as an observer." -
XCTAssert(operationChannelTest())
}
func operationChannelTest() -> Bool {
for (doCancel, doStart) in [(true, false), (false, true)] {
let op = BlockOperation { () -> Void in }
_ = op.channelZKeyValue(\.isCancelled, path: "isCancelled")
var cancelled: Bool = false
op.channelZKeyValue(\.isCancelled, path: "isCancelled").receive { cancelled = $0 }
var asynchronous: Bool = false
op.channelZKeyValue(\.isAsynchronous, path: "isAsynchronous").receive { asynchronous = $0 }
var executing: Bool = false
op.channelZKeyValue(\.isExecuting, path: "isExecuting").receive { [unowned op] in
executing = $0
_ = ("executing=\(executing) op: \(op)")
}
op.channelZKeyValue(\.isExecuting, path: "isExecuting").map({ !$0 }).filter({ $0 }).receive { [unowned op] in
_ = ("executing=\($0) op: \(op)")
}
var finished: Bool = false
op.channelZKeyValue(\.isFinished, path: "isFinished").receive { finished = $0 }
var ready: Bool = false
op.channelZKeyValue(\.isReady, path: "isReady").receive { ready = $0 }
XCTAssertEqual(false, cancelled)
XCTAssertEqual(false, asynchronous)
XCTAssertEqual(false, executing)
XCTAssertEqual(false, finished)
XCTAssertEqual(true, ready)
if doCancel {
op.cancel()
} else if doStart {
op.start()
}
// XCTAssertEqual(doCancel, cancelled)
XCTAssertEqual(false, asynchronous)
XCTAssertEqual(false, executing)
// XCTAssertEqual(doStart, finished)
// XCTAssertEqual(false, ready) // seems rather indeterminate
}
return true
}
func testStraightConduit() {
let state1 = StatefulObject()
let state2 = StatefulObject()
// note that since we allow 1 re-entrant pass, we're going to be set to X+(off * 2)
let conduit = (state1∞\.int).conduit(state2∞\.int)
defer { conduit.cancel() }
state1.int += 1
XCTAssertEqual(state1.int, 1)
XCTAssertEqual(state2.int, 1)
state2.int += 1
XCTAssertEqual(state1.int, 2)
XCTAssertEqual(state2.int, 2)
}
func testKVOReentrancy() {
KVOReentrancyTest(limit: ChannelZReentrancyLimit)
// disabled so this doesn't muck up parallel testing
// let limit = ChannelZReentrancyLimit
// defer { ChannelZReentrancyLimit = limit } // defer
// for lim in limit...limit+11 {
// ChannelZReentrancyLimit = lim
// KVOReentrancyTest(limit: lim)
// }
}
/// Test reentrancy guards for conduits that would never achieve equilibrium
func KVOReentrancyTest(limit: Int) {
// we expect the ChannelZReentrantReceptions to be incremented; clear it so we don't fail in tearDown
ChannelZ.ChannelZReentrantReceptions.set(0)
defer { ChannelZ.ChannelZReentrantReceptions.set(0) }
let state1 = StatefulObject()
let state2 = StatefulObject()
// note that since we allow 1 re-entrant pass, we're going to be set to X+(off * 2)
let delta = (3...100).randomElement()!
// link stat1.int to state2.int with an offset mapping
let receipt = (state1∞\.int).map({ $0 + delta }).conduit(state2∞\.int)
// we've observed intermittent crashes here…
withExtendedLifetime(receipt) {
XCTAssertEqual(0, ChannelZReentrantReceptions.get())
let inc = (3...100).randomElement()!
state1.int += inc
XCTAssertEqual(1, ChannelZReentrantReceptions.get())
XCTAssertEqual(state1.int, inc + ((limit + 2) * delta))
XCTAssertEqual(state2.int, inc + ((limit + 2) * delta))
}
receipt.cancel()
state1.int = 0
state2.int = 0
let receipt2 = (state1∞\.int).map({ $0 + delta }).conduit(state2∞\.int)
withExtendedLifetime(receipt2) {
let inc = (3...100).randomElement()!
state2.int += inc
XCTAssertEqual(2, ChannelZReentrantReceptions.get())
XCTAssertEqual(state1.int, inc + ((limit + 1) * delta)) // different from above because state1 is the dominant side
XCTAssertEqual(state2.int, inc + ((limit + 2) * delta))
}
receipt2.cancel()
}
func testKVOConduit() {
let state1 = StatefulObject()
let state2 = StatefulObject()
state1.int = 1
state2.int = 2
XCTAssertEqual(1, state1.int)
XCTAssertEqual(2, state2.int)
let i1 = (state1∞\.int)
let i2 = (state2∞\.int)
XCTAssertEqual(1, state1.int)
XCTAssertEqual(2, state2.int)
// let rcvr = i1.bind(i2)
let rcvr = i2.conduit(i1)
XCTAssertEqual(2, state1.int)
XCTAssertEqual(2, state2.int)
state2.int += 1
XCTAssertEqual(3, state1.int)
XCTAssertEqual(3, state2.int)
state1.int += 1
XCTAssertEqual(4, state1.int)
XCTAssertEqual(4, state2.int)
rcvr.cancel() // unbind
state2.int += 1
XCTAssertEqual(4, state1.int)
XCTAssertEqual(5, state2.int)
}
func testKVOBind() {
let state1 = StatefulObject()
let state2 = StatefulObject()
state1.int = 1
state2.int = 2
XCTAssertEqual(1, state1.int)
XCTAssertEqual(2, state2.int)
let i1 = (state1∞\.int)
let i2 = (state2∞\.int)
XCTAssertEqual(1, state1.int)
XCTAssertEqual(2, state2.int)
let rcvr = i1.bind(i2)
// let rcvr = i2.bind(i1)
XCTAssertEqual(1, state1.int)
XCTAssertEqual(1, state2.int)
state2.int += 2
XCTAssertEqual(3, state1.int)
XCTAssertEqual(3, state2.int)
state1.int += 1
XCTAssertEqual(4, state1.int)
XCTAssertEqual(4, state2.int)
rcvr.cancel() // unbind
state2.int += 1
XCTAssertEqual(4, state1.int)
XCTAssertEqual(5, state2.int)
}
/// Test reentrancy guards for conduits that would never achieve equilibrium
func testKVOBindOptional() {
let state1 = StatefulObject()
let state2 = StatefulObject()
state1.num1 = nil
state2.num1 = 2
XCTAssertEqual(nil, state1.num1)
XCTAssertEqual(2, state2.num1)
let i1 = (state1∞\.num1)
let i2 = (state2∞\.num1)
XCTAssertEqual(nil, state1.num1)
XCTAssertEqual(2, state2.num1)
let rcvr = i1.bindOptionalPulseToPulse(i2)
// let rcvr = i2.bind(i1)
XCTAssertEqual(nil, state1.num1)
// XCTAssertEqual(nil, state2.num1) // FIXME: should nil out num1
state2.num1 = 2
// XCTAssertEqual(2, state1.num1) // FIXME: set num1 to 2
XCTAssertEqual(2, state2.num1)
state2.num1 = NSNumber(value: state2.num1!.intValue + 1)
XCTAssertEqual(3, state1.num1)
XCTAssertEqual(3, state2.num1)
state1.num1 = NSNumber(value: state1.num1!.intValue + 1)
XCTAssertEqual(4, state1.num1)
XCTAssertEqual(4, state2.num1)
state1.num1 = nil
XCTAssertEqual(nil, state1.num1)
XCTAssertEqual(nil, state2.num1)
state2.num1 = 99
XCTAssertEqual(99, state1.num1)
XCTAssertEqual(99, state2.num1)
rcvr.cancel() // unbind
state2.num1 = NSNumber(value: state2.num1!.intValue + 1)
XCTAssertEqual(99, state1.num1)
XCTAssertEqual(100, state2.num1)
}
/// Test reentrancy guards for conduits that would never achieve equilibrium
func testSwiftReentrancy() {
func reentrants() -> Int64 {
let x = ChannelZReentrantReceptions.get()
ChannelZReentrantReceptions.set(0)
return x
}
let state1 = ∞=Int(0)=∞
let state2 = ∞=Int(0)=∞
let state3 = ∞=Int(0)=∞
XCTAssertEqual(0, reentrants())
// note that since we allow 1 re-entrant pass, we're going to be set to X+(off * 2)
state1.map({ $0 + 1 }).conduit(state2)
state2.map({ $0 + 2 }).conduit(state3)
state3.map({ $0 + 3 }).conduit(state1)
state3.map({ $0 + 4 }).conduit(state2)
state3.map({ $0 + 5 }).conduit(state3)
XCTAssertEqual(166, reentrants())
state1 ∞= state1∞? + 1
XCTAssertEqual(state1∞?, 30)
XCTAssertEqual(state2∞?, 30)
XCTAssertEqual(state3∞?, 31)
XCTAssertEqual(185, reentrants())
state2 ∞= state2∞? + 1
XCTAssertEqual(state1∞?, 35)
XCTAssertEqual(state2∞?, 35)
XCTAssertEqual(state3∞?, 36)
XCTAssertEqual(112, reentrants())
state3 ∞= state3∞? + 1
XCTAssertEqual(state1∞?, 42)
XCTAssertEqual(state2∞?, 43)
XCTAssertEqual(state3∞?, 42)
XCTAssertEqual(139, reentrants())
// we expect the ChannelZReentrantReceptions to be incremented; clear it so we don't fail in tearDown
_ = reentrants()
}
// func testRequiredToOptional() {
// let state1 = ∞Int(0)∞
// let state2 = ∞Optional<Int>()∞
//
// state1.map({ Optional<Int>($0) }) ∞-> state2
//
// XCTAssertEqual(0, state1∞?)
// XCTAssertEqual(999, state2∞? ?? 999)
//
// state1 ∞= state1∞? + 1
//
// XCTAssertEqual(1, state1∞?)
// XCTAssertEqual(1, state2∞? ?? 999)
//
// }
func testMemory2() {
autoreleasepool {
let md1 = MemoryDemo()
let md2 = MemoryDemo()
let cndt = (md1∞\.stringField).conduit(md2∞\.stringField)
md1.stringField += "Hello "
md2.stringField += "World"
XCTAssertEqual(md1.stringField, "Hello World")
XCTAssertEqual(md2.stringField, "Hello World")
XCTAssertEqual(2, MemoryDemoCount)
cndt.cancel()
}
// subscriptions are retained by the channel sources
XCTAssertEqual(0, MemoryDemoCount)
}
func testAutoKVOIdentification() {
let state = StatefulObjectSubSubclass()
var count = 0
let _ : Receipt = state.channelZKeyValue(\.optstr) ∞> { _ in count += 1 }
state∞\.reqstr ∞> { _ in count += 1 }
state∞\.optnsstr ∞> { _ in count += 1 }
state∞\.reqnsstr ∞> { _ in count += 1 }
state∞\.int ∞> { _ in count += 1 }
state∞\.dbl ∞> { _ in count += 1 }
state∞\.num1 ∞> { _ in count += 1 }
state∞\.num2 ∞> { _ in count += 1 }
state∞\.num3 ∞> { _ in count += 1 }
state∞\.num3 ∞> { _ in count += 1 }
state∞\.reqobj ∞> { _ in count += 1 }
state∞\.optobj ∞> { _ in count += 1 }
}
func testSimpleObservation() {
var observer: NSKeyValueObservation?
autoreleasepool {
let ob = StatefulObject()
var changes = 0
observer = ob.observe(\.reqstr) { (x, y) in
changes += 1
}
for _ in 1...3 {
ob.reqstr += "x"
}
XCTAssertEqual(3, changes)
observer?.invalidate()
}
}
func testDeepKeyPath() {
testDeepKeyPath(withSeparateChannel: true)
// testDeepKeyPath(withSeparateChannel: false) // fails because the channel is unretained
}
func testDeepKeyPath(withSeparateChannel: Bool) {
typealias T = StatefulObjectSubSubclass
let state = T()
var count = 0
let rcvr: Receipt
var channel: KeyStateChannel<T, Int>?
if withSeparateChannel {
channel = state.channelZKeyState(\.state.int)
rcvr = channel!.receive({ _ in
count += 1
})
} else {
rcvr = state.channelZKeyState(\.state.int).receive({ _ in
count += 1
})
}
assertChanges(count, state.setValue(state.state.int + 1, forKeyPath: "state.int"))
assertChanges(count, state.state.int += 1)
let oldstate = state.state
assertChanges(count, state.state = StatefulObject())
assertRemains(count, oldstate.int += 1, msg: "should not be watching stale state")
assertChanges(count, state.state.int += 1)
assertChanges(count, state.state.int -= 1)
assertChanges(count, state.state = StatefulObject(), msg: "new intermediate with same terminal value should not pass sieve") // or should it?
rcvr.cancel()
// defer { rcvr.cancel() }
// XCTAssertNotNil(rcvr)
}
func testDeepOptionalKeyPath() {
let state = StatefulObjectSubSubclass()
var count = 0
let channel = state∞(\.optobj?.optobj?.int)
channel ∞> { _ in count += 1 }
if false { // something changed in the macOS 10.15.3 -> 10.15.4 upgrade that broke this!
assertChanges(count, state.optobj = StatefulObjectSubSubclass())
assertChanges(count, state.optobj!.optobj = StatefulObjectSubSubclass())
assertChanges(count, state.optobj!.optobj!.int += 1)
}
}
func testCollectionArrayKeyPaths() {
let state = StatefulObjectSubSubclass()
var changes = 0
let rcvr = state.channelZCollection(\.array).receive { change in
switch change {
case .assigned(_): break
case .added(let indices, _): changes += indices.count
case .removed(let indices, _): changes += indices.count
case .replaced(let indices, _, _): changes += indices.count
}
}
let array = state.mutableArrayValue(forKey: "array")
array.add("One") // +1
array.add("Two") // +1
array.add("Three") // +1
array.removeObject(at: 1) // -1
array.replaceObject(at: 1, with: "None") // +-1
array.removeAllObjects() // -2
array.addObjects(from: ["A", "B", "C", "D"]) // +4
XCTAssertEqual(11, changes)
XCTAssertNotNil(rcvr)
}
func testCollectionOrderedSetKeyPaths() {
let state = StatefulObjectSubSubclass()
var changes = 0
let channel = state.channelZCollection(\.orderedSet).receive { change in
switch change {
case .assigned: break
case .added(let indices, _): changes += indices.count
case .removed(let indices, _): changes += indices.count
case .replaced(let indices, _, _): changes += indices.count
}
}
let orderedSet = state.mutableOrderedSetValue(forKey: "orderedSet")
orderedSet.add("One") // +1
orderedSet.add("Two") // +1
orderedSet.add("Three") // +1
orderedSet.add("One") // +0
orderedSet.add("Two") // +0
orderedSet.add("Three") // +0
orderedSet.add("Four") // +1
orderedSet.removeObject(at: 1) // -1
orderedSet.replaceObject(at: 1, with: "None") // +-1
orderedSet.removeAllObjects() // -3
orderedSet.addObjects(from: ["A", "B", "C", "D"]) // +4
XCTAssertEqual(13, changes)
XCTAssertNotNil(channel)
}
func testCollectionSetKeyPaths() {
// the new Swift 4 observe() behaves differently with Sets; it no longer reports the inserted or removed elements
let state = StatefulObjectSubSubclass()
var changes = 0
let receiver = state.channelZCollection(\.set).receive { change in
switch change {
case .assigned: break
case .added: changes += 1 // changes += new.count
case .removed: changes += 1 // changes += old.count
}
}
let set = state.mutableSetValue(forKey: "set")
set.add("One")
set.add("Two")
set.add("Three")
set.add("One")
set.add("Two")
set.add("Three")
set.remove("Two")
set.remove("nonexistant") // shouldn't fire
// XCTAssertEqual(4, changes)
XCTAssertEqual(8, changes)
XCTAssertNotNil(receiver)
}
private var keptalive = Array<Any>()
/// Keep the given object alive for the duration of the test; useful for channels that automatically cleanup resources upon deallocation
func keepalive<T>(_ ob: T) -> T {
keptalive.append(ob)
return ob
}
override func tearDown() {
super.tearDown()
keptalive.removeAll()
// ensure that all the bindings and observers are properly cleaned up
#if DEBUG_CHANNELZ
XCTAssertEqual(0, ChannelZTests.StatefulObjectCount, "\(self.name) all StatefulObject instances should have been deallocated")
ChannelZTests.StatefulObjectCount = 0
XCTAssertEqual(0, ChannelZ.ChannelZKeyValueObserverCount.get(), "\(self.name) KV observers were not cleaned up")
ChannelZ.ChannelZKeyValueObserverCount.set(0)
// tests that expect reentrant detection should manually clear it with ChannelZReentrantReceptions = 0
XCTAssertEqual(0, ChannelZ.ChannelZReentrantReceptions.get(), "\(self.name) unexpected reentrant receptions detected")
ChannelZ.ChannelZReentrantReceptions.set(0)
// XCTAssertEqual(0, ChannelZ.ChannelZNotificationObserverCount.get(), "Notification observers were not cleaned up")
// ChannelZ.ChannelZNotificationObserverCount = 0
#else
XCTFail("ChannelZ debugging must be enabled for tests – e.g.: swift test -Xswiftc -DDEBUG_CHANNELZ")
#endif
}
}
struct StatefulObjectHolder {
let ob: StatefulObject
}
enum SomeEnum { case yes, no, maybeSo }
struct SwiftStruct {
var intField: Int
var stringField: String?
var enumField: SomeEnum = .no
}
struct SwiftEquatableStruct : Equatable {
var intField: Int
var stringField: String?
var enumField: SomeEnum = .no
}
func == (lhs: SwiftEquatableStruct, rhs: SwiftEquatableStruct) -> Bool {
return lhs.intField == rhs.intField && lhs.stringField == rhs.stringField && lhs.enumField == rhs.enumField
}
struct SwiftObservables {
let stringField = ∞=("")=∞
let enumField = ∞=(SomeEnum.no)=∞
let swiftStruct = ∞(SwiftStruct(intField: 1, stringField: "", enumField: .yes))∞
}
var StatefulObjectCount = 0
class StatefulObject : NSObject {
@objc dynamic var optstr: String?
@objc dynamic var reqstr: String = ""
@objc dynamic var optnsstr: NSString?
@objc dynamic var reqnsstr: NSString = ""
@objc dynamic var int: Int = 0
@objc dynamic var dbl: Double = 0
@objc dynamic var num1: NSNumber?
@objc dynamic var num2: NSNumber?
@objc dynamic var num3: NSNumber = 9
@objc dynamic var reqobj: NSObject = NSObject()
@objc dynamic var optobj: StatefulObject? = nil
@objc dynamic var array = NSMutableArray()
@objc dynamic var set = NSMutableSet()
@objc dynamic var orderedSet = NSMutableOrderedSet()
override init() {
super.init()
StatefulObjectCount += 1
}
deinit {
StatefulObjectCount -= 1
}
}
class StatefulObjectSubclass : StatefulObject {
@objc dynamic var state = StatefulObject()
}
final class StatefulObjectSubSubclass : StatefulObjectSubclass { }
var InstanceTrackingUndoManagerInstanceCount = 0
class InstanceTrackingUndoManager : UndoManager {
override init() {
super.init()
InstanceTrackingUndoManagerInstanceCount += 1
}
deinit {
InstanceTrackingUndoManagerInstanceCount -= 1
}
}
class CoreDataPerson : NSManagedObject {
@objc dynamic var fullName: String?
@NSManaged var age: Int16
}
var MemoryDemoCount = 0
class MemoryDemo : NSObject {
@objc dynamic var stringField : String = ""
// track creates and releases
override init() { MemoryDemoCount += 1 }
deinit { MemoryDemoCount -= 1 }
}
class NumericHolderClass : NSObject {
@objc dynamic var numberField: NSNumber = 0
@objc dynamic var decimalNumberField: NSDecimalNumber = 0
@objc dynamic var doubleField: Double = 0
@objc dynamic var floatField: Float = 0
@objc dynamic var intField: Int = 0
@objc dynamic var uInt64Field: UInt64 = 0
@objc dynamic var int64Field: Int64 = 0
@objc dynamic var uInt32Field: UInt32 = 0
@objc dynamic var int32Field: Int32 = 0
@objc dynamic var uInt16Field: UInt16 = 0
@objc dynamic var int16Field: Int16 = 0
@objc dynamic var uInt8Field: UInt8 = 0
@objc dynamic var int8Field: Int8 = 0
@objc dynamic var boolField: Bool = false
// var numberFieldZ: Channel<KeyValueTransceiver<NSNumber>, NSNumber> { return channelZKey(numberField) }
// lazy var decimalNumberFieldZ: NSDecimalNumber = 0
// lazy var doubleFieldZ: Double = 0
// lazy var floatFieldZ: Float = 0
// lazy var intFieldZ: Int = 0
// lazy var uInt64FieldZ: UInt64 = 0
// lazy var int64FieldZ: Int64 = 0
// lazy var uInt32FieldZ: UInt32 = 0
// lazy var int32FieldZ: Int32 = 0
// lazy var uInt16FieldZ: UInt16 = 0
// lazy var int16FieldZ: Int16 = 0
// lazy var uInt8FieldZ: UInt8 = 0
// lazy var int8FieldZ: Int8 = 0
// lazy var boolFieldZ: Bool = false
}
struct NumericHolderStruct {
let numberField = ∞(NSNumber(floatLiteral: 0.0))∞
let decimalNumberField = ∞=(NSDecimalNumber(floatLiteral: 0.0))=∞
let doubleField = ∞=(Double(0))=∞
let floatField = ∞=(Float(0))=∞
let intField = ∞=(Int(0))=∞
let uInt64Field = ∞=(UInt64(0))=∞
let int64Field = ∞=(Int64(0))=∞
let uInt32Field = ∞=(UInt32(0))=∞
let int32Field = ∞=(Int32(0))=∞
let uInt16Field = ∞=(UInt16(0))=∞
let int16Field = ∞=(Int16(0))=∞
let uInt8Field = ∞=(UInt8(0))=∞
let int8Field = ∞=(Int8(0))=∞
let boolField = ∞=(Bool(false))=∞
}
struct NumericHolderOptionalStruct {
let numberField = ∞=(nil as NSNumber?)=∞
let decimalNumberField = ∞=(nil as NSDecimalNumber?)=∞
let doubleField = ∞=(nil as Double?)=∞
let floatField = ∞=(nil as Float?)=∞
let intField = ∞=(nil as Int?)=∞
let uInt64Field = ∞=(nil as UInt64?)=∞
let int64Field = ∞=(nil as Int64?)=∞
let uInt32Field = ∞=(nil as UInt32?)=∞
let int32Field = ∞=(nil as Int32?)=∞
let uInt16Field = ∞=(nil as UInt16?)=∞
let int16Field = ∞=(nil as Int16?)=∞
let uInt8Field = ∞=(nil as UInt8?)=∞
let int8Field = ∞=(nil as Int8?)=∞
let boolField = ∞=(nil as Bool?)=∞
}
var ChannelThingsInstances = 0
class ChannelThing: NSObject {
let int = ∞=(0)=∞
let double = ∞=(0.0)=∞
let string = ∞=("")=∞
let stringish = ∞(nil as String?)∞
override init() { ChannelThingsInstances += 1 }
deinit { ChannelThingsInstances -= 1 }
}
#endif
|
mit
|
0e26ebd3ef7e01775dc8b556e937391c
| 33.07878 | 436 | 0.573192 | 3.977065 | false | false | false | false |
barterkwip/weather
|
WiproWeather/src/model/WeatherService.swift
|
1
|
3678
|
//
// File.swift
// WiproWeather
//
// Created by bartek on 6/13/16.
// Copyright © 2016 bartoszalksnin. All rights reserved.
//
import Foundation
import CoreData
class WeatherCondition {
let id: Int;
let description: String;
let iconUrl: String;
init(id: Int, description: String, iconUrl: String) {
self.id = id;
self.description = description;
self.iconUrl = iconUrl;
}
static func FromJson(json: NSDictionary?) -> WeatherCondition? {
guard let id = json?["id"] as? Int else { return nil }
guard let description = json?["description"] as? String else { return nil }
guard let icon = json?["icon"] as? String else { return nil }
let iconUrl = WeatherService.iconUrl + icon + ".png"
return WeatherCondition(id: id, description: description, iconUrl: iconUrl);
}
}
class WeatherStats {
let minTemperature: Int;
let maxTemperature: Int;
let humidity: Int;
init(minTemperature: Int, maxTemperature: Int, humidity: Int) {
self.minTemperature = minTemperature;
self.maxTemperature = maxTemperature;
self.humidity = humidity;
}
static func FromJson(json: NSDictionary?) -> WeatherStats? {
guard let mainStats = json?["main"] as? NSDictionary else { return nil }
guard let minTemperature = mainStats["temp_min"] as? Int else { return nil }
guard let maxTemperature = mainStats["temp_max"] as? Int else { return nil }
guard let humidity = mainStats["humidity"] as? Int else { return nil }
return WeatherStats(minTemperature: minTemperature, maxTemperature: maxTemperature, humidity: humidity);
}
}
class WeatherForecastPoint {
let weatherConditions: Array<WeatherCondition>;
let weatherStats: WeatherStats;
let date: NSDate;
init(weatherConditions: Array<WeatherCondition>, weatherStats: WeatherStats, date: Int) {
self.weatherConditions = weatherConditions;
self.weatherStats = weatherStats;
self.date = NSDate(timeIntervalSince1970: NSTimeInterval(date));
}
static func FromJson(json: NSDictionary?) -> WeatherForecastPoint? {
guard let weatherConditions = parseWeatherConditions(json) else { return nil };
guard let weatherStats = WeatherStats.FromJson(json) else { return nil };
guard let date = json?["dt"] as? Int else { return nil };
return WeatherForecastPoint(weatherConditions: weatherConditions, weatherStats: weatherStats, date: date);
}
static func parseWeatherConditions(json: NSDictionary?) -> Array<WeatherCondition>? {
guard let weatherConditionList = json?["weather"] as? NSArray else { return nil }
let weatherConditions = weatherConditionList.map({ json -> WeatherCondition? in
let item = WeatherCondition.FromJson(json as? NSDictionary)
return item
}
).filter({ item in
return item != nil
}
).map({ item in
return item!
})
return weatherConditions;
}
}
class WeatherForecast: BaseDto {
let forecastPoints: Array<WeatherForecastPoint>;
init(forecastPoints: Array<WeatherForecastPoint>) {
self.forecastPoints = forecastPoints;
}
static func FromJson(json: NSDictionary?) -> BaseDto? {
guard let forecastList = json?["list"] as? NSArray else { return nil }
let forecastPoints = forecastList.map({ json -> WeatherForecastPoint? in
let item = WeatherForecastPoint.FromJson(json as? NSDictionary)
return item
}
).filter({ item in
return item != nil
}
).map({ item in
return item!
})
return WeatherForecast(forecastPoints: forecastPoints);
}
}
class WeatherService: NetworkService<WeatherForecast> {
private static let iconUrl = "http://openweathermap.org/img/w/"
convenience init() {
self.init(methodName: "forecast");
}
override init(methodName: String) {
super.init(methodName: methodName);
}
}
|
gpl-3.0
|
afc6a76c0039089372b12d4e8b3ac063
| 28.190476 | 108 | 0.726951 | 3.748216 | false | false | false | false |
tryswift/trySwiftData
|
Example/Tests/SessionTests/MeetupSessionViewModelTests.swift
|
1
|
3362
|
//
// MeetupSessionViewModelTests.swift
// trySwiftData
//
// Created by Alvin Varghese on 26/03/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
//import XCTest
//import TrySwiftData
//
//class MeetupSessionViewModelTests: XCTestCase {
//
// //MARK: Local Variables
//
// fileprivate let meetupSession = nyc2016Sessions["preconfmeetup"]!
// fileprivate var viewModel: SessionViewModel!
//
// // No Event
//
// fileprivate var viewModel_NoEvent: SessionViewModel!
//
// // No Sponsor
//
// fileprivate var viewModel_NoSponsor: SessionViewModel!
//
// //MARK: Setup
//
// override func setUp() {
//
// viewModel = SessionViewModel(session: meetupSession)
//
// // No Event
//
// let session_NoEvent = Session()
// session_NoEvent.type = .meetup
// session_NoEvent.sponsor = Sponsor()
// session_NoEvent.location?.name = Venue.localizedName(for: .conference)
// let meetupSession_NoEvent = session_NoEvent
// viewModel_NoEvent = SessionViewModel(session: meetupSession_NoEvent)
//
// // No Sponsor
//
// let session_NoSponsor = Session()
// session_NoSponsor.type = .meetup
// session_NoSponsor.event = nyc2016Events["meetup"]
// session_NoSponsor.sponsor = nil
// viewModel_NoSponsor = SessionViewModel(session: session_NoSponsor)
// }
//
// //MARK: Event Title
//
// func test_EventTitle() {
// XCTAssertEqual( viewModel.title, meetupSession.event?.title)
// }
//
// //MARK: Default Title - No Event
//
// func test_DefaultTitle() {
// XCTAssertEqual( viewModel_NoEvent.title, "TBD")
// }
//
// //MARK: Subtitle
//
// func testPresenter() {
// XCTAssertEqual( viewModel.presenter, meetupSession.sponsor?.localizedName)
// }
//
// //MARK: Subtitle - No Sponsor
//
// func testPresenter_NoSponsor() {
// XCTAssertEqual( viewModel_NoSponsor.presenter, "try! Conference")
// }
//
// // Problem - There are no assets for New York, so Logo URL test wont work
//
//// //MARK: Logo URL
////
//// func testLogoURL() {
//// XCTAssertEqual(viewModel.logoURL.lastPathComponent, meetupSession.event?.logoAssetName)
//// }
//
// func testShortDescription() {
// XCTAssertEqual(viewModel.shortDescription, "Special Event")
// }
//
// func testLocation() {
// XCTAssertEqual(viewModel.location, meetupSession.event?.localizedLocation)
// }
//
// func testLocation_NoEvent() {
// XCTAssertEqual(viewModel_NoEvent.location, "Conference")
// }
//
// func testLongDescription() {
// XCTAssertEqual(viewModel.longDescription, Conference.current.localizedDescription)
// }
//
// func testSelectable() {
// XCTAssertFalse(meetupSession.event == nil)
// }
//
// func testTwitter() {
// XCTAssertEqual(viewModel.twitter, "@\(meetupSession.sponsor!.twitter!)")
// }
//
// func testTwitter_NoSponsor() {
// XCTAssertEqual(viewModel_NoSponsor.twitter, "@\(Conference.current.twitter!)")
// }
//
// func test_NoTwitter_ButThereIsASponsor() {
// XCTAssertEqual(viewModel_NoEvent.twitter, "@tryswiftconf")
// }
//}
|
mit
|
e9a7060688e2aef8f12c8b416c26e3de
| 27.243697 | 99 | 0.60607 | 3.751116 | false | true | false | false |
tristanhimmelman/HidingNavigationBar
|
HidingNavigationBar/HidingViewController.swift
|
1
|
5904
|
//
// HidingViewController.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tristan Himmelman
//
// 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 HidingViewController {
var child: HidingViewController?
var navSubviews: [UIView]?
var view: UIView
var expandedCenter: ((UIView) -> CGPoint)?
var alphaFadeEnabled = false
var contractsUpwards = true
init(view: UIView) {
self.view = view
}
init() {
view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
view.backgroundColor = UIColor.clear
view.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
}
func expandedCenterValue() -> CGPoint {
if let expandedCenter = expandedCenter {
return expandedCenter(view)
}
return CGPoint(x: 0, y: 0)
}
func contractionAmountValue() -> CGFloat {
return view.bounds.height
}
func contractedCenterValue() -> CGPoint {
if contractsUpwards {
return CGPoint(x: expandedCenterValue().x, y: expandedCenterValue().y - contractionAmountValue())
} else {
return CGPoint(x: expandedCenterValue().x, y: expandedCenterValue().y + contractionAmountValue())
}
}
func isContracted() -> Bool {
return Float(fabs(view.center.y - contractedCenterValue().y)) < .ulpOfOne
}
func isExpanded() -> Bool {
return Float(fabs(view.center.y - expandedCenterValue().y)) < .ulpOfOne
}
func totalHeight() -> CGFloat {
let height = expandedCenterValue().y - contractedCenterValue().y
if let child = child {
return child.totalHeight() + height
}
return height
}
func setAlphaFadeEnabled(_ alphaFadeEnabled: Bool) {
self.alphaFadeEnabled = alphaFadeEnabled
if !alphaFadeEnabled {
updateSubviewsToAlpha(1.0)
}
}
func updateYOffset(_ delta: CGFloat) -> CGFloat {
var deltaY = delta
if child != nil && deltaY < 0 {
deltaY = child!.updateYOffset(deltaY)
child!.view.isHidden = (deltaY) < 0;
}
var newYOffset = view.center.y + deltaY
var newYCenter = max(min(expandedCenterValue().y, newYOffset), contractedCenterValue().y)
if contractsUpwards == false {
newYOffset = view.center.y - deltaY
newYCenter = min(max(expandedCenterValue().y, newYOffset), contractedCenterValue().y)
}
view.center = CGPoint(x: view.center.x, y: newYCenter)
if alphaFadeEnabled {
var newAlpha: CGFloat = 1.0 - (expandedCenterValue().y - view.center.y) * 2 / contractionAmountValue()
newAlpha = CGFloat(min(max(.ulpOfOne, Float(newAlpha)), 1.0))
updateSubviewsToAlpha(newAlpha)
}
var residual = newYOffset - newYCenter
if (child != nil && deltaY > 0 && residual > 0) {
residual = child!.updateYOffset(residual)
child!.view.isHidden = residual - (newYOffset - newYCenter) > 0
}
return residual;
}
func snap(_ contract: Bool, completion:(() -> Void)!) -> CGFloat {
var deltaY: CGFloat = 0
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
if let child = self.child {
if contract && child.isContracted() {
deltaY = self.contract()
} else {
deltaY = self.expand()
}
} else {
if contract {
deltaY = self.contract()
} else {
deltaY = self.expand()
}
}
}) { (success: Bool) -> Void in
if completion != nil{
completion();
}
}
return deltaY;
}
func expand() -> CGFloat {
view.isHidden = false
if alphaFadeEnabled {
updateSubviewsToAlpha(1)
navSubviews = nil
}
var amountToMove = expandedCenterValue().y - view.center.y
view.center = expandedCenterValue()
if let child = child {
amountToMove += child.expand()
}
return amountToMove;
}
func contract() -> CGFloat {
if alphaFadeEnabled {
updateSubviewsToAlpha(0)
}
let amountToMove = contractedCenterValue().y - view.center.y
view.center = contractedCenterValue()
return amountToMove;
}
// MARK: - Private methods
// Recursively applies an operation to all views in a view hierarchy
fileprivate func applyToViewHierarchy(rootView: UIView, operation: (UIView) -> Void) {
operation(rootView)
rootView.subviews.forEach { view in
applyToViewHierarchy(rootView: view, operation: operation)
}
}
fileprivate func updateSubviewsToAlpha(_ alpha: CGFloat) {
if navSubviews == nil {
navSubviews = []
// loops through and subview and save the visible ones in navSubviews array
for subView in view.subviews {
let isBackgroundView = subView === view.subviews[0]
let isViewHidden = subView.isHidden || Float(subView.alpha) < .ulpOfOne
if isBackgroundView == false && isViewHidden == false {
navSubviews?.append(subView)
}
}
}
navSubviews?.forEach { subView in
applyToViewHierarchy(rootView: subView) { view in
view.alpha = alpha
}
}
}
}
|
mit
|
cbcbd8976c6058d39c83dd82055b0afa
| 26.981043 | 105 | 0.679878 | 3.692308 | false | false | false | false |
noppoMan/Slimane
|
Sources/Slimane/Route/Route.swift
|
1
|
1665
|
//
// Route.swift
// Slimane
//
// Created by Yuki Takei on 2016/10/05.
//
//
protocol Route: Responder {
var path: String { get }
var regexp: Regex { get }
var paramKeys: [String] { get }
var method: HTTPCore.Method { get }
var handler: Respond { get }
var middlewares: [Middleware] { get }
}
extension Route {
public func params(_ request: Request) -> [String: String] {
guard let path = request.path else {
return [:]
}
var parameters: [String: String] = [:]
let values = regexp.groups(path)
for (index, key) in paramKeys.enumerated() {
parameters[key] = values[index]
}
return parameters
}
}
struct BasicRoute: Route {
let path: String
let regexp: Regex
let method: HTTPCore.Method
let handler: Respond
let paramKeys: [String]
let middlewares: [Middleware]
init(method: HTTPCore.Method, path: String, middlewares: [Middleware] = [], handler: @escaping Respond){
let parameterRegularExpression = try! Regex(pattern: ":([[:alnum:]_]+)")
let pattern = parameterRegularExpression.replace(path, withTemplate: "([[:alnum:]_-]+)")
self.method = method
self.path = path
self.regexp = try! Regex(pattern: "^" + pattern + "$")
self.paramKeys = parameterRegularExpression.groups(path)
self.middlewares = middlewares
self.handler = handler
}
func respond(_ request: Request, _ response: Response, _ responder: @escaping (Chainer) -> Void) {
self.handler(request, response, responder)
}
}
|
mit
|
883c83338f49f5d1d8c85ec0ba0c2d54
| 27.220339 | 108 | 0.58979 | 4.172932 | false | false | false | false |
ludoded/ReceiptBot
|
Pods/Material/Sources/iOS/StatusBarController.swift
|
2
|
4500
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the StatusBarController.
This is the recommended method of accessing the StatusBarController
through child UIViewControllers.
*/
public var statusBarController: StatusBarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is StatusBarController {
return viewController as? StatusBarController
}
viewController = viewController?.parent
}
return nil
}
}
open class StatusBarController: RootController {
/**
A Display value to indicate whether or not to
display the rootViewController to the full view
bounds, or up to the toolbar height.
*/
open var statusBarDisplay = Display.full {
didSet {
layoutSubviews()
}
}
/// Device status bar style.
open var statusBarStyle: UIStatusBarStyle {
get {
return Application.statusBarStyle
}
set(value) {
Application.statusBarStyle = value
}
}
/// Device visibility state.
open var isStatusBarHidden: Bool {
get {
return Application.isStatusBarHidden
}
set(value) {
Application.isStatusBarHidden = value
statusBar.isHidden = isStatusBarHidden
}
}
/// A boolean that indicates to hide the statusBar on rotation.
open var shouldHideStatusBarOnRotation = true
/// A reference to the statusBar.
open let statusBar = UIView()
/**
To execute in the order of the layout chain, override this
method. LayoutSubviews should be called immediately, unless you
have a certain need.
*/
open override func layoutSubviews() {
super.layoutSubviews()
if shouldHideStatusBarOnRotation {
statusBar.isHidden = Application.shouldStatusBarBeHidden
}
statusBar.width = view.width
switch statusBarDisplay {
case .partial:
let h = statusBar.height
rootViewController.view.y = h
rootViewController.view.height = view.height - h
case .full:
rootViewController.view.frame = view.bounds
}
}
/**
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()
prepareStatusBar()
}
}
extension StatusBarController {
/// Prepares the statusBar.
fileprivate func prepareStatusBar() {
statusBar.backgroundColor = .white
statusBar.height = 20
view.addSubview(statusBar)
}
}
|
lgpl-3.0
|
c7db5923b438bc62e4605e3043231263
| 32.834586 | 88 | 0.692667 | 5.044843 | false | false | false | false |
hirohisa/RxSwift
|
RxSwift/RxSwift/Observables/Implementations/Sink.swift
|
11
|
1585
|
//
// Sink.swift
// Rx
//
// Created by Krunoslav Zaher on 2/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Sink<O : ObserverType> : Disposable {
private typealias Element = O.Element
typealias State = (
observer: O?,
cancel: Disposable,
disposed: Bool
)
private var lock = SpinLock()
private var _state: State
var observer: O? {
get {
return lock.calculateLocked { _state.observer }
}
}
var cancel: Disposable {
get {
return lock.calculateLocked { _state.cancel }
}
}
var state: State {
get {
return lock.calculateLocked { _state }
}
}
init(observer: O, cancel: Disposable) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
_state = (
observer: observer,
cancel: cancel,
disposed: false
)
}
func dispose() {
var cancel: Disposable? = lock.calculateLocked {
if _state.disposed {
return nil
}
var cancel = _state.cancel
_state.disposed = true
_state.observer = nil
_state.cancel = NopDisposable.instance
return cancel
}
if let cancel = cancel {
cancel.dispose()
}
}
deinit {
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
}
|
mit
|
29d7f8269589f557ca5b2c4660d6cd47
| 19.597403 | 60 | 0.505994 | 4.832317 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/Geocoding.swift
|
1
|
2026
|
import Foundation
import CoreLocation
import SwiftSignalKit
func geocodeLocation(dictionary: [String: String]) -> Signal<(Double, Double)?, NoError> {
return Signal { subscriber in
let geocoder = CLGeocoder()
geocoder.geocodeAddressDictionary(dictionary, completionHandler: { placemarks, _ in
if let location = placemarks?.first?.location {
subscriber.putNext((location.coordinate.latitude, location.coordinate.longitude))
} else {
subscriber.putNext(nil)
}
subscriber.putCompletion()
})
return ActionDisposable {
geocoder.cancelGeocode()
}
}
}
struct ReverseGeocodedPlacemark {
let street: String?
let city: String?
let country: String?
var fullAddress: String {
var components: [String] = []
if let street = self.street {
components.append(street)
}
if let city = self.city {
components.append(city)
}
if let country = self.country {
components.append(country)
}
return components.joined(separator: ", ")
}
}
func reverseGeocodeLocation(latitude: Double, longitude: Double) -> Signal<ReverseGeocodedPlacemark?, NoError> {
return Signal { subscriber in
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude), completionHandler: { placemarks, _ in
if let placemarks = placemarks, let placemark = placemarks.first {
let result = ReverseGeocodedPlacemark(street: placemark.thoroughfare, city: placemark.locality, country: placemark.country)
subscriber.putNext(result)
subscriber.putCompletion()
} else {
subscriber.putNext(nil)
subscriber.putCompletion()
}
})
return ActionDisposable {
geocoder.cancelGeocode()
}
}
}
|
gpl-2.0
|
4a0fd44fa4f6c21247e3415f9d65baf3
| 32.766667 | 139 | 0.609082 | 5.303665 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/DatabaseTable.swift
|
1
|
9822
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Represents a data table composed of databaseColumns and databaseRows.
@author Ferran Vila Conesa
@since v2.0
@version 1.0
*/
public class DatabaseTable : APIBean {
/**
Number of databaseColumns.
*/
var columnCount : Int32?
/**
Definition of databaseColumns.
*/
var databaseColumns : [DatabaseColumn]?
/**
Rows of the table containing the data.
*/
var databaseRows : [DatabaseRow]?
/**
Name of the table.
*/
var name : String?
/**
Number of databaseRows.
*/
var rowCount : Int32?
/**
Default constructor
@since v2.0
*/
public override init() {
super.init()
}
/**
Constructor by default
@param name The name of the table
@since v2.0
*/
public init(name: String) {
super.init()
self.name = name
}
/**
Constructor using fields
@param name The name of the table
@param columnCount The number of databaseColumns
@param rowCount The number of databaseRows
@param databaseColumns The databaseColumns of the table
@param databaseRows The databaseRows of the table
@since v2.0
*/
public init(name: String, columnCount: Int32, rowCount: Int32, databaseColumns: [DatabaseColumn], databaseRows: [DatabaseRow]) {
super.init()
self.name = name
self.columnCount = columnCount
self.rowCount = rowCount
self.databaseColumns = databaseColumns
self.databaseRows = databaseRows
}
/**
Get the number of databaseColumns
@return The number of databaseColumns
@since v2.0
*/
public func getColumnCount() -> Int32? {
return self.columnCount
}
/**
Sets the number of databaseColumns
@param columnCount The number of databaseColumns
@since v2.0
*/
public func setColumnCount(columnCount: Int32) {
self.columnCount = columnCount
}
/**
Get the databaseColumns
@return The databaseColumns
@since v2.0
*/
public func getDatabaseColumns() -> [DatabaseColumn]? {
return self.databaseColumns
}
/**
Sets the databaseColumns of the table
@param databaseColumns The databaseColumns of the table
@since v2.0
*/
public func setDatabaseColumns(databaseColumns: [DatabaseColumn]) {
self.databaseColumns = databaseColumns
}
/**
Get the databaseRows of the table
@return The databaseRows of the table
@since v2.0
*/
public func getDatabaseRows() -> [DatabaseRow]? {
return self.databaseRows
}
/**
Sets the databaseRows of the table
@param databaseRows The databaseRows of the table
@since v2.0
*/
public func setDatabaseRows(databaseRows: [DatabaseRow]) {
self.databaseRows = databaseRows
}
/**
Returns the name of the table
@return The name of the table
@since v2.0
*/
public func getName() -> String? {
return self.name
}
/**
Sets the name of the table
@param name The name of the table
@since v2.0
*/
public func setName(name: String) {
self.name = name
}
/**
Get the number of databaseRows
@return The number of databaseRows
@since v2.0
*/
public func getRowCount() -> Int32? {
return self.rowCount
}
/**
Sets the number of databaseRows
@param rowCount The number of databaseRows
@since v2.0
*/
public func setRowCount(rowCount: Int32) {
self.rowCount = rowCount
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> DatabaseTable {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> DatabaseTable {
let resultObject : DatabaseTable = DatabaseTable()
if let value : AnyObject = dict.objectForKey("columnCount") {
if "\(value)" as NSString != "<null>" {
let numValue = value as! Int
resultObject.columnCount = Int32(numValue)
}
}
if let value : AnyObject = dict.objectForKey("databaseColumns") {
if "\(value)" as NSString != "<null>" {
var databaseColumns : [DatabaseColumn] = [DatabaseColumn]()
for (var i = 0;i < (value as! NSArray).count ; i++) {
databaseColumns.append(DatabaseColumn.Serializer.fromDictionary((value as! NSArray)[i] as! NSDictionary))
}
resultObject.databaseColumns = databaseColumns
}
}
if let value : AnyObject = dict.objectForKey("databaseRows") {
if "\(value)" as NSString != "<null>" {
var databaseRows : [DatabaseRow] = [DatabaseRow]()
for (var i = 0;i < (value as! NSArray).count ; i++) {
databaseRows.append(DatabaseRow.Serializer.fromDictionary((value as! NSArray)[i] as! NSDictionary))
}
resultObject.databaseRows = databaseRows
}
}
if let value : AnyObject = dict.objectForKey("name") {
if "\(value)" as NSString != "<null>" {
resultObject.name = (value as! String)
}
}
if let value : AnyObject = dict.objectForKey("rowCount") {
if "\(value)" as NSString != "<null>" {
let numValue = value as! Int
resultObject.rowCount = Int32(numValue)
}
}
return resultObject
}
public static func toJSON(object: DatabaseTable) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.columnCount != nil ? jsonString.appendString("\"columnCount\": \(object.columnCount!), ") : jsonString.appendString("\"columnCount\": null, ")
if (object.databaseColumns != nil) {
// Start array of objects.
jsonString.appendString("\"databaseColumns\": [")
for var i = 0; i < object.databaseColumns!.count; i++ {
jsonString.appendString(DatabaseColumn.Serializer.toJSON(object.databaseColumns![i]))
if (i < object.databaseColumns!.count-1) {
jsonString.appendString(", ");
}
}
// End array of objects.
jsonString.appendString("], ");
} else {
jsonString.appendString("\"databaseColumns\": null, ")
}
if (object.databaseRows != nil) {
// Start array of objects.
jsonString.appendString("\"databaseRows\": [")
for var i = 0; i < object.databaseRows!.count; i++ {
jsonString.appendString(DatabaseRow.Serializer.toJSON(object.databaseRows![i]))
if (i < object.databaseRows!.count-1) {
jsonString.appendString(", ");
}
}
// End array of objects.
jsonString.appendString("], ");
} else {
jsonString.appendString("\"databaseRows\": null, ")
}
object.name != nil ? jsonString.appendString("\"name\": \"\(JSONUtil.escapeString(object.name!))\", ") : jsonString.appendString("\"name\": null, ")
object.rowCount != nil ? jsonString.appendString("\"rowCount\": \(object.rowCount!)") : jsonString.appendString("\"rowCount\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
161163b366b19856abb16b78ae2b6a8f
| 30.273885 | 161 | 0.554379 | 5.05404 | false | false | false | false |
cuappdev/tcat-ios
|
TCAT/Views/BusIcon.swift
|
1
|
4765
|
//
// BusIcon.swift
// TCAT
//
// Created by Matthew Barker on 2/26/17.
// Copyright © 2017 cuappdev. All rights reserved.
//
import UIKit
enum BusIconType: String {
case blueBannerSmall, directionLarge, directionSmall, liveTracking, redBannerSmall
/// Return BusIcon's frame width
var width: CGFloat {
switch self {
case .blueBannerSmall, .directionSmall, .redBannerSmall:
return 48
case .directionLarge:
return 72
case .liveTracking:
return 72
}
}
/// Return BusIcon's frame height
var height: CGFloat {
switch self {
case .blueBannerSmall, .directionSmall, .redBannerSmall:
return 24
case .directionLarge:
return 36
case .liveTracking:
return 30
}
}
/// Return BusIcon's corner radius
var cornerRadius: CGFloat {
switch self {
case .directionLarge:
return 8
default:
return 4
}
}
var baseColor: UIColor {
switch self {
case .blueBannerSmall, .redBannerSmall:
return Colors.white
case .directionLarge, .directionSmall, .liveTracking:
return Colors.tcatBlue
}
}
var contentColor: UIColor {
switch self {
case .blueBannerSmall:
return Colors.tcatBlue
case .directionLarge, .directionSmall, .liveTracking:
return Colors.white
case .redBannerSmall:
return Colors.lateRed
}
}
}
class BusIcon: UIView {
private var type: BusIconType
private let baseView = UIView()
private let image = UIImageView(image: UIImage(named: "bus"))
private let label = UILabel()
private var liveIndicator: LiveIndicator?
override var intrinsicContentSize: CGSize {
return CGSize(width: type.width, height: type.height)
}
// MARK: - Init
init(type: BusIconType, number: Int) {
self.type = type
super.init(frame: .zero)
var fontSize: CGFloat
switch type {
case .blueBannerSmall, .directionSmall, .redBannerSmall: fontSize = 14
case .directionLarge: fontSize = 20
case .liveTracking: fontSize = 16
}
backgroundColor = .clear
isOpaque = false
baseView.backgroundColor = type.baseColor
baseView.layer.cornerRadius = type.cornerRadius
addSubview(baseView)
image.tintColor = type.contentColor
addSubview(image)
label.text = "\(number)"
label.font = .getFont(.semibold, size: fontSize)
label.textColor = type.contentColor
label.textAlignment = .center
addSubview(label)
if type == .liveTracking {
liveIndicator = LiveIndicator(size: .large, color: type.contentColor)
addSubview(liveIndicator!)
}
setupConstraints(for: type)
}
private func setupConstraints(for type: BusIconType) {
let imageLeadingOffset: CGFloat = type == .directionLarge ? 12 : 8
var constant: CGFloat
switch type {
case .blueBannerSmall, .directionSmall, .redBannerSmall: constant = 0.75
case .directionLarge: constant = 1
case .liveTracking: constant = 0.87
}
let imageSize = CGSize(width: image.frame.width * constant, height: image.frame.height * constant)
let labelLeadingOffset: CGFloat = type == .liveTracking
? 4
: (type.width - imageSize.width - imageLeadingOffset - label.intrinsicContentSize.width) / 2
let liveIndicatorLeadingOffset = 4
baseView.snp.makeConstraints { make in
make.edges.equalToSuperview()
make.size.equalTo(CGSize(width: type.width, height: type.height))
}
image.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(imageLeadingOffset)
make.centerY.equalToSuperview()
make.size.equalTo(imageSize)
}
label.snp.makeConstraints { make in
make.leading.equalTo(image.snp.trailing).offset(labelLeadingOffset)
make.centerY.equalToSuperview()
make.size.equalTo(label.intrinsicContentSize)
}
if let liveIndicator = liveIndicator {
liveIndicator.snp.makeConstraints { make in
make.leading.equalTo(label.snp.trailing).offset(liveIndicatorLeadingOffset)
make.centerY.equalToSuperview()
make.size.equalTo(liveIndicator.intrinsicContentSize)
}
}
}
required init?(coder aDecoder: NSCoder) {
type = .directionSmall
super.init(coder: aDecoder)
}
}
|
mit
|
e3e9410646a567378f2599e87ba3a3e4
| 27.526946 | 106 | 0.609992 | 4.693596 | false | false | false | false |
mchirico/SwiftCharts
|
Examples/Examples/BubbleExample.swift
|
2
|
10778
|
//
// ScatterExample.swift
// Examples
//
// Created by ischuetz on 16/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import CoreGraphics
import SwiftCharts
class BubbleExample: UIViewController {
private var chart: Chart?
private let colorBarHeight: CGFloat = 50
private let useViewsLayer = true
override func viewDidLoad() {
super.viewDidLoad()
let frame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height - colorBarHeight)
let colorBar = ColorBar(frame: CGRectMake(0, chartFrame.origin.y + chartFrame.size.height, self.view.frame.size.width, self.colorBarHeight), c1: UIColor.redColor(), c2: UIColor.greenColor())
self.view.addSubview(colorBar)
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
func toColor(percentage: Double) -> UIColor {
return colorBar.colorForPercentage(percentage).colorWithAlphaComponent(0.6)
}
let chartPoints: [ChartPointBubble] = [
(2, 2, 100, toColor(0)),
(2.1, 5, 250, toColor(0)),
(4, 4, 200, toColor(0.2)),
(2.3, 5, 150, toColor(0.7)),
(6, 7, 120, toColor(0.9)),
(8, 3, 50, toColor(1)),
(2, 4.5, 80, toColor(0.7)),
(2, 5.2, 50, toColor(0.4)),
(2, 4, 100, toColor(0.3)),
(2.7, 5.5, 200, toColor(0.5)),
(1.7, 2.8, 150, toColor(0.7)),
(4.4, 8, 120, toColor(0.9)),
(5, 6.3, 250, toColor(1)),
(6, 8, 100, toColor(0)),
(4, 8.5, 200, toColor(0.5)),
(8, 5, 200, toColor(0.6)),
(8.5, 10, 150, toColor(0.7)),
(9, 11, 120, toColor(0.6)),
(10, 6, 100, toColor(1)),
(11, 7, 100, toColor(0)),
(11, 4, 200, toColor(0.5)),
(11.5, 10, 150, toColor(0.7)),
(12, 7, 120, toColor(0.9)),
(12, 9, 250, toColor(0.8))
].map{
let d = ChartAxisValueDouble($0, labelSettings: labelSettings)
let e = ChartAxisValueDouble($1)
let f = Double($2)
let k: UIColor = $3
return ChartPointBubble(x: ChartAxisValueDouble($0, labelSettings: labelSettings), y: ChartAxisValueDouble($1), diameterScalar: Double($2), bgColor: $3)
}
let xValues = Array(stride(from: -2, through: 14, by: 2)).map {ChartAxisValueInt($0, labelSettings: labelSettings)}
let yValues = Array(stride(from: -2, through: 12, by: 2)).map {ChartAxisValueInt($0, labelSettings: labelSettings)}
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 0.5, animDelay: 0)
let bubbleLayer = self.bubblesLayer(xAxis: xAxis, yAxis: yAxis, chartInnerFrame: innerFrame, chartPoints: chartPoints)
let guidelinesLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: guidelinesLayerSettings)
let guidelinesHighlightLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.redColor(), linesWidth: 1, dotWidth: 4, dotSpacing: 4)
let guidelinesHighlightLayer = ChartGuideLinesForValuesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: guidelinesHighlightLayerSettings, axisValuesX: [ChartAxisValueDouble(0)], axisValuesY: [ChartAxisValueDouble(0)])
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
guidelinesHighlightLayer,
bubbleLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
// We can use a view based layer for easy animation (or interactivity), in which case we use the default chart points layer with a generator to create bubble views.
// On the other side, if we don't need animation or want a better performance, we use ChartPointsBubbleLayer, which instead of creating views, renders directly to the chart's context.
private func bubblesLayer(#xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, chartInnerFrame: CGRect, chartPoints: [ChartPointBubble]) -> ChartLayer {
let maxBubbleDiameter: Double = 30, minBubbleDiameter: Double = 2
if self.useViewsLayer == true {
let (minDiameterScalar: Double, maxDiameterScalar: Double) = chartPoints.reduce((min: 0, max: 0)) {tuple, chartPoint in
(min: min(tuple.min, chartPoint.diameterScalar), max: max(tuple.max, chartPoint.diameterScalar))
}
let diameterFactor = (maxBubbleDiameter - minBubbleDiameter) / (maxDiameterScalar - minDiameterScalar)
return ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: chartInnerFrame, chartPoints: chartPoints, viewGenerator: {(chartPointModel, layer, chart) -> UIView? in
let diameter = CGFloat(chartPointModel.chartPoint.diameterScalar * diameterFactor)
let rect = CGRectMake(chartPointModel.screenLoc.x - diameter / 2, chartPointModel.screenLoc.y - diameter / 2, diameter, diameter)
let circleView = ChartPointEllipseView(center: chartPointModel.screenLoc, diameter: diameter)
circleView.fillColor = chartPointModel.chartPoint.bgColor
circleView.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
circleView.borderWidth = 1
circleView.animDelay = Float(chartPointModel.index) * 0.2
circleView.animDuration = 1.2
circleView.animDamping = 0.4
circleView.animInitSpringVelocity = 0.5
return circleView
})
} else {
return ChartPointsBubbleLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: chartInnerFrame, chartPoints: chartPoints)
}
}
class ColorBar: UIView {
let dividers: [CGFloat]
let gradientImg: UIImage
lazy var imgData: UnsafePointer<UInt8> = {
let provider = CGImageGetDataProvider(self.gradientImg.CGImage)
let pixelData = CGDataProviderCopyData(provider)
return CFDataGetBytePtr(pixelData)
}()
init(frame: CGRect, c1: UIColor, c2: UIColor) {
var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRectMake(0, 0, frame.width, 30)
gradient.colors = [UIColor.blueColor().CGColor, UIColor.cyanColor().CGColor, UIColor.yellowColor().CGColor, UIColor.redColor().CGColor]
gradient.startPoint = CGPointMake(0, 0.5)
gradient.endPoint = CGPointMake(1.0, 0.5)
let imgHeight = 1
let imgWidth = Int(gradient.bounds.size.width)
let bitmapBytesPerRow = imgWidth * 4
let bitmapByteCount = bitmapBytesPerRow * imgHeight
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate (nil,
imgWidth,
imgHeight,
8,
bitmapBytesPerRow,
colorSpace,
bitmapInfo)
UIGraphicsBeginImageContext(gradient.bounds.size)
gradient.renderInContext(context)
let gradientImg = UIImage(CGImage: CGBitmapContextCreateImage(context))!
UIGraphicsEndImageContext()
self.gradientImg = gradientImg
let segmentSize = gradient.frame.size.width / 6
self.dividers = Array(stride(from: segmentSize, through: gradient.frame.size.width, by: segmentSize))
super.init(frame: frame)
self.layer.insertSublayer(gradient, atIndex: 0)
let numberFormatter = NSNumberFormatter()
numberFormatter.maximumFractionDigits = 2
for x in stride(from: segmentSize, through: gradient.frame.size.width - 1, by: segmentSize) {
let dividerW: CGFloat = 1
let divider = UIView(frame: CGRectMake(x - dividerW / 2, 25, dividerW, 5))
divider.backgroundColor = UIColor.blackColor()
self.addSubview(divider)
let text = "\(numberFormatter.stringFromNumber(x / gradient.frame.size.width)!)"
let labelWidth = ChartUtils.textSize(text, font: ExamplesDefaults.labelFont).width
let label = UILabel()
label.center = CGPointMake(x - labelWidth / 2, 30)
label.font = ExamplesDefaults.labelFont
label.text = text
label.sizeToFit()
self.addSubview(label)
}
}
func colorForPercentage(percentage: Double) -> UIColor {
let data = self.imgData
let xNotRounded = self.gradientImg.size.width * CGFloat(percentage)
let x = 4 * (floor(abs(xNotRounded / 4)))
let pixelIndex = Int(x * 4)
let color = UIColor(
red: CGFloat(data[pixelIndex + 0]) / 255.0,
green: CGFloat(data[pixelIndex + 1]) / 255.0,
blue: CGFloat(data[pixelIndex + 2]) / 255.0,
alpha: CGFloat(data[pixelIndex + 3]) / 255.0
)
return color
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
|
apache-2.0
|
597b13470812a04732ef5e637698a125
| 43.908333 | 250 | 0.600668 | 4.881341 | false | false | false | false |
aabrahamyan/AAPhotoLibrary
|
AAPhotoLibrary/Extension/AAPhotoLibrary+Reader.swift
|
1
|
6576
|
//
// AAPhotoLibrary+Reader.swift
// AAPhotoLibrary
//
// Created by Armen Abrahamyan on 5/7/16.
// Copyright © 2016 Armen Abrahamyan. All rights reserved.
//
import Foundation
import Photos
/**
** This extension is responsible for reading photo library content
**/
extension PHPhotoLibrary {
// MARK: Public methods
/**
* Fetch All Collections
*/
@objc
public final class func fetchCollectionsByType(_ type:PHAssetCollectionType, includeHiddenAssets: Bool, sortByName: Bool, completion: @escaping (_ fetchResults: PHFetchResult<PHAssetCollection>?, _ error: NSError?) -> Void) {
checkAuthorizationStatus { (authorizationStatus, error) in
guard authorizationStatus == .authorized else {
completion(nil, error)
print("Impossible to access the Photo Library, please make sure that you don't expilicitly deneid access or there is no specific parenthal control enabled !")
return
}
let options = PHFetchOptions()
options.includeHiddenAssets = includeHiddenAssets
if sortByName {
options.sortDescriptors = [NSSortDescriptor(key: "localizedTitle", ascending: true)]
}
let collection = PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: options)
completion(collection, nil)
}
}
/**
* Fetches all images from collection
*/
@objc
public final class func fetchAllItemsFromCollection(_ collectionType: PHAssetCollectionType, collectionId: String, sortByDate: Bool, completion: @escaping (_ fetchResult: PHFetchResult<PHAsset>?, _ error: NSError?) -> Void) {
checkAuthorizationStatus { (authorizationStatus, error) in
let collection = findCollectionById(collectionId, collectionType: collectionType)
if collection != nil {
let options = PHFetchOptions()
if sortByDate {
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
}
let fetchResult = PHAsset.fetchAssets(in: collection!, options: options)
completion(fetchResult, error)
}
}
}
/**
* Get an image from asset identifier
//PHImageManagerMaximumSize
*/
@objc
public class func imageFromAssetIdentifier(_ asstItemIdentifeir: String, size: CGSize, completion: @escaping (_ image: UIImage?, _ info:[AnyHashable: Any]?) -> Void) {
checkAuthorizationStatus { (authorizationStatus, error) in
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "localIdentifier=%@", asstItemIdentifeir)
let fetchResult = PHAsset.fetchAssets(with: options)
if let asset = fetchResult.firstObject {
imageFromAsset(asset, size: size, completion: completion)
}
}
}
/**
* TODO: MOVE REQUEST OPTIONS AS ARGUMENTS
* Retrieves an original image from an asset object
*/
@objc
public class func imageFromAsset(_ asset: PHAsset, size: CGSize, completion: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) {
checkAuthorizationStatus { (authorizationStatus, error) in
if asset.mediaType == .image {
let requestOptions = PHImageRequestOptions()
requestOptions.resizeMode = .exact
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isSynchronous = false
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: requestOptions, resultHandler: { (image, info) in
completion(image, info)
})
} else {
completion(nil, ["error": "Asset is not of an image type."])
}
}
}
/**
* Retrieves a video from an Asset object
*/
@objc
public class func videoFromAsset(_ asset: PHAsset, completion: @escaping (_ avplayerItem: AVPlayerItem?, _ info: [AnyHashable: Any]?) -> Void) {
checkAuthorizationStatus { (authorizationStatus, error) in
if asset.mediaType == .video {
let requestOptions = PHVideoRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
PHImageManager.default().requestPlayerItem(forVideo: asset, options: requestOptions, resultHandler: { (avplayerItem, info) in
completion(avplayerItem, info)
})
} else {
completion(nil, ["error": "Asset is not of an image type."])
}
}
}
/**
* Check Authorization status
*/
@objc
public final class func checkAuthorizationStatus(_ completion: @escaping (_ authorizationStatus: PHAuthorizationStatus, _ error: NSError?) -> Void) {
let status = PHPhotoLibrary.authorizationStatus()
switch (status) {
case .notDetermined:
PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) in
completion(status, AAPLErrorHandler.aaForceAccessDenied.rawValue.error)
})
break
case .authorized:
completion(status, nil)
break
case .restricted:
print("Access is restricted: Maybe parental controls are turned on ?")
completion(status, AAPLErrorHandler.aaRestricted.rawValue.error)
break
case .denied:
print("User denied an access to library")
completion(status, AAPLErrorHandler.aaDenied.rawValue.error)
break
}
}
// MARK: Private Helpers
/**
* Search Collection By Local Stored Identifeir
*/
@objc
fileprivate final class func findCollectionById (_ folderIdentifier: String, collectionType: PHAssetCollectionType) -> PHAssetCollection? {
var collection: PHAssetCollection?
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "localIdentifier=%@", folderIdentifier)
collection = PHAssetCollection.fetchAssetCollections(with: collectionType, subtype: .any, options: fetchOptions).firstObject
return collection
}
}
|
apache-2.0
|
b7ea21e54357904b74e13600e2e50579
| 37.450292 | 229 | 0.609278 | 5.687716 | false | false | false | false |
ruter/Strap-in-Swift
|
Pachinko/Pachinko/GameViewController.swift
|
1
|
1397
|
//
// GameViewController.swift
// Pachinko
//
// Created by Ruter on 16/4/20.
// Copyright (c) 2016年 Ruter. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
apache-2.0
|
025c6e8b9807947edffacb945a72fbac
| 25.320755 | 94 | 0.600717 | 5.470588 | false | false | false | false |
ccadena/swift_example_app
|
iosSearchApp/Objects/Item.swift
|
1
|
2023
|
//
// Item.swift
// iosSearchApp
//
// Created by Camilo Cadena on 9/28/15.
// Copyright © 2015 Camilo Cadena. All rights reserved.
//
import UIKit
struct itemKey {
static let titleTextKey = "titleTextKey"
static let iconPhotoKey = "iconPhoto"
static let descriptionTextKey = "descriptionText"
static let indexKey = "index"
}
class Item: NSObject, NSCoding {
var titleText: String
var iconPhoto: UIImage?
var descriptionText: String
var index: Int
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("items")
init?(titleText: String, iconPhoto: UIImage, descriptionText: String, index: Int) {
self.titleText = titleText
self.descriptionText = descriptionText
self.iconPhoto = iconPhoto
self.index = index
super.init()
// Fail if title or description are missing
if (titleText.isEmpty || descriptionText.isEmpty) {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(titleText, forKey: itemKey.titleTextKey)
aCoder.encodeObject(iconPhoto, forKey: itemKey.iconPhotoKey)
aCoder.encodeObject(descriptionText, forKey: itemKey.descriptionTextKey)
aCoder.encodeObject(index, forKey:itemKey.indexKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let titleText = aDecoder.decodeObjectForKey(itemKey.titleTextKey) as! String
let iconPhoto = aDecoder.decodeObjectForKey(itemKey.iconPhotoKey) as? UIImage
let descriptionText = aDecoder.decodeObjectForKey(itemKey.descriptionTextKey) as! String
let index = aDecoder.decodeObjectForKey(itemKey.indexKey) as! Int
self.init(titleText: titleText, iconPhoto: iconPhoto!, descriptionText: descriptionText, index: index)
}
}
|
gpl-3.0
|
fab8ad01d8ad980dc6b06fa40abdaa79
| 33.271186 | 123 | 0.693373 | 4.724299 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/Stack/20_ValidParentheses.swift
|
1
|
1258
|
//
// 20_ValidParentheses.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-24.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:20 Valid Parentheses
URL: https://leetcode.com/problems/valid-parentheses/
Space: O(N)
Time: O(N)
*/
class ValidParentheses_Solution {
func isValid(_ s: String) -> Bool {
let characters = [Character](s.characters)
let validInput = "([{"
var characterStack = [Character]()
for i in characters {
if validInput.characters.contains(i) {
characterStack.push(i)
continue
}
switch i {
case ")":
if let firstPop = characterStack.pop() {
if firstPop != "(" {
return false
}
} else {
return false
}
case "]":
if let firstPop = characterStack.pop() {
if firstPop != "[" {
return false
}
} else {
return false
}
case "}":
if let firstPop = characterStack.pop() {
if firstPop != "{" {
return false
}
} else {
return false
}
default:
return false
}
}
return characterStack.isEmpty
}
}
|
mit
|
c402336d6725fcef49d07f80518f6ea4
| 20.305085 | 54 | 0.522673 | 4.081169 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications
|
lab-2/lab-2/lab-2/ThirdViewController.swift
|
1
|
3226
|
/*
* @author Tyler Brockett
* @project CSE 394 Lab 2
* @version February 2, 2016
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tyler Brockett
*
* 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 ThirdViewController: UIViewController {
var firstMessage:String = ""
var secondMessage:String = ""
var default_height: CGFloat = 0.0
@IBOutlet weak var labelFirstMessage: UILabel!
@IBOutlet weak var labelSecondMessage: UILabel!
@IBOutlet weak var finalMessage: UILabel!
@IBOutlet weak var thirdMessage: UITextField!
@IBAction func thirdMessageEdited(sender: UITextField) {
updateFinalMessage()
}
override func viewDidLoad() {
super.viewDidLoad()
self.default_height = self.view.frame.origin.y
labelFirstMessage.text = firstMessage
labelSecondMessage.text = secondMessage
updateFinalMessage()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func updateFinalMessage() {
var third: String = ""
if let t:String = thirdMessage.text! {
third = t
}
finalMessage.text = firstMessage + "\n" + secondMessage + "\n" + third
}
func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y = self.default_height - 100
}
func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = self.default_height
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent:event)
view.endEditing(true)
self.thirdMessage.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.thirdMessage.resignFirstResponder()
return true
}
}
|
mit
|
44e1141fa19d0f482efb70b66a3d9586
| 34.844444 | 153 | 0.699008 | 4.78635 | false | false | false | false |
auth0/Auth0.swift
|
Auth0/String+URLSafe.swift
|
1
|
650
|
import Foundation
/// Adds a utility method for decoding base64url-encoded data, like ID tokens.
public extension String {
/// Decodes base64url-encoded data.
func a0_decodeBase64URLSafe() -> Data? {
let lengthMultiple = 4
let paddingLength = lengthMultiple - count % lengthMultiple
let padding = (paddingLength < lengthMultiple) ? String(repeating: "=", count: paddingLength) : ""
let base64EncodedString = self
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
+ padding
return Data(base64Encoded: base64EncodedString)
}
}
|
mit
|
862b7ba2cff1bb3094dbc42dc960015f
| 35.111111 | 106 | 0.643077 | 4.676259 | false | false | false | false |
grpc/grpc-swift
|
Sources/GRPC/AsyncAwaitSupport/GRPCAsyncServerCallContext.swift
|
1
|
4459
|
/*
* Copyright 2021, gRPC 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.
*/
#if compiler(>=5.6)
import Logging
import NIOConcurrencyHelpers
import NIOHPACK
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public struct GRPCAsyncServerCallContext: Sendable {
@usableFromInline
let contextProvider: AsyncServerCallContextProvider
/// Details of the request, including request headers and a logger.
public var request: Request
/// A response context which may be used to set response headers and trailers.
public var response: Response {
Response(contextProvider: self.contextProvider)
}
/// Access the ``UserInfo`` dictionary which is shared with the interceptor contexts for this RPC.
///
/// - Important: While ``UserInfo`` has value-semantics, this function accesses a reference
/// wrapped ``UserInfo``. The contexts passed to interceptors provide the same reference. As such
/// this may be used as a mechanism to pass information between interceptors and service
/// providers.
public func withUserInfo<Result: Sendable>(
_ body: @Sendable @escaping (UserInfo) throws -> Result
) async throws -> Result {
return try await self.contextProvider.withUserInfo(body)
}
/// Modify the ``UserInfo`` dictionary which is shared with the interceptor contexts for this RPC.
///
/// - Important: While ``UserInfo`` has value-semantics, this function accesses a reference
/// wrapped ``UserInfo``. The contexts passed to interceptors provide the same reference. As such
/// this may be used as a mechanism to pass information between interceptors and service
/// providers.
public func withMutableUserInfo<Result: Sendable>(
_ modify: @Sendable @escaping (inout UserInfo) -> Result
) async throws -> Result {
return try await self.contextProvider.withMutableUserInfo(modify)
}
@inlinable
internal init(
headers: HPACKHeaders,
logger: Logger,
contextProvider: AsyncServerCallContextProvider
) {
self.request = Request(headers: headers, logger: logger)
self.contextProvider = contextProvider
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension GRPCAsyncServerCallContext {
public struct Request: Sendable {
/// The request headers received from the client at the start of the RPC.
public var headers: HPACKHeaders
/// A logger.
public var logger: Logger
@usableFromInline
init(headers: HPACKHeaders, logger: Logger) {
self.headers = headers
self.logger = logger
}
}
public struct Response: Sendable {
private let contextProvider: AsyncServerCallContextProvider
/// Set the metadata to return at the start of the RPC.
///
/// - Important: If this is required it should be updated _before_ the first response is sent
/// via the response stream writer. Updates must not be made after the first response has
/// been sent.
public func setHeaders(_ headers: HPACKHeaders) async throws {
try await self.contextProvider.setResponseHeaders(headers)
}
/// Set the metadata to return at the end of the RPC.
///
/// If this is required it must be updated before returning from the handler.
public func setTrailers(_ trailers: HPACKHeaders) async throws {
try await self.contextProvider.setResponseTrailers(trailers)
}
/// Whether compression should be enabled for responses, defaulting to `true`. Note that for
/// this value to take effect compression must have been enabled on the server and a compression
/// algorithm must have been negotiated with the client.
public func compressResponses(_ compress: Bool) async throws {
try await self.contextProvider.setResponseCompression(compress)
}
@usableFromInline
internal init(contextProvider: AsyncServerCallContextProvider) {
self.contextProvider = contextProvider
}
}
}
#endif
|
apache-2.0
|
feb41f64df9ff424a4ae1d32fb660097
| 36.470588 | 101 | 0.725275 | 4.708553 | false | false | false | false |
matthewpalmer/Locksmith
|
Source/LocksmithSecurityClass.swift
|
13
|
1230
|
import Foundation
// With thanks to http://iosdeveloperzone.com/2014/10/22/taming-foundation-constants-into-swift-enums/
// MARK: Security Class
public enum LocksmithSecurityClass: RawRepresentable {
case genericPassword, internetPassword, certificate, key, identity
public init?(rawValue: String) {
switch rawValue {
case String(kSecClassGenericPassword):
self = .genericPassword
case String(kSecClassInternetPassword):
self = .internetPassword
case String(kSecClassCertificate):
self = .certificate
case String(kSecClassKey):
self = .key
case String(kSecClassIdentity):
self = .identity
default:
self = .genericPassword
}
}
public var rawValue: String {
switch self {
case .genericPassword:
return String(kSecClassGenericPassword)
case .internetPassword:
return String(kSecClassInternetPassword)
case .certificate:
return String(kSecClassCertificate)
case .key:
return String(kSecClassKey)
case .identity:
return String(kSecClassIdentity)
}
}
}
|
mit
|
9652bd869c694de22e764a142f7cbe00
| 30.538462 | 102 | 0.625203 | 5.491071 | false | false | false | false |
Athlee/ATHKit
|
Examples/ATHImagePickerController/Storyboard/TestPicker/Pods/Material/Sources/iOS/PageTabBarController.swift
|
1
|
12425
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
/// A memory reference to the PageTabBarItem instance for UIViewController extensions.
private var PageTabBarItemKey: UInt8 = 0
open class PageTabBarItem: FlatButton {
open override func prepare() {
super.prepare()
pulseAnimation = .none
}
}
open class PageTabBar: TabBar {
open override func prepare() {
super.prepare()
isLineAnimated = false
lineAlignment = .top
}
}
@objc(PageTabBarAlignment)
public enum PageTabBarAlignment: Int {
case top
case bottom
}
/// Grid extension for UIView.
extension UIViewController {
/// Grid reference.
public private(set) var pageTabBarItem: PageTabBarItem {
get {
return AssociatedObject(base: self, key: &PageTabBarItemKey) {
return PageTabBarItem()
}
}
set(value) {
AssociateObject(base: self, key: &PageTabBarItemKey, value: value)
}
}
}
extension UIViewController {
/**
A convenience property that provides access to the PageTabBarController.
This is the recommended method of accessing the PageTabBarController
through child UIViewControllers.
*/
public var pageTabBarController: PageTabBarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is PageTabBarController {
return viewController as? PageTabBarController
}
viewController = viewController?.parent
}
return nil
}
}
@objc(PageTabBarControllerDelegate)
public protocol PageTabBarControllerDelegate {
/**
A delegation method that is executed when a UIViewController did transition to.
- Parameter pageTabBarController: A PageTabBarController.
- Parameter willTransitionTo viewController: A UIViewController.
*/
@objc
optional func pageTabBarController(pageTabBarController: PageTabBarController, didTransitionTo viewController: UIViewController)
}
@objc(PageTabBarController)
open class PageTabBarController: RootController {
/// Reference to the PageTabBar.
@IBInspectable
open let pageTabBar = PageTabBar()
/// A boolean that indicates whether bounce is enabled.
open var isBounceEnabled: Bool {
didSet {
scrollView?.bounces = isBounceEnabled
}
}
/// Indicates that the tab has been pressed and animating.
open internal(set) var isTabSelectedAnimation = false
/// The currently selected UIViewController.
open internal(set) var selectedIndex = 0
/// PageTabBar alignment setting.
open var pageTabBarAlignment = PageTabBarAlignment.bottom
/// Delegation handler.
open weak var delegate: PageTabBarControllerDelegate?
/// A reference to the instance when it is a UIPageViewController.
open var pageViewController: UIPageViewController? {
return rootViewController as? UIPageViewController
}
/// A reference to the scrollView.
open var scrollView: UIScrollView? {
guard let v = pageViewController else {
return nil
}
for view in v.view.subviews {
if let v = view as? UIScrollView {
return v
}
}
return nil
}
/// A reference to the UIViewControllers.
open var viewControllers = [UIViewController]()
public required init?(coder aDecoder: NSCoder) {
isBounceEnabled = true
super.init(coder: aDecoder)
prepare()
}
public override init(rootViewController: UIViewController) {
isBounceEnabled = true
super.init(rootViewController: UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil))
viewControllers.append(rootViewController)
setViewControllers(viewControllers, direction: .forward, animated: true)
prepare()
}
public init(viewControllers: [UIViewController], selectedIndex: Int = 0) {
isBounceEnabled = true
super.init(rootViewController: UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil))
self.selectedIndex = selectedIndex
self.viewControllers.append(contentsOf: viewControllers)
setViewControllers([self.viewControllers[selectedIndex]], direction: .forward, animated: true)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
let p = pageTabBar.intrinsicContentSize.height + pageTabBar.layoutEdgeInsets.top + pageTabBar.layoutEdgeInsets.bottom
let y = view.height - p
pageTabBar.height = p
pageTabBar.width = view.width + pageTabBar.layoutEdgeInsets.left + pageTabBar.layoutEdgeInsets.right
rootViewController.view.height = y
switch pageTabBarAlignment {
case .top:
pageTabBar.y = 0
rootViewController.view.y = p
case .bottom:
pageTabBar.y = y
rootViewController.view.y = 0
}
}
/**
Sets the view controllers.
- Parameter _ viewController: An Array of UIViewControllers.
- Parameter direction: A UIPageViewControllerNavigationDirection enum value.
- Parameter animated: A boolean indicating to include animation.
- Parameter completion: An optional completion block.
*/
open func setViewControllers(_ viewControllers: [UIViewController], direction: UIPageViewControllerNavigationDirection, animated: Bool, completion: ((Bool) -> Void)? = nil) {
pageViewController?.setViewControllers(viewControllers, direction: direction, animated: animated, completion: completion)
prepare()
}
/**
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()
preparePageTabBar()
preparePageTabBarItems()
}
open override func prepareRootViewController() {
super.prepareRootViewController()
guard let v = pageViewController else {
return
}
v.delegate = self
v.dataSource = self
v.isDoubleSided = false
scrollView?.delegate = self
}
/// Prepares the pageTabBarItems.
open func preparePageTabBarItems() {
pageTabBar.buttons.removeAll()
for x in viewControllers {
let button = x.pageTabBarItem as UIButton
pageTabBar.buttons.append(button)
button.removeTarget(self, action: #selector(pageTabBar.handleButton(button:)), for: .touchUpInside)
button.removeTarget(self, action: #selector(handlePageTabBarButton(button:)), for: .touchUpInside)
button.addTarget(self, action: #selector(handlePageTabBarButton(button:)), for: .touchUpInside)
}
}
/**
Handles the pageTabBarButton.
- Parameter button: A UIButton.
*/
@objc
internal func handlePageTabBarButton(button: UIButton) {
guard let index = pageTabBar.buttons.index(of: button) else {
return
}
guard index != selectedIndex else {
return
}
let direction: UIPageViewControllerNavigationDirection = index < selectedIndex ? .reverse : .forward
isTabSelectedAnimation = true
selectedIndex = index
pageTabBar.select(at: selectedIndex)
setViewControllers([viewControllers[index]], direction: direction, animated: true) { [weak self] _ in
guard let s = self else {
return
}
s.isTabSelectedAnimation = false
s.delegate?.pageTabBarController?(pageTabBarController: s, didTransitionTo: s.viewControllers[s.selectedIndex])
}
}
/// Prepares the pageTabBar.
private func preparePageTabBar() {
pageTabBar.zPosition = 1000
pageTabBar.dividerColor = Color.grey.lighten3
view.addSubview(pageTabBar)
pageTabBar.select(at: selectedIndex)
}
}
extension PageTabBarController: UIPageViewControllerDelegate {
open func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
print("HERE, \(previousViewControllers)")
guard let v = pageViewController.viewControllers?.first else {
return
}
guard let index = viewControllers.index(of: v) else {
return
}
print("INDEX=\(index)")
selectedIndex = index
pageTabBar.select(at: selectedIndex)
if finished && completed {
delegate?.pageTabBarController?(pageTabBarController: self, didTransitionTo: v)
}
}
}
extension PageTabBarController: UIPageViewControllerDataSource {
open func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let current = viewControllers.index(of: viewController) else {
return nil
}
let previous = current - 1
guard previous >= 0 else {
return nil
}
return viewControllers[previous]
}
open func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let current = viewControllers.index(of: viewController) else {
return nil
}
let next = current + 1
guard viewControllers.count > next else {
return nil
}
return viewControllers[next]
}
}
extension PageTabBarController: UIScrollViewDelegate {
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard !pageTabBar.isAnimating else {
return
}
guard !isTabSelectedAnimation else {
return
}
guard let selected = pageTabBar.selected else {
return
}
guard 0 < view.width else {
return
}
let x = (scrollView.contentOffset.x - view.width) / scrollView.contentSize.width * view.width
pageTabBar.line.center.x = selected.center.x + x
}
}
|
mit
|
b140c7a88bb090b7913a0512fbc3cc4c
| 33.706704 | 195 | 0.660604 | 5.461538 | false | false | false | false |
yonat/MultiToggleButton
|
Example/MultiToggleButtonDemo/ToggleButtonDemo.swift
|
1
|
1687
|
//
// AppDelegate.swift
// ToggleButtonDemo
//
// Created by Yonat Sharon on 02.03.2015.
// Copyright (c) 2015 Yonat Sharon. All rights reserved.
//
import MiniLayout
import MultiToggleButton
import UIKit
class ToggleButtonViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let toggleButton = MultiToggleButton(
images: [
UIImage(named: "camera-flash"),
UIImage(named: "facebook"),
UIImage(named: "clock"),
UIImage(named: "test_tube"),
],
states: ["Toggle", "State", "Alter", "Color"],
colors: [nil, nil, .gray, .red],
backgroundColors: [nil, nil, .yellow, UIColor.lightGray.withAlphaComponent(0.25)]
) { button in
print("Performing action for state: \(button.currentStateIndex)")
}
// make background coloring appear nicer
toggleButton.contentEdgeInsets = UIEdgeInsets(top: 2, left: 8, bottom: 2, right: 8)
toggleButton.layer.cornerRadius = 8
view.addConstrainedSubview(toggleButton, constrain: .centerX, .centerY)
}
}
@UIApplicationMain
class ToggleButtonDemo: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.rootViewController = ToggleButtonViewController()
window.makeKeyAndVisible()
self.window = window
return true
}
}
|
mit
|
3c998b96a696c211cff0138ac100dc5d
| 32.74 | 145 | 0.64671 | 4.806268 | false | false | false | false |
hughbe/swift
|
test/decl/protocol/req/recursion.swift
|
6
|
3467
|
// RUN: %target-typecheck-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/19840527
class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}}
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}}
}
// FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic
// should also become "associated type 'Foo' references itself"
protocol CircularAssocTypeDefault {
associatedtype Z = Z // expected-error{{associated type 'Z' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}}
associatedtype Z2 = Z3
// expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}}
associatedtype Z3 = Z2
// expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}}
associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}}
associatedtype Z5 = Self.Z6
// expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}}
associatedtype Z6 = Self.Z5
// expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}}
}
struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { }
// expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P> where A.T == S<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'S' references itself}}
func f(a: A.T) {
g(a: id(t: a))
// expected-error@-1 {{cannot convert value of type 'A.T' to expected argument type 'S<_>'}}
_ = A.T.self
}
func g(a: S<A>) {
f(a: id(t: a))
// expected-note@-1 {{expected an argument list of type '(a: A.T)'}}
// expected-error@-2 {{cannot invoke 'f' with an argument list of type '(a: S<A>)'}}
_ = S<A>.self
}
func id<T>(t: T) -> T {
return t
}
}
protocol I {
init()
}
protocol PI {
associatedtype T : I
}
struct SI<A: PI> : I where A : I, A.T == SI<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'SI' references itself}}
func ggg<T : I>(t: T.Type) -> T {
return T()
}
func foo() {
_ = A()
_ = A.T()
_ = SI<A>()
_ = ggg(t: A.self)
_ = ggg(t: A.T.self)
_ = self.ggg(t: A.self)
_ = self.ggg(t: A.T.self)
}
}
// Used to hit infinite recursion
struct S4<A: PI> : I where A : I {
}
struct S5<A: PI> : I where A : I, A.T == S4<A> {
// expected-warning@-1{{redundant conformance constraint 'A': 'I'}}
// expected-warning@-2{{redundant conformance constraint 'A': 'PI'}}
// expected-note@-3{{conformance constraint 'A': 'PI' inferred from type here}}
// expected-note@-4{{conformance constraint 'A': 'I' inferred from type here}}
}
// Used to hit ArchetypeBuilder assertions
struct SU<A: P> where A.T == SU {
}
struct SIU<A: PI> : I where A : I, A.T == SIU {
}
|
apache-2.0
|
1d40be534033805cd67e4bde2e9ed229
| 29.955357 | 135 | 0.646957 | 3.228119 | false | false | false | false |
milseman/swift
|
test/SILGen/borrow.swift
|
9
|
1370
|
// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
import Swift
final class D {}
// Make sure that we insert the borrow for a ref_element_addr lvalue in the
// proper place.
final class C {
var d: D = D()
}
func useD(_ d: D) {}
// CHECK-LABEL: sil hidden @_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}} : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[BOX:%.*]] = alloc_box ${ var C }, var, name "c"
// CHECK: [[PB_BOX:%.*]] = project_box [[BOX]]
// CHECK: [[FUNC:%.*]] = function_ref @_T06borrow4useD{{.*}} : $@convention(thin) (@owned D) -> ()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB_BOX]] : $*C
// CHECK: [[CLASS:%.*]] = load [copy] [[ACCESS]]
// CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[CLASS]]
// CHECK: [[OFFSET:%.*]] = ref_element_addr [[BORROWED_CLASS]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[OFFSET]] : $*D
// CHECK: [[LOADED_VALUE:%.*]] = load [copy] [[ACCESS]]
// CHECK: end_borrow [[BORROWED_CLASS]] from [[CLASS]]
// CHECK: apply [[FUNC]]([[LOADED_VALUE]])
// CHECK: destroy_value [[CLASS]]
// CHECK: destroy_value [[BOX]]
// CHECK: } // end sil function '_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}}'
func lvalueBorrowShouldBeAtEndOfFormalAccessScope() {
var c = C()
useD(c.d)
}
|
apache-2.0
|
2212eb80e9e94e25a28800f6fc1c43cb
| 39.294118 | 122 | 0.607299 | 3.215962 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingData/NetworkClients/TransactionClientAPI.swift
|
1
|
1289
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import FeatureCardIssuingDomain
import Foundation
protocol TransactionClientAPI {
func fetchTransactions(
_ params: TransactionsParams?
) -> AnyPublisher<[Card.Transaction], NabuNetworkError>
}
extension TransactionClientAPI {
func fetchTransactions() -> AnyPublisher<[Card.Transaction], NabuNetworkError> {
fetchTransactions(nil)
}
}
struct TransactionsParams {
let cardId: String?
let types: [Card.Transaction.TransactionType]?
let from: Date?
let to: Date?
let toId: String?
let fromId: String?
let limit: Int?
enum CodingKeys: String, CodingKey {
case cardId
case types
case toId
case fromId
case limit
case from
case to
}
init(
cardId: String? = nil,
types: [Card.Transaction.TransactionType]? = nil,
from: Date? = nil,
to: Date? = nil,
toId: String? = nil,
fromId: String? = nil,
limit: Int? = nil
) {
self.cardId = cardId
self.types = types
self.from = from
self.to = to
self.toId = toId
self.fromId = fromId
self.limit = limit
}
}
|
lgpl-3.0
|
7bcda7c926298532affa7e829996b7e3
| 20.830508 | 84 | 0.606366 | 4.366102 | false | false | false | false |
CrazyZhangSanFeng/BanTang
|
BanTang/BanTang/Classes/Home/Controller/搜索界面/BTSearchDanpinViewController.swift
|
1
|
5596
|
//
// BTSearchDanpinViewController.swift
// BanTang
//
// Created by 张灿 on 16/6/20.
// Copyright © 2016年 张灿. All rights reserved.
// 搜索界面里的 单品控制器
import UIKit
import SnapKit
private let cellID = "danpinSearchTableCell"
private let collectionCellID = "collectionCellID"
class BTSearchDanpinViewController: UIViewController {
//左侧模型数组
var danPinModels: [BTSearchDanpinModel] = [BTSearchDanpinModel]()
//左侧cell选中时 对应的 右侧模型数组
var selectModels: [subclassModel] = [subclassModel]()
//左侧tableview
var danPinTableView: UITableView?
//右侧collectionView
var collectionView: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
buildtableView()
buildCollectionView()
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: - 创建左侧tableview
extension BTSearchDanpinViewController: UITableViewDelegate, UITableViewDataSource {
func buildtableView() {
//创建tableview
danPinTableView = UITableView(frame: CGRectZero, style: .Plain)
danPinTableView!.dataSource = self
danPinTableView!.delegate = self
//取消系统分割线
danPinTableView!.separatorStyle = .None
danPinTableView!.backgroundColor = UIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1.0)
danPinTableView!.rowHeight = 50
danPinTableView!.showsVerticalScrollIndicator = false
//注册cell
danPinTableView!.registerNib(UINib.init(nibName: "BTSearchCategoryTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
view.addSubview(danPinTableView!)
danPinTableView!.snp_makeConstraints { (make) in
make.top.leading.bottom.equalTo(self.view)
make.width.equalTo(BTscreenW / 4)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return danPinModels.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! BTSearchCategoryTableViewCell
cell.categoryModel = danPinModels[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//把当前选中cell的模型里面的右侧模型数组拿出来,保存起来
selectModels = danPinModels[indexPath.row].subclass
//刷新右侧
collectionView?.reloadData()
}
}
//MARK: - 创建右侧collectionview
extension BTSearchDanpinViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func buildCollectionView() {
let margin: CGFloat = 0
//布局方式
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = margin
layout.minimumInteritemSpacing = margin
layout.itemSize = CGSize(width: BTscreenW / 4 * 3 / 3, height: 100)
layout.scrollDirection = .Vertical
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView!.backgroundColor = UIColor.whiteColor()
collectionView!.dataSource = self
collectionView!.delegate = self
//注册cell
collectionView!.registerNib(UINib.init(nibName: "BTSearchCategoryRightCell", bundle: nil), forCellWithReuseIdentifier: collectionCellID)
view.addSubview(collectionView!)
collectionView!.snp_makeConstraints { (make) in
make.top.trailing.bottom.equalTo(self.view)
make.leading.equalTo((self.danPinTableView?.snp_trailing)!)
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return selectModels.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellID, forIndexPath: indexPath) as! BTSearchCategoryRightCell
cell.subclass = selectModels[indexPath.row]
return cell
}
}
//MARK: - 数据请求
extension BTSearchDanpinViewController {
func loadData() {
BTHomePageDataTool.getSearchDanpinData { (danpinModels, error) in
if error != nil {
return
}
self.danPinModels = danpinModels!
//默认加载右侧第一个
self.selectModels = self.danPinModels[0].subclass
self.danPinTableView?.reloadData()
self.collectionView?.reloadData()
//默认选中第一个cell,注意!!!一定要在刷新之后做!
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.danPinTableView?.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None)
//点用代理,选中cell,请求数据
self.tableView(self.danPinTableView!, didSelectRowAtIndexPath: indexPath)
}
}
}
|
apache-2.0
|
d05487355461a9b099fa6e351850e639
| 30.52071 | 145 | 0.645391 | 5.222549 | false | false | false | false |
noahemmet/FingerPaint
|
FingerPaint/TouchManager.swift
|
1
|
3337
|
//
// TouchManager.swift
// FingerPaint
//
// Created by Noah Emmet on 5/8/16.
// Copyright © 2016 Sticks. All rights reserved.
//
import Foundation
public class TouchManager {
public private(set) var stroke: Stroke = Stroke(points: [])
public private(set) var anchors: [Touch] = []
public private(set) var touchFrames: [TouchFrame] = []
// public private(set) var touches: Set<Touch> = []
public var state: UIGestureRecognizerState {
guard let previousFrame = touchFrames.elementAtIndex(touchFrames.count-2),
let newestFrame = touchFrames.last else {
return .Possible
}
if previousFrame.touches.count == 0 {
return .Began
} else if newestFrame.touches.count == 0 {
touchFrames = []
return .Ended
} else {
return .Changed
}
}
public var bezierPath: UIBezierPath {
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(touchFrames.first!.touches.first!.location)
print("Count: ", touchFrames.count)
for (index, touchFrame) in touchFrames.enumerate() {
print(index)
guard let previousFrame = touchFrames.elementAtIndex(index-1) else {
print("nope ", index)
for touch in touchFrame.touches {
bezierPath.addLineToPoint(touch.location)
}
continue
}
let diffCount = (from: previousFrame.touches.count, to: touchFrame.touches.count)
switch diffCount {
case (from: 0, to: 0):
fatalError("Beginning from .None to .None is illegal")
case (from: 0, to: 1):
print("began from .None to .Single")
case (from: 0, to: 2):
print("began from .None to .Double")
case (from: 1, to: 0):
print("ended from .Single to .None")
case (from: 1, to: 1):
// print("moved from .Single to .Single")
break
case (from: 1, to: 2):
print("changed from .Single to .Double")
case (from: 2, to: 0):
print("ended from .Double to .None")
case (from: 2, to: 1):
print("changed from .Double to .Single")
// touchNodes.append(next)
case (from: 2, to: 2):
print("moved from .Double to .Double")
break
default:
print("Not handling >2 touches")
// fatalError("Not handling >2 touches")
}
}
return bezierPath
}
public func appendTouchFrame(touchFrame: TouchFrame) {
touchFrames.append(touchFrame)
}
public func addTouches(touches: [Touch]) {
let touchFrame = TouchFrame(previous: touchFrames.last, addTouches: touches)
appendTouchFrame(touchFrame)
}
public func moveTouches(touches: [Touch]) {
let touchFrame = TouchFrame(previous: touchFrames.last!, addTouches: touches)
appendTouchFrame(touchFrame)
}
public func removeTouches(touches: [Touch]) {
let touchFrame = TouchFrame(previous: touchFrames.last!, addTouches: touches)
appendTouchFrame(touchFrame)
}
public func addTouches(uiTouches: Set<UITouch>) {
let touchFrame = TouchFrame(previous: touchFrames.last, addTouches: uiTouches)
touchFrames.append(touchFrame)
}
public func moveTouches(uiTouches: Set<UITouch>) {
let touchFrame = TouchFrame(previous: touchFrames.last!, moveTouches: uiTouches)
touchFrames.append(touchFrame)
}
public func removeTouches(uiTouches: Set<UITouch>) {
let touchFrame = TouchFrame(previous: touchFrames.last!, removeTouches: uiTouches)
touchFrames.append(touchFrame)
}
}
|
apache-2.0
|
329948705ab84b37cf757ef828671ddb
| 24.272727 | 84 | 0.677158 | 3.411043 | false | false | false | false |
pauljohanneskraft/Math
|
CoreMath/Classes/Functions/Discrete Functions/Smoothing.swift
|
1
|
1405
|
//
// Smoothing.swift
// Math
//
// Created by Paul Kraft on 17.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Cocoa
extension DiscreteFunction {
public func smoothed(using range: CountableRange<Int>) -> DiscreteFunction {
let maxIndex = points.count - 1
let newPoints = self.points.indices.map { index -> Point in
let range = max(index + range.lowerBound, 0)...min(index + range.upperBound - 1, maxIndex)
let y = points[range].reduce(into: 0.0) { (acc: inout Double, point: Point) in acc += point.y }
return (x: points[index].x, y: y / Double(range.count))
}
return DiscreteFunction(points: newPoints)
}
public func smoothed(using range: CountableClosedRange<Int>) -> DiscreteFunction {
let maxIndex = points.count - 1
let newPoints = self.points.indices.map { index -> Point in
let range = max(index + range.lowerBound, 0)...min(index + range.upperBound, maxIndex)
let y = points[range].reduce(into: 0.0) { (acc: inout Double, point: Point) in acc += point.y }
return (x: points[index].x, y: y / Double(range.count))
}
return DiscreteFunction(points: newPoints)
}
public func smoothed(usingLast count: Int) -> DiscreteFunction {
return smoothed(using: (-count)...0)
}
}
|
mit
|
a63fc2271ece65ccb4046f95f74d33f3
| 36.945946 | 107 | 0.615385 | 3.95493 | false | false | false | false |
uasys/swift
|
test/refactoring/SyntacticRename/callsites.swift
|
5
|
3872
|
func /*defaults:def*/withDefaults(_ xx: Int = 4, y: Int = 2, x: Int = 1) {}
// valid
/*defaults:call*/withDefaults()
/*defaults:call*/withDefaults(2)
/*defaults:call*/withDefaults(y: 2)
/*defaults:call*/withDefaults(2, x: 3)
/*defaults:call*/withDefaults(y: 2, x: 3)
/*defaults:call*/withDefaults(2, y: 1, x: 4)
// false positives
/*defaults:call*/withDefaults(y: 2, 3)
/*defaults:call*/withDefaults(y: 2, 4, x: 3)
// invalid
/*defaults:call*/withDefaults(x: 2, y: 3)
func /*trailing:def*/withTrailingClosure(x: Int, y: () -> Int) {}
// valid
/*trailing:call*/withTrailingClosure(x: 2, y: { return 1})
/*trailing:call*/withTrailingClosure(x: 2) { return 1}
// false positives
/*trailing:call*/withTrailingClosure(x: 1, y: 2) { return 1}
/*trailing:call*/withTrailingClosure(x: 1, y: 2) { return 1}
/*trailing:call*/withTrailingClosure(x: 2)
{ return 1}
func /*varargs:def*/withVarargs(x: Int..., y: Int, _: Int) {}
// valid
/*varargs:call*/withVarargs(x: 1, 2, 3, y: 2, 4)
/*varargs:call*/withVarargs(y: 2, 4)
// false positives
/*varargs:call*/withVarargs(x: 1, y: 2, 4, 5)
//invalid
/*varargs:call*/withVarargs(2, y: 2)
func /*varargs2:def*/withVarargs(x: Int, y: Int, _: Int...) {}
// valid
/*varargs2:call*/withVarargs(x: 1, y: 2, 4, 5)
/*varargs2:call*/withVarargs(x: 1, y: 2)
// false positive
/*varargs2:call*/withVarargs(x: 1, 2, y: 2, 4)
func /*mixed:def*/withAllOfTheAbove(x: Int = 2, _: Int..., z: Int = 2, c: () -> Int) {}
// valid
/*mixed:call*/withAllOfTheAbove(2){ return 1 }
/*mixed:call*/withAllOfTheAbove(x: 1, 2, c: {return 1})
/*mixed:call*/withAllOfTheAbove(x: 1, c: {return 1})
/*mixed:call*/withAllOfTheAbove(1, z: 1) { return 1 }
/*mixed:call*/withAllOfTheAbove(1, 2, c: {return 1})
// false positives
/*mixed:call*/withAllOfTheAbove(z: 1, 2, c: {return 1})
// RUN: rm -rf %t.result && mkdir -p %t.result
// RUN: %refactor -syntactic-rename -source-filename %s -pos="defaults" -is-function-like -old-name "withDefaults(_:y:x:)" -new-name "betterName(x:y:z:)" >> %t.result/callsites_defaults.swift
// RUN: diff -u %S/Outputs/callsites/defaults.swift.expected %t.result/callsites_defaults.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="trailing" -is-function-like -old-name "withTrailingClosure(x:y:)" -new-name "betterName(a:b:)" >> %t.result/callsites_trailing.swift
// RUN: diff -u %S/Outputs/callsites/trailing.swift.expected %t.result/callsites_trailing.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="varargs" -is-function-like -old-name "withVarargs(x:y:_:)" -new-name "betterName(a:b:c:)" >> %t.result/callsites_varargs.swift
// RUN: diff -u %S/Outputs/callsites/varargs.swift.expected %t.result/callsites_varargs.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="varargs2" -is-function-like -old-name "withVarargs(x:y:_:)" -new-name "betterName(a:b:c:)" >> %t.result/callsites_varargs2.swift
// RUN: diff -u %S/Outputs/callsites/varargs2.swift.expected %t.result/callsites_varargs2.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="mixed" -is-function-like -old-name "withAllOfTheAbove(x:_:z:c:)" -new-name "betterName(a:b:c:d:)" >> %t.result/callsites_mixed.swift
// RUN: diff -u %S/Outputs/callsites/mixed.swift.expected %t.result/callsites_mixed.swift
// RUN: rm -rf %t.ranges && mkdir -p %t.ranges
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="defaults" -is-function-like -old-name "withDefaults(_:y:x:)" >> %t.ranges/callsites_defaults.swift
// RUN: diff -u %S/FindRangeOutputs/callsites/defaults.swift.expected %t.ranges/callsites_defaults.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="trailing" -is-function-like -old-name "withTrailingClosure(x:y:)" >> %t.ranges/callsites_trailing.swift
// RUN: diff -u %S/FindRangeOutputs/callsites/trailing.swift.expected %t.ranges/callsites_trailing.swift
|
apache-2.0
|
02210cd413cb58b8a36fb6900be86235
| 46.219512 | 194 | 0.692407 | 2.809869 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Settings/Clearables.swift
|
1
|
5894
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
import SDWebImage
import CoreSpotlight
private let log = Logger.browserLogger
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
fileprivate let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String { .ClearableHistory }
func clear() -> Success {
// Treat desktop sites as part of browsing history.
Tab.ChangeUserAgent.clear()
return profile.history.clearHistory().bindQueue(.main) { success in
SDImageCache.shared.clearDisk()
SDImageCache.shared.clearMemory()
self.profile.recentlyClosedTabs.clearTabs()
CSSearchableIndex.default().deleteAllSearchableItems()
NotificationCenter.default.post(name: .PrivateDataClearedHistory, object: nil)
log.debug("HistoryClearable succeeded: \(success).")
return Deferred(value: success)
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: Error
init(err: Error) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String { .ClearableCache }
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: .distantPast, completionHandler: {})
MemoryReaderModeCache.sharedInstance.clear()
DiskReaderModeCache.sharedInstance.clear()
log.debug("CacheClearable succeeded.")
return succeed()
}
}
private func deleteLibraryFolderContents(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: .libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
let contents = try manager.contentsOfDirectory(atPath: dir.path)
for content in contents {
do {
try manager.removeItem(at: dir.appendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "Not permitted". We ignore this.
log.debug("Couldn't delete some library contents.")
}
}
}
private func deleteLibraryFolder(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: .libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
try manager.removeItem(at: dir)
}
// Removes all app cache storage.
class SiteDataClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String { .ClearableOfflineData }
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: .distantPast, completionHandler: {})
log.debug("SiteDataClearable succeeded.")
return succeed()
}
}
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String { .ClearableCookies }
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: .distantPast, completionHandler: {})
log.debug("CookiesClearable succeeded.")
return succeed()
}
}
class TrackingProtectionClearable: Clearable {
//@TODO: re-using string because we are too late in cycle to change strings
var label: String {
return Strings.SettingsTrackingProtectionSectionName
}
func clear() -> Success {
let result = Success()
ContentBlocker.shared.clearSafelist() {
result.fill(Maybe(success: ()))
}
return result
}
}
// Clears our downloaded files in the `~/Documents/Downloads` folder.
class DownloadedFilesClearable: Clearable {
var label: String { .ClearableDownloads }
func clear() -> Success {
if let downloadsPath = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads"),
let files = try? FileManager.default.contentsOfDirectory(at: downloadsPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants]) {
for file in files {
try? FileManager.default.removeItem(at: file)
}
}
NotificationCenter.default.post(name: .PrivateDataClearedDownloadedFiles, object: nil)
return succeed()
}
}
|
mpl-2.0
|
0ab3c941485115a4c22b53d37850b40e
| 32.299435 | 209 | 0.689175 | 4.944631 | false | false | false | false |
ksti/XCodeTemplates
|
Project Templates/iOS/Application/Game.xctemplate/SceneKit_GameViewController.swift
|
1
|
4049
|
//
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
// animate the 3d object
ship.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1)))
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.blackColor()
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
scnView.addGestureRecognizer(tapGesture)
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view as! SCNView
// check what nodes are tapped
let p = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material.emission.contents = UIColor.redColor()
SCNTransaction.commit()
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
|
gpl-3.0
|
8b8d890f4feb9e1332dd0a990443b9f5
| 31.392 | 102 | 0.588046 | 5.662937 | false | false | false | false |
vkaramov/VKSplitViewController
|
SwiftDemo/SwiftDemo/SDMasterViewController.swift
|
1
|
1288
|
//
// ViewController.swift
// SwiftDemo
//
// Created by Viacheslav Karamov on 04.07.15.
// Copyright (c) 2015 Viacheslav Karamov. All rights reserved.
//
import UIKit
class SDMasterViewController: UITableViewController
{
static let kNavigationStoryboardId = "MasterNavigationController";
static let colors = [UIColor.redColor(), UIColor.orangeColor(), UIColor.yellowColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.magentaColor()];
var detailController : SDDetailViewController?;
override func viewDidLoad()
{
super.viewDidLoad();
let splitController = UIApplication.sharedApplication().delegate?.window??.rootViewController as? VKSplitViewController;
let detailNavController = splitController?.detailViewController as? UINavigationController;
detailController = detailNavController?.viewControllers.first as? SDDetailViewController;
selectRowAtIndex(0);
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
selectRowAtIndex(indexPath.row);
}
private func selectRowAtIndex(index : Int)
{
self.detailController?.setBackgroundColor(SDMasterViewController.colors[index]);
}
}
|
mit
|
13fee597efc65aed219d1379eb8172c8
| 29.666667 | 158 | 0.716615 | 5.434599 | false | false | false | false |
andrzejsemeniuk/ASToolkit
|
ASToolkit/UILabelWithInsets.swift
|
1
|
1288
|
//
// UILabelWithInsets.swift
// ASToolkit
//
// Created by andrzej semeniuk on 2/4/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
open class UILabelWithInsets: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
open class UITextFieldWithInsets: UITextField {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
|
mit
|
44e530cb2f952c475ce70037bedf26db
| 24.235294 | 70 | 0.634033 | 4.820225 | false | false | false | false |
kstaring/swift
|
stdlib/public/core/Bool.swift
|
1
|
9335
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Bool Datatype and Supporting Operators
//===----------------------------------------------------------------------===//
/// A value type whose instances are either `true` or `false`.
///
/// `Bool` represents Boolean values in Swift. Create instances of `Bool` by
/// using one of the Boolean literals `true` or `false`, or by assigning the
/// result of a Boolean method or operation to a variable or constant.
///
/// var godotHasArrived = false
///
/// let numbers = 1...5
/// let containsTen = numbers.contains(10)
/// print(containsTen)
/// // Prints "false"
///
/// let (a, b) = (100, 101)
/// let aFirst = a < b
/// print(aFirst)
/// // Prints "true"
///
/// Swift uses only simple Boolean values in conditional contexts to help avoid
/// accidental programming errors and to help maintain the clarity of each
/// control statement. Unlike in other programming languages, in Swift, integers
/// and strings cannot be used where a Boolean value is required.
///
/// For example, the following code sample does not compile, because it
/// attempts to use the integer `i` in a logical context:
///
/// var i = 5
/// while i {
/// print(i)
/// i -= 1
/// }
///
/// The correct approach in Swift is to compare the `i` value with zero in the
/// `while` statement.
///
/// while i != 0 {
/// print(i)
/// i -= 1
/// }
///
/// Using Imported Boolean values
/// =============================
///
/// The C `bool` and `Boolean` types and the Objective-C `BOOL` type are all
/// bridged into Swift as `Bool`. The single `Bool` type in Swift guarantees
/// that functions, methods, and properties imported from C and Objective-C
/// have a consistent type interface.
@_fixed_layout
public struct Bool {
internal var _value: Builtin.Int1
/// Creates an instance initialized to `false`.
///
/// Do not call this initializer directly. Instead, use the Boolean literal
/// `false` to create a new `Bool` instance.
@_transparent
public init() {
let zero: Int8 = 0
self._value = Builtin.trunc_Int8_Int1(zero._value)
}
@_versioned
@_transparent
internal init(_ v: Builtin.Int1) { self._value = v }
public init(_ value: Bool) {
self = value
}
}
extension Bool : _ExpressibleByBuiltinBooleanLiteral, ExpressibleByBooleanLiteral {
@_transparent
public init(_builtinBooleanLiteral value: Builtin.Int1) {
self._value = value
}
/// Creates an instance initialized to the specified Boolean literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use a Boolean literal. Instead, create a new `Bool` instance by
/// using one of the Boolean literals `true` or `false`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// In this example, both assignments to the `printedMessage` variable call
/// this Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
@_transparent
public init(booleanLiteral value: Bool) {
self = value
}
}
extension Bool {
// This is a magic entry point known to the compiler.
@_transparent
public // COMPILER_INTRINSIC
func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}
}
extension Bool : CustomStringConvertible {
/// A textual representation of the Boolean value.
public var description: String {
return self ? "true" : "false"
}
}
// This is a magic entry point known to the compiler.
@_transparent
public // COMPILER_INTRINSIC
func _getBool(_ v: Builtin.Int1) -> Bool { return Bool(v) }
extension Bool : Equatable, Hashable {
/// The hash value for the Boolean value.
///
/// Two values that are equal always have equal hash values.
///
/// - Note: The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
/// - SeeAlso: `Hashable`
@_transparent
public var hashValue: Int {
return self ? 1 : 0
}
@_transparent
public static func == (lhs: Bool, rhs: Bool) -> Bool {
return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))
}
}
extension Bool : LosslessStringConvertible {
public init?(_ description: String) {
if description == "true" {
self = true
} else if description == "false" {
self = false
} else {
return nil
}
}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
extension Bool {
/// Performs a logical NOT operation on a Boolean value.
///
/// The logical NOT operator (`!`) inverts a Boolean value. If the value is
/// `true`, the result of the operation is `false`; if the value is `false`,
/// the result is `true`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// - Parameter a: The Boolean value to negate.
@_transparent
public static prefix func ! (a: Bool) -> Bool {
return Bool(Builtin.xor_Int1(a._value, true._value))
}
}
extension Bool {
/// Performs a logical AND operation on two Bool values.
///
/// The logical AND operator (`&&`) combines two Bool values and returns
/// `true` if both of the values are `true`. If either of the values is
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `true`. For example:
///
/// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]
/// let sum = measurements.reduce(0, combine: +)
///
/// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {
/// print("Average measurement is less than 6.5")
/// }
/// // Prints "Average measurement is less than 6.5"
///
/// In this example, `lhs` tests whether `measurements.count` is greater than
/// zero. Evaluation of the `&&` operator is one of the following:
///
/// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`
/// and `rhs` is not evaluated, preventing a divide-by-zero error in the
/// expression `sum / Double(measurements.count)`. The result of the
/// operation is `false`.
/// - When `measurements.count` is greater than zero, `lhs` evaluates to
/// `true` and `rhs` is evaluated. The result of evaluating `rhs` is the
/// result of the `&&` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@_transparent
@inline(__always)
public static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows
-> Bool{
return lhs ? try rhs() : false
}
/// Performs a logical OR operation on two Bool values.
///
/// The logical OR operator (`||`) combines two Bool values and returns
/// `true` if at least one of the values is `true`. If both values are
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `false`. For example:
///
/// let majorErrors: Set = ["No first name", "No last name", ...]
/// let error = ""
///
/// if error.isEmpty || !majorErrors.contains(error) {
/// print("No major errors detected")
/// } else {
/// print("Major error: \(error)")
/// }
/// // Prints "No major errors detected"
///
/// In this example, `lhs` tests whether `error` is an empty string.
/// Evaluation of the `||` operator is one of the following:
///
/// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is
/// not evaluated, skipping the call to `majorErrors.contains(_:)`. The
/// result of the operation is `true`.
/// - When `error` is not an empty string, `lhs` evaluates to `false` and
/// `rhs` is evaluated. The result of evaluating `rhs` is the result of the
/// `||` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@_transparent
@inline(__always)
public static func || (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows
-> Bool {
return lhs ? true : try rhs()
}
}
|
apache-2.0
|
75d86566e48522fd566c04b20eec5fc0
| 33.194139 | 83 | 0.601178 | 4.09071 | false | false | false | false |
dvlproad/CJUIKit
|
CJBaseUIKit-Swift/UIButton/UIButton+CJUpDownStructure.swift
|
1
|
3099
|
//
// UIButton+CJUpDownStructure.m
// CJUIKitDemo
//
// Created by ciyouzen on 2017/7/3.
// Copyright © 2017年 dvlproad. All rights reserved.
//
extension UIButton {
/**
* 将图片和文字竖直排放(调用前提:必须保证你的button的size已经确定后才能调用)
* @attention 也要保证Button的宽度一定要大于等于图片的宽
*
* @param spacing 图片和文字的间隔为多少
*/
func cjVerticalImageAndTitle(spacing: CGFloat) {
let imageSize: CGSize = self.imageView!.frame.size
var titleSize: CGSize = self.titleLabel!.frame.size
let text: String = self.titleLabel!.text!
let font: UIFont = self.titleLabel!.font
//CGSize textSize = [text sizeWithFont:font];
let maxSize: CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.font: font
]
let textRect: CGRect = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let textSize: CGSize = textRect.size
let frameWidth: CGFloat = CGFloat(ceilf(Float(textSize.width)))
let frameHeight: CGFloat = CGFloat(ceilf(Float(textSize.height)))
let frameSize: CGSize = CGSize(width: frameWidth, height: frameHeight)
if titleSize.width+0.5 < frameSize.width {
titleSize.width = frameSize.width
}
let totalFrameHeight: CGFloat = (imageSize.height+spacing+titleSize.height)
self.imageEdgeInsets = UIEdgeInsets(top: -(totalFrameHeight-imageSize.height), left: 0.0, bottom: 0.0, right: -titleSize.width)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: -(totalFrameHeight-titleSize.height), right: 0)
}
/**
* 左图片、右文字时候
*
* @param spacing 图片与文字的间隔
* @param leftOffset 视图与左边缘的距离
*/
func cjLeftImageOffset(leftOffset: CGFloat, imageAndTitleSpacing spacing: CGFloat) {
self.contentHorizontalAlignment = .left
//水平左对齐
self.contentVerticalAlignment = .center
//垂直居中对齐
/**
* 按照上面的操作 按钮的内容对津贴屏幕左边缘 不美观 可以添加一下代码实现间隔已达到美观
* UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)
* top: 为正数:表示向下偏移 为负数:表示向上偏移
* left: 为整数:表示向右偏移 为负数:表示向左偏移
* bottom: 为整数:表示向上偏移 为负数:表示向下偏移
* right: 为整数:表示向左偏移 为负数:表示向右偏移
*
**/
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: leftOffset, bottom: 0, right: 0)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: leftOffset+spacing, bottom: 0, right: 0)
}
}
|
mit
|
c8f47cc12bcec64e71d72ca7285ade09
| 40.53125 | 135 | 0.648608 | 3.791726 | false | false | false | false |
matrix-org/matrix-ios-sdk
|
MatrixSDK/Background/MXBackgroundPushRulesManager.swift
|
1
|
7976
|
//
// Copyright 2020 The Matrix.org Foundation C.I.C
//
// 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
/// Background push rules manager. Does work independent from a `MXNotificationCenter`.
@objcMembers public class MXBackgroundPushRulesManager: NSObject {
private let credentials: MXCredentials
private var pushRulesResponse: MXPushRulesResponse? {
didSet {
var tmpRules: [MXPushRule] = []
if let global = pushRulesResponse?.global {
if let rules = global.override as? [MXPushRule] {
tmpRules.append(contentsOf: rules)
}
if let rules = global.content as? [MXPushRule] {
tmpRules.append(contentsOf: rules)
}
if let rules = global.room as? [MXPushRule] {
tmpRules.append(contentsOf: rules)
}
if let rules = global.sender as? [MXPushRule] {
tmpRules.append(contentsOf: rules)
}
if let rules = global.underride as? [MXPushRule] {
tmpRules.append(contentsOf: rules)
}
}
flatRules = tmpRules
}
}
private var flatRules: [MXPushRule] = []
private var eventMatchConditionChecker: MXPushRuleEventMatchConditionChecker
private var memberCountConditionChecker: MXPushRuleRoomMemberCountConditionChecker
private var permissionConditionChecker: MXPushRuleSenderNotificationPermissionConditionChecker
/// Initializer.
/// - Parameter credentials: Credentials to use when fetching initial push rules.
public init(withCredentials credentials: MXCredentials) {
self.credentials = credentials
eventMatchConditionChecker = MXPushRuleEventMatchConditionChecker()
memberCountConditionChecker = MXPushRuleRoomMemberCountConditionChecker(matrixSession: nil)
permissionConditionChecker = MXPushRuleSenderNotificationPermissionConditionChecker(matrixSession: nil)
super.init()
}
/// Handle account data from a sync response.
/// - Parameter accountData: The account data to be handled.
public func handleAccountData(_ accountData: [AnyHashable: Any]) {
guard let events = accountData["events"] as? [[AnyHashable: Any]] else { return }
events.forEach { (event) in
if let type = event["type"] as? String,
type == kMXAccountDataTypePushRules,
let content = event["content"] as? [AnyHashable: Any] {
self.pushRulesResponse = MXPushRulesResponse(fromJSON: content)
}
}
}
/// Check whether the given room is mentions only.
/// - Parameter roomId: The room identifier to be checked
/// - Returns: If the room is mentions only.
public func isRoomMentionsOnly(_ roomId: String) -> Bool {
// Check push rules at room level
guard let rule = self.getRoomPushRule(forRoom: roomId) else {
return false
}
for ruleAction in rule.actions {
guard let action = ruleAction as? MXPushRuleAction else { continue }
if action.actionType == MXPushRuleActionTypeDontNotify {
return rule.enabled
}
}
return false
}
/// Fetch push rule matching an event.
/// - Parameters:
/// - event: The event to be matched.
/// - roomState: Room state.
/// - currentUserDisplayName: Display name of the current user.
/// - Returns: Push rule matching the event.
public func pushRule(matching event: MXEvent,
roomState: MXRoomState,
currentUserDisplayName: String?) -> MXPushRule? {
// return nil if current user's event
if event.sender == credentials.userId {
return nil
}
let displayNameChecker = MXPushRuleDisplayNameCondtionChecker(matrixSession: nil,
currentUserDisplayName: currentUserDisplayName)
let conditionCheckers: [MXPushRuleConditionType: MXPushRuleConditionChecker] = [
.eventMatch: eventMatchConditionChecker,
.containsDisplayName: displayNameChecker,
.roomMemberCount: memberCountConditionChecker,
.senderNotificationPermission: permissionConditionChecker
]
let eventDictionary = event.jsonDictionary()
let equivalentCondition = MXPushRuleCondition()
for rule in flatRules.filter({ $0.enabled }) {
var conditionsOk: Bool = true
var runEquivalent: Bool = false
guard let kind = MXPushRuleKind(identifier: rule.kind) else { continue }
switch kind {
case .override, .underride:
conditionsOk = true
for condition in rule.conditions {
guard let condition = condition as? MXPushRuleCondition else { continue }
let conditionType = MXPushRuleConditionType(identifier: condition.kind)
if let checker = conditionCheckers[conditionType] {
conditionsOk = checker.isCondition(condition,
satisfiedBy: event,
roomState: roomState,
withJsonDict: eventDictionary)
if !conditionsOk {
// Do not need to go further
break
}
} else {
conditionsOk = false
}
}
case .content:
equivalentCondition.parameters = [
"key": "content.body",
"pattern": rule.pattern as Any
]
runEquivalent = true
case .room:
equivalentCondition.parameters = [
"key": "room_id",
"pattern": rule.ruleId as Any
]
runEquivalent = true
case .sender:
equivalentCondition.parameters = [
"key": "user_id",
"pattern": rule.ruleId as Any
]
runEquivalent = true
}
if runEquivalent {
conditionsOk = eventMatchConditionChecker.isCondition(equivalentCondition,
satisfiedBy: event,
roomState: roomState,
withJsonDict: eventDictionary)
}
if conditionsOk {
return rule
}
}
return nil
}
// MARK: - Private
private func getRoomPushRule(forRoom roomId: String) -> MXPushRule? {
guard let rules = pushRulesResponse?.global.room as? [MXPushRule] else {
return nil
}
return rules.first(where: { roomId == $0.ruleId })
}
}
|
apache-2.0
|
f6273512d71575fcc4c7210f9f478de1
| 40.326425 | 117 | 0.551153 | 5.418478 | false | false | false | false |
hejunbinlan/actor-platform
|
actor-apps/app-ios/Actor/Controllers/Contacts/Cells/ContactCell.swift
|
55
|
2007
|
//
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
class ContactCell : BasicCell {
let avatarView = AvatarView(frameSize: 40, type: .Rounded);
let shortNameView = UILabel();
let titleView = UILabel();
init(reuseIdentifier:String) {
super.init(reuseIdentifier: reuseIdentifier, separatorPadding: 80)
titleView.font = UIFont(name: "HelveticaNeue", size: 18);
titleView.textColor = MainAppTheme.list.contactsTitle
shortNameView.font = UIFont(name: "HelveticaNeue-Bold", size: 18);
shortNameView.textAlignment = NSTextAlignment.Center
shortNameView.textColor = MainAppTheme.list.contactsShortTitle
self.contentView.addSubview(avatarView);
self.contentView.addSubview(shortNameView);
self.contentView.addSubview(titleView);
backgroundColor = MainAppTheme.list.bgColor
var selectedView = UIView()
selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor
selectedBackgroundView = selectedView
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindContact(contact: AMContact, shortValue: String?, isLast: Bool) {
avatarView.bind(contact.getName(), id: contact.getUid(), avatar: contact.getAvatar());
titleView.text = contact.getName();
if (shortValue == nil){
shortNameView.hidden = true;
} else {
shortNameView.text = shortValue!;
shortNameView.hidden = false;
}
hideSeparator(isLast)
}
override func layoutSubviews() {
super.layoutSubviews()
var width = self.contentView.frame.width;
shortNameView.frame = CGRectMake(0, 8, 30, 40);
avatarView.frame = CGRectMake(30, 8, 40, 40);
titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40);
}
}
|
mit
|
18da1aeae136a2475b2d14c2e245246e
| 31.918033 | 94 | 0.632785 | 5.004988 | false | false | false | false |
CoderLiLe/Swift
|
if/main.swift
|
1
|
1207
|
//
// main.swift
// if
//
// Created by LiLe on 15/3/3.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
if语句基本使用
OC:
int age1 = 10;
int age2 = 20;
int max;
max = age2;
if (age1 > age2) {
max = age1;
}
NSLog(@"%d", max);
if (age1 > age2) {
max = age1;
}else
{
max = age2;
}
NSLog(@"%d", max);
如果只有一条指令if后面的大括号可以省略
Swift:
if 条件表达式 {指令} if 条件表达式 {指令} else{指令}
0.if后的圆括号可以省略
1.只能以bool作为条件语句
2.如果只有条指令if后面的大括号不可以省略
*/
var age1:Int
var age2:Int
var max:Int
max = age2;
if age1 > age2
{
max = age1
}
print(max)
if age1 > age2
{
max = age1;
}else
{
max = age2;
}
print(max)
/*
多分支
OC:
float score = 99.9;
if (score >= 90) {
NSLog(@"优秀");
}else
{
if (score >= 60) {
NSLog(@"良好");
}else
{
NSLog(@"不给力");
}
}
if (score >= 90) {
NSLog(@"优秀");
}else if (score >= 60)
{
NSLog(@"良好");
}else
{
NSLog(@"不给力");
}
*/
var score = 99.9;
if score >= 90
{
print("优秀")
}else if score >= 60
{
print("良好")
}else
{
print("不给力")
}
|
mit
|
2c725ac946b2fa0266906b0f6c99aabb
| 9.46875 | 50 | 0.549254 | 2.228381 | false | false | false | false |
gigascorp/fiscal-cidadao
|
ios/FiscalCidadao/DenunciaReadViewController.swift
|
1
|
7653
|
/*
Copyright (c) 2009-2014, Apple Inc. All rights reserved.
Copyright (C) 2016 Andrea Mendonça, Emílio Weba, Guilherme Ribeiro, Márcio Oliveira, Thiago Nunes, Wallas Henrique
This file is part of Fiscal Cidadão.
Fiscal Cidadão is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fiscal Cidadão is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Fiscal Cidadão. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class DenunciaReadViewController: UITableViewController
{
var denuncia : Denuncia?
var convenio : Convenio?
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var proponentLabel: UILabel!
@IBOutlet weak var responsibleLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
let photoGalleryView = PhotoGalleryView()
let formarter = NSNumberFormatter()
var descHeight : CGFloat = 0
var commentsHeight : CGFloat = 0
override func viewDidLoad()
{
super.viewDidLoad()
formarter.locale = NSLocale(localeIdentifier: "pt_BR")
formarter.positiveFormat = "###,##0.00"
self.tableView.delegate = self
self.tableView.dataSource = self
self.convenio = self.denuncia?.convenio
var attributes = [String : AnyObject]()
let font = UIFont.systemFontOfSize(15)
attributes[NSFontAttributeName] = font
let margin : CGFloat = 15 // Cell margin checked in storyboard
let width = (tableView.frame.size.width - 2 * margin)
// This is very tricky.
//
let baseSize = CGSize(width: width ,height: CGFloat.max)
if let desc = convenio?.desc
{
let boundingRect = desc.boundingRectWithSize(baseSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
// Add a padding
descHeight = boundingRect.height + 40
}
else
{
descHeight = tableView.rowHeight
}
if let comments = denuncia?.comments
{
let boundingRect = comments.boundingRectWithSize(baseSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
// Add a padding
commentsHeight = boundingRect.height + 40
}
else
{
commentsHeight = tableView.rowHeight
}
let data = DataController.sharedInstance
for photo in denuncia!.photos
{
data.makeHTTPGetRequest(photo, body: nil, onCompletion:
{
(data, err) in
let img = UIImage(data: data)
self.photoGalleryView.addPhoto(img!, removable: false)
})
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if denuncia!.photos.isEmpty
{
return 18
}
else
{
return 20
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : UITableViewCell!
if indexPath.row % 2 == 0
{
cell = tableView.dequeueReusableCellWithIdentifier("SectionCell", forIndexPath: indexPath)
}
else if indexPath.row == 19
{
cell = tableView.dequeueReusableCellWithIdentifier("GalleryCell", forIndexPath: indexPath)
}
else
{
cell = tableView.dequeueReusableCellWithIdentifier("DetailCell", forIndexPath: indexPath)
}
switch indexPath.row
{
case 0:
cell?.textLabel?.text = "Denúncia"
case 1:
cell?.textLabel?.text = denuncia?.comments
case 2:
cell?.textLabel?.text = "Data da denúncia"
case 3:
cell?.textLabel?.text = denuncia?.denunciaDate!
case 4:
cell?.textLabel?.text = "Parecer do governo"
case 5:
cell?.textLabel?.text = denuncia?.status
case 6:
cell?.textLabel?.text = "Descrição"
case 7:
cell?.textLabel?.text = convenio?.desc
case 8:
cell?.textLabel?.text = "Proponente"
case 9:
cell?.textLabel?.text = convenio?.proponent
case 10:
cell?.textLabel?.text = "Responsável"
case 11:
cell?.textLabel?.text = convenio?.responsible
case 12:
cell?.textLabel?.text = "Telefone"
case 13:
cell?.textLabel?.text = convenio?.responsiblePhone
case 14:
cell?.textLabel?.text = "Período"
case 15:
cell?.textLabel?.text = (convenio?.startDate)! + " à " + (convenio?.endDate)!
case 16:
cell?.textLabel?.text = "Valor"
case 17:
cell?.textLabel?.text = "R$ " + formarter.stringFromNumber(NSNumber(float: (convenio?.value)!))!
case 18:
cell?.textLabel?.text = "Fotos Enviadas"
case 19:
if let galleryCell = cell as? GalleryTableViewCell
{
photoGalleryView.topView = self.view
photoGalleryView.addToScrollView(galleryCell.scrollView)
}
default:
cell?.textLabel?.text = " "
}
// let cell = tableView.dequeueReusableCellWithIdentifier("section", forIndexPath: indexPath)
// Configure the cell...
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if indexPath.row == 1
{
return commentsHeight
}
else if indexPath.row == 19
{
return 120 // Hard coded, got by the storyboard
}
else if indexPath.row == 7
{
return descHeight
}
else
{
return self.tableView.rowHeight
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "ComplaintSegue"
{
if let cvc = segue.destinationViewController as? DenunciaViewController
{
cvc.convenio = convenio
}
}
}
}
|
gpl-3.0
|
83f3f3de4082caf5da8ba9ed7906adc3
| 29.802419 | 164 | 0.585155 | 5.019054 | false | false | false | false |
marcelganczak/swift-js-transpiler
|
test/types/array.swift
|
1
|
864
|
var arrayOfInts: [Int] = [1, 2, 3]
print(arrayOfInts[0])
print(arrayOfInts.count)
arrayOfInts.append(5)
arrayOfInts.insert(4, at: 3)
arrayOfInts.append(contentsOf: [9, 10, 11])
arrayOfInts.insert(contentsOf: [6, 7, 8], at: 5)
arrayOfInts += [12, 13, 14]
print(arrayOfInts.count)
print(arrayOfInts[4])
print(arrayOfInts[5])
print(arrayOfInts[7])
arrayOfInts.remove(at: 2)
print(arrayOfInts.count)
print(arrayOfInts[2])
var arrayOfStrings: [String] = ["We", "love", "Swift"]
print(arrayOfStrings[0])
print(arrayOfStrings.count)
var emptyArray: [Int] = []
print(emptyArray.count)
var inferredArrayOfInts = [1, 2, 3]
print(inferredArrayOfInts[0])
print(inferredArrayOfInts.count)
var inferredEmptyArray = [Int]()
print(inferredEmptyArray.count)
var inferredFilledArray = [Int](repeating: 0, count: 3)
print(inferredFilledArray[0])
print(inferredFilledArray.count)
|
mit
|
0326dff0376c613f606314e1ec6e64f7
| 25.212121 | 55 | 0.751157 | 3.130435 | false | false | false | false |
devpunk/cartesian
|
cartesian/View/Settings/VSettingsCellRetina.swift
|
1
|
3312
|
import UIKit
class VSettingsCellRetina:VSettingsCell
{
private weak var check:UISwitch!
private let kLabelLeft:CGFloat = 10
private let kLabelWidth:CGFloat = 210
private let kCheckTop:CGFloat = 30
private let kCheckHeight:CGFloat = 100
private let kCheckWidth:CGFloat = 70
override init(frame:CGRect)
{
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:16),
NSForegroundColorAttributeName:UIColor.black]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:14),
NSForegroundColorAttributeName:UIColor.black]
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("VSettingsCellRetina_stringTitle", comment:""),
attributes:attributesTitle)
let stringSubtitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("VSettingsCellRetina_stringSubtitle", comment:""),
attributes:attributesSubtitle)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringSubtitle)
super.init(frame:frame)
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.attributedText = mutableString
let check:UISwitch = UISwitch()
check.translatesAutoresizingMaskIntoConstraints = false
check.tintColor = UIColor.black
check.onTintColor = UIColor.cartesianOrange
check.addTarget(
self,
action:#selector(actionCheck(sender:)),
for:UIControlEvents.valueChanged)
self.check = check
addSubview(label)
addSubview(check)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.leftToLeft(
view:label,
toView:self,
constant:kLabelLeft)
NSLayoutConstraint.width(
view:label,
constant:kLabelWidth)
NSLayoutConstraint.topToTop(
view:check,
toView:self,
constant:kCheckTop)
NSLayoutConstraint.height(
view:check,
constant:kCheckHeight)
NSLayoutConstraint.rightToRight(
view:check,
toView:self)
NSLayoutConstraint.width(
view:check,
constant:kCheckWidth)
loadRetina()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionCheck(sender check:UISwitch)
{
let retina:Bool = check.isOn
MSession.sharedInstance.settings?.retina = retina
DManager.sharedInstance?.save()
}
//MARK: private
private func loadRetina()
{
guard
let retina:Bool = MSession.sharedInstance.settings?.retina
else
{
return
}
check.isOn = retina
}
}
|
mit
|
8c3c58c26ed7ce2d94a04ca78a84f8f7
| 28.837838 | 87 | 0.611111 | 5.740035 | false | false | false | false |
jaynakus/Signals
|
SwiftSignalKit/Subscriber.swift
|
1
|
2688
|
import Foundation
public final class Subscriber<T, E> {
private var next: ((T) -> Void)!
private var error: ((E) -> Void)!
private var completed: (() -> Void)!
private var lock: OSSpinLock = 0
private var terminated = false
internal var disposable: Disposable!
public init(next: ((T) -> Void)! = nil, error: ((E) -> Void)! = nil, completed: (() -> Void)! = nil) {
self.next = next
self.error = error
self.completed = completed
}
internal func assignDisposable(_ disposable: Disposable) {
if self.terminated {
disposable.dispose()
} else {
self.disposable = disposable
}
}
internal func markTerminatedWithoutDisposal() {
OSSpinLockLock(&self.lock)
if !self.terminated {
self.terminated = true
self.next = nil
self.error = nil
self.completed = nil
}
OSSpinLockUnlock(&self.lock)
}
public func putNext(_ next: T) {
var action: ((T) -> Void)! = nil
OSSpinLockLock(&self.lock)
if !self.terminated {
action = self.next
}
OSSpinLockUnlock(&self.lock)
if action != nil {
action(next)
}
}
public func putError(_ error: E) {
var shouldDispose = false
var action: ((E) -> Void)! = nil
OSSpinLockLock(&self.lock)
if !self.terminated {
action = self.error
shouldDispose = true;
self.next = nil
self.error = nil
self.completed = nil;
self.terminated = true
}
OSSpinLockUnlock(&self.lock)
if action != nil {
action(error)
}
if shouldDispose && self.disposable != nil {
let disposable = self.disposable!
disposable.dispose()
self.disposable = nil
}
}
public func putCompletion() {
var shouldDispose = false
var action: (() -> Void)! = nil
OSSpinLockLock(&self.lock)
if !self.terminated {
action = self.completed
shouldDispose = true;
self.next = nil
self.error = nil
self.completed = nil;
self.terminated = true
}
OSSpinLockUnlock(&self.lock)
if action != nil {
action()
}
if shouldDispose && self.disposable != nil {
let disposable = self.disposable!
disposable.dispose()
self.disposable = nil
}
}
}
|
mit
|
39592d6481264b35969bdd3020f28b95
| 25.613861 | 106 | 0.5 | 4.878403 | false | false | false | false |
ryuichis/swift-lint
|
Sources/Metric/NPathComplexity.swift
|
2
|
5969
|
/*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project 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
import AST
/*
* References:
* - Brian A. Nejmeh (1988). “NPATH: a measure of execution path complexity and
* its applications”. Communications of the ACM 31 (2) p. 188-200
*/
public class NPathComplexity {
public func calculate(for codeBlock: CodeBlock) -> Int {
return nPath(codeBlock)
}
private func nPath(_ codeBlock: CodeBlock) -> Int {
return nPath(codeBlock.statements)
}
private func nPath(_ stmts: [Statement]) -> Int {
return stmts.reduce(1) { $0 * nPath($1) }
}
private func nPath(_ stmt: Statement) -> Int { // swift-lint:suppress(high_cyclomatic_complexity)
switch stmt {
case let deferStmt as DeferStatement:
return nPath(deferStmt.codeBlock)
case let doStmt as DoStatement:
return nPath(doStmt)
case let forStmt as ForInStatement:
return nPath(forStmt)
case let guardStmt as GuardStatement:
return nPath(guardStmt)
case let ifStmt as IfStatement:
return nPath(ifStmt)
case let labeledStmt as LabeledStatement:
return nPath(labeledStmt.statement)
case let repeatWhileStmt as RepeatWhileStatement:
return nPath(repeatWhileStmt)
case let returnStmt as ReturnStatement:
return 1 + (returnStmt.expression.map({ nPath(forExpression: $0) }) ?? 0)
case let switchStmt as SwitchStatement:
return nPath(switchStmt)
case let throwStmt as ThrowStatement:
return 1 + nPath(forExpression: throwStmt.expression)
case let whileStmt as WhileStatement:
return nPath(whileStmt)
case let expr as Expression:
return 1 + nPath(forExpression: expr)
default:
return 1
}
}
private func nPath(_ doStmt: DoStatement) -> Int {
return nPath(doStmt.codeBlock) + doStmt.catchClauses.reduce(0) {
var npCatch = $0 + nPath($1.codeBlock)
if let expr = $1.whereExpression {
npCatch += nPath(forExpression: expr) + 1
}
return npCatch
}
}
private func nPath(_ forStmt: ForInStatement) -> Int {
return 1 +
nPath(forStmt.codeBlock) +
nPath(forExpression: forStmt.collection) +
(forStmt.item.whereClause.map({ nPath(forExpression: $0) + 1 }) ?? 0)
}
private func nPath(_ guardStmt: GuardStatement) -> Int {
return 1 + nPath(guardStmt.codeBlock) + nPath(guardStmt.conditionList)
}
private func nPath(_ ifStmt: IfStatement) -> Int {
return nPath(ifStmt.codeBlock) +
nPath(ifStmt.conditionList) +
(
ifStmt.elseClause.map({
switch $0 {
case .else(let block):
return nPath(block)
case .elseif(let ifStmt):
return nPath(ifStmt)
}
}) ?? 1
)
}
private func nPath(_ repeatWhileStmt: RepeatWhileStatement) -> Int {
return 1 +
nPath(repeatWhileStmt.codeBlock) +
nPath(forExpression: repeatWhileStmt.conditionExpression)
}
private func nPath(_ switchStmt: SwitchStatement) -> Int {
let npExpr = nPath(forExpression: switchStmt.expression)
if switchStmt.cases.isEmpty {
return 1 + npExpr
}
return npExpr + switchStmt.cases.reduce(0) {
switch $1 {
case let .case(items, stmts):
let npItems = items.reduce(0) { carryOver, item in
let npWhere = item.whereExpression.map({ nPath(forExpression: $0) + 1 }) ?? 0
return carryOver + npWhere
}
return npItems + nPath(stmts) + $0
case .default(let stmts):
return nPath(stmts) + $0
}
}
}
private func nPath(_ whileStmt: WhileStatement) -> Int {
return 1 + nPath(whileStmt.codeBlock) + nPath(whileStmt.conditionList)
}
private func nPath(forExpression expr: Expression) -> Int { // swift-lint:rule_configure(NESTED_CODE_BLOCK_DEPTH=7)
class NPathExpressionVisitor : ASTVisitor {
var _count = 0
func cal(_ expr: Expression) -> Int {
_count = 0
do {
_ = try traverse(expr)
return _count
} catch {
return 0
}
}
func visit(_ biOpExpr: BinaryOperatorExpression) throws -> Bool {
let biOp = biOpExpr.binaryOperator
if biOp == "&&" || biOp == "||" {
_count += 1
}
return true
}
func visit(_ seqExpr: SequenceExpression) throws -> Bool {
for element in seqExpr.elements {
switch element {
case .binaryOperator(let biOp) where biOp == "&&" || biOp == "||":
_count += 1
case .ternaryConditionalOperator:
_count += 1
default:
continue
}
}
return true
}
func visit(_ ternaryExpr: TernaryConditionalOperatorExpression) throws -> Bool {
_count += 1
return true
}
}
return NPathExpressionVisitor().cal(expr)
}
private func nPath(_ conditionList: ConditionList) -> Int {
return conditionList.reduce(0) {
switch $1 {
case .expression(let expr):
return $0 + 1 + nPath(forExpression: expr)
case .case(_, let expr):
return $0 + 1 + nPath(forExpression: expr)
case .let(_, let expr):
return $0 + 1 + nPath(forExpression: expr)
case .var(_, let expr):
return $0 + 1 + nPath(forExpression: expr)
default:
return $0 + 1
}
} - 1
}
}
|
apache-2.0
|
0261c4a8851c31c86b21e89b8dca1e06
| 29.126263 | 117 | 0.627326 | 3.981976 | false | false | false | false |
TheTrueTom/TransferCalculator
|
Transfer calculator/NSAnimatedImageView.swift
|
1
|
1205
|
//
// NSAnimatedImageView.swift
// Transfer calculator
//
// Created by Thomas Brichart on 16/02/2016.
// Copyright © 2016 Thomas Brichart. All rights reserved.
//
import Foundation
import Cocoa
class NSAnimatedImageView: NSImageView {
var timer: Timer = Timer()
var interval: TimeInterval = 0.1
var imagesArray: [String] = []
var currentIndex: Int = 0
init(imageList: [String]) {
super.init(frame: NSRect(x: 0, y: 0, width: 25, height: 25))
imagesArray = imageList
if !imagesArray.isEmpty {
self.image = NSImage(named: imagesArray[0])
}
if imagesArray.count > 1 {
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(NSAnimatedImageView.changeImage), userInfo: nil, repeats: true)
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func changeImage() {
currentIndex += 1
if currentIndex >= imagesArray.count {
currentIndex = 0
}
self.image = NSImage(named: imagesArray[currentIndex])
self.needsDisplay = true
}
}
|
mit
|
ab5403d34fb230c3547f884c070460f9
| 24.617021 | 162 | 0.592193 | 4.34657 | false | false | false | false |
madewithray/ray-demo-swift
|
SDKDemo/MainTableViewController.swift
|
1
|
1786
|
//
// MainTableViewController.swift
// SDKDemo
//
// Created by Sean Ooi on 6/11/15.
// Copyright (c) 2015 Yella Inc. All rights reserved.
//
import UIKit
import RaySDK
let notificationRefreshKey = "NotificationRefreshKey"
class MainTableViewController: UITableViewController {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
title = "Ray SDK"
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshView", name: notificationRefreshKey, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func refreshView() {
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appDelegate.items.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let dict = appDelegate.items[indexPath.row]
if let beacon = dict["beacon"] as? RSDKBeacon {
cell.textLabel?.text = "\(beacon.major)-\(beacon.minor)"
cell.detailTextLabel?.text = "RSSI: \(beacon.rssi)"
}
else {
cell.textLabel?.text = "Some beacon"
cell.detailTextLabel?.text = "RSSI: I have no idea"
}
return cell
}
}
|
mit
|
99042e431ac8fb382c1607b5e10ca08b
| 28.766667 | 130 | 0.664614 | 5.045198 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.