repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wmcginty/Shifty | Sources/Shifty/Model/Shift/Shift.swift | 1 | 7491 | //
// Shift.swift
// Shifty
//
// Created by William McGinty on 12/25/17.
//
import UIKit
/// Represents the shift of a single `UIView` object.
public struct Shift: Hashable {
// MARK: - NativeViewRestorationBehavior Subtype
public struct NativeViewRestorationBehavior: OptionSet, Hashable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// The source native view will be restored (and visible) after the shift has completed.
public static let source = NativeViewRestorationBehavior(rawValue: 1 << 0)
/// The destination native view will be restored (and visible) after the shift has completed.
public static let destination = NativeViewRestorationBehavior(rawValue: 1 << 1)
/// Neither native view will be restored (and visible) after the shift has completed.
public static let none: NativeViewRestorationBehavior = []
/// Both native views will be restored (and visible) after the shift has completed.
public static let all: NativeViewRestorationBehavior = [.source, .destination]
}
// MARK: - VisualAnimationBehavior Subtype
public enum VisualAnimationBehavior {
// MARK: - Custom Subtype
public struct Custom {
// MARK: - Typealias
public typealias Handler = (_ replicant: UIView, _ destination: Snapshot) -> Void
// MARK: - Properties
private let preparations: Handler?
private let animations: Handler
// MARK: - Initializers
public init(preparations: Handler? = nil, animations: @escaping Handler) {
self.preparations = preparations
self.animations = animations
}
// MARK: - Interface
func prepare(replicant: UIView, with snapshot: Snapshot) {
preparations?(replicant, snapshot)
}
func animate(replicant: UIView, to snapshot: Snapshot) {
animations(replicant, snapshot)
}
}
/// Any visual differences between the source and destination targets are ignored.
case none
/// Any visual difference between the source and destination `alpha`, `backgroundColor` or `cornerRadius` are automatically animated between along the same timing curve as the shift.
case automatic
/// Allows for completely custom animations to account for visual differences between the source and destination targets.
case custom(Custom)
}
// MARK: - Properties
public let identifier: Shift.Identifier
public let source: Target
public let destination: Target
/// The behavior describing how the native views being replicated are restored to their previous state after the `Shift`. has completed.
public var nativeViewRestorationBehavior: NativeViewRestorationBehavior = .all
/// The behavior describing the way any visual differences between the `source` and `target` are shifted.
public var visualAnimationBehavior: VisualAnimationBehavior = .none
// MARK: - Initializers
public init(identifier: Shift.Identifier, source: Target, destination: Target) {
self.identifier = identifier
self.source = source
self.destination = destination
}
// MARK: - Modification
public var debug: Shift { return Shift(identifier: identifier, source: source.debug, destination: destination.debug) }
public func replicating(using strategy: ReplicationStrategy) -> Shift {
return Shift(identifier: identifier, source: source.replicating(using: strategy), destination: destination.replicating(using: strategy))
}
public func visuallyAnimating(using behavior: VisualAnimationBehavior) -> Shift {
var shift = Shift(identifier: identifier, source: source, destination: destination)
shift.visualAnimationBehavior = behavior
return shift
}
public func visuallyAnimating(using preparations: Shift.VisualAnimationBehavior.Custom.Handler?, animations: @escaping Shift.VisualAnimationBehavior.Custom.Handler) -> Shift {
return visuallyAnimating(using: .custom(VisualAnimationBehavior.Custom(preparations: preparations, animations: animations)))
}
public func restoringNativeViews(using behavior: NativeViewRestorationBehavior) -> Shift {
var shift = Shift(identifier: identifier, source: source, destination: destination)
shift.nativeViewRestorationBehavior = behavior
return shift
}
}
// MARK: - Container Management
public extension Shift {
func configuredReplicant(in container: UIView, with insertionStrategy: Target.ReplicantInsertionStrategy = .standard) -> UIView {
let replicant = source.configuredReplicant(in: container, with: insertionStrategy, afterScreenUpdates: true)
configureNativeViews(hidden: true)
return replicant
}
func layoutDestinationIfNeeded() {
destination.view.superview?.layoutIfNeeded()
}
func preshift(for replicant: UIView, using snapshot: Snapshot?) {
let snap = snapshot ?? destinationSnapshot()
visualShiftPreparations(for: replicant, using: snap)
}
func shift(for replicant: UIView, using snapshot: Snapshot?) {
let snap = snapshot ?? destinationSnapshot()
positionalShift(for: replicant, using: snap)
visualShift(for: replicant, using: snap)
//Execute any alongside animations necessary when shifting from the source to the destination
source.alongsideAnimations?(replicant, destination, snap)
}
}
// MARK: - Helper
extension Shift {
func visualShiftPreparations(for replicant: UIView, using snapshot: Snapshot) {
switch visualAnimationBehavior {
case .custom(let custom): custom.prepare(replicant: replicant, with: snapshot)
default: break
}
}
func visualShift(for replicant: UIView, using snapshot: Snapshot) {
switch visualAnimationBehavior {
case .none: break
case .automatic: snapshot.applyVisualState(to: replicant)
case .custom(let custom): custom.animate(replicant: replicant, to: snapshot)
}
}
func positionalShift(for replicant: UIView, using snapshot: Snapshot) {
snapshot.applyPositionalState(to: replicant)
}
func cleanup(replicant: UIView) {
source.cleanup(replicant: replicant, restoreNativeView: nativeViewRestorationBehavior.contains(.source))
destination.cleanup(replicant: replicant, restoreNativeView: nativeViewRestorationBehavior.contains(.destination))
}
func destinationSnapshot() -> Snapshot {
return destination.snapshot()
}
func configureNativeViews(hidden: Bool) {
[source, destination].forEach { $0.configureNativeView(hidden: hidden) }
}
}
// MARK: - Hashable
extension Shift {
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
hasher.combine(source)
hasher.combine(destination)
}
public static func == (lhs: Shift, rhs: Shift) -> Bool {
return lhs.identifier == rhs.identifier && lhs.source == rhs.source && lhs.destination == rhs.destination
}
}
| mit | 2939c1d29cd9803622286cd504672bfb | 38.634921 | 190 | 0.668269 | 5.007353 | false | false | false | false |
LiuSky/XBKit | Sources/Styles/HeightPalette.swift | 1 | 371 | //
// HeightPalette.swift
// XBKit
//
// Created by xiaobin liu on 2017/3/24.
// Copyright © 2017年 Sky. All rights reserved.
//
import Foundation
import UIKit
/// 高度模版
public enum HeightPalette {
public static let
oneLine = 1/UIScreen.main.scale,
coarseLine = 1,
buttonHeight = 44,
footViewHeight = 50,
textFieldHight = 50
}
| mit | 5a21335643f4299988ef6527a1fe85d0 | 16.142857 | 47 | 0.655556 | 3.333333 | false | false | false | false |
litoarias/SwiftTemplate | TemplateSwift3/Utils/Extensions/UITextField+Border.swift | 1 | 1088 | //
// UITextField+Border.swift
// TemplateSwift3
//
// Created by Hipolito Arias on 13/07/2017.
// Copyright © 2017 Hipolito Arias. All rights reserved.
//
import UIKit
extension UITextField {
func resetTextFieldBorder() {
layer.borderColor = UIColor.pinkishGrey.cgColor
layer.borderWidth = 0.5
}
func highlightTextFieldBorder() {
layer.borderColor = UIColor.tomato.cgColor
layer.borderWidth = 1.0
}
func disable() {
self.alpha = 0.5
self.backgroundColor = UIColor.silver
self.isUserInteractionEnabled = false
}
func enable() {
self.alpha = 1.0
self.backgroundColor = UIColor.white
self.isUserInteractionEnabled = true
}
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
}
}
}
| mit | 7f18a0c3a81075d2a96b31360908a990 | 23.704545 | 172 | 0.624655 | 4.685345 | false | false | false | false |
neonichu/UXCatalog | UICatalog/WebViewController.swift | 1 | 2366 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to use UIWebView.
*/
import UIKit
class WebViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate {
// MARK: Properties
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var addressTextField: UITextField!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureWebView()
loadAddressURL()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
// MARK: Convenience
func loadAddressURL() {
if let requestURL = NSURL(string: addressTextField.text) {
let request = NSURLRequest(URL: requestURL)
webView.loadRequest(request)
}
}
// MARK: Configuration
func configureWebView() {
webView.backgroundColor = UIColor.whiteColor()
webView.scalesPageToFit = true
webView.dataDetectorTypes = .All
}
// MARK: UIWebViewDelegate
func webViewDidStartLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
// Report the error inside the web view.
let localizedErrorMessage = NSLocalizedString("An error occured:", comment: "")
let errorHTML = "<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">\(localizedErrorMessage) \(error.localizedDescription)</div></body></html>"
webView.loadHTMLString(errorHTML, baseURL: nil)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
// MARK: UITextFieldDelegate
/// Dismisses the keyboard when the "Done" button is clicked.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
loadAddressURL()
return true
}
}
| mit | 80bb7ca2759dbaf911a447833265cb89 | 27.481928 | 193 | 0.674704 | 5.642005 | false | false | false | false |
papertigers/MapleBacon | Library/MapleBacon/MapleBaconTests/ImageExtensionTests.swift | 1 | 946 | //
// Copyright (c) 2015 Zalando SE. All rights reserved.
//
import XCTest
import UIKit
@testable import MapleBacon
class ImageExtensionTests: XCTestCase {
func test_whenImageViewRequestImageWithValidURL_thenImageViewHasImage() {
let expectation = expectationWithDescription("Testing Valid imageView extension")
let imageView = UIImageView()
imageView.setImageWithURL(NSURL(string: imageURL)!, completion: {
(imageInstance, _) in
if (imageView.image != nil) {
expectation.fulfill()
}
})
waitForExpectationsWithTimeout(timeout) {
error in
if (error != nil) {
XCTFail("Expectation failed")
}
}
}
func test_whenDataIsEmpty_thenImageWithCachedDataReturnsNilWithoutCrashing() {
let emptyData = NSData()
XCTAssertNil(UIImage.imageWithCachedData(emptyData))
}
}
| mit | 124aa7412f1a13a510335cd9d0ba72af | 26.823529 | 89 | 0.633192 | 5.284916 | false | true | false | false |
csontosgabor/Twitter_Post | Twitter_Post/ModalAnimatorPhoto.swift | 1 | 3362 | //
// ModalAnimatorPhoto.swift
// Transition
//
// Created by Gabor Csontos on 12/22/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import UIKit
public class ModalAnimatorPhoto {
public class func present(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
var toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height)
toViewFrame.size.height = toViewFrame.size.height
toView.frame = toViewFrame
toView.alpha = 0.0
fromView.addSubview(toView)
UIView.animate(
withDuration: 0.2,
animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
toView.alpha = 1.0
}) { (result) -> Void in
completion()
}
}
public class func dismiss(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
//Checking PhotoAutorizationStatus
if PhotoAutorizationStatusCheck() {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
} else {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
public class func dismissOnBottom(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
public class func showOnfullScreen(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
| mit | 0d3fc072ea90840cd59420e323e50709 | 29.008929 | 126 | 0.51205 | 5.218944 | false | false | false | false |
PeeJWeeJ/SwiftyHUD | SwiftyHUD/SwiftyHUD/SwiftyHUD/SwiftyHUDModule/IndefiniteAnimatedView.swift | 1 | 5238 | ////
//// IndefiniteAnimatedView.swift
//// SVProgressHUD
////
//// Created by Paul Fechner on 12/26/15.
//// Copyright © 2015 EmbeddedSources. All rights reserved.
////
//
//let animationDuration = 1.0
//
//let linearCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
//
//let animations = [CABasicAnimation(keyPath: "strokeStart", fromValue: 0.015, toValue: 0.515),
// CABasicAnimation(keyPath: "strokeStart", fromValue: 0.485, toValue: 0.985)]
//
//let animationGroup = CAAnimationGroup(duration: animationDuration, repeatCount: Float.infinity, removedOnCompletion: false, timingFunction: linearCurve,
// animations: animations)
//
//
//class IndefiniteAnimatedView: UIView {
//
// private var indefiniteAnimatedLayer: CAShapeLayer?
//
// override var frame: CGRect {
// didSet {
// if(!CGRectEqualToRect(frame, oldValue)){
// layoutIfSuperviewExists()
// }
// }
// }
//
// var strokeThickness: CGFloat? {
// didSet {
// if let _ = indefiniteAnimatedLayer, thickness = strokeThickness{
// indefiniteAnimatedLayer!.lineWidth = thickness;
// }
// }
// }
//
// var radius: CGFloat?{
// didSet{
// if(radius != oldValue){
// resetIndefiniteAnimatedLayerIfExists()
// }
// }
// }
//
// var strokeColor: UIColor? {
// didSet{
// if let _ = indefiniteAnimatedLayer, color = strokeColor {
// indefiniteAnimatedLayer!.strokeColor = color.CGColor;
// }
// }
// }
//
// var animatedLayer: CAShapeLayer? {
// get{
// if let layer = indefiniteAnimatedLayer {
// return layer
// }
// else{
// return getLayer()
// }
// }
// }
//
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
//
// override init(frame: CGRect) {
// super.init(frame: frame)
// }
//
// override func willMoveToSuperview(newSuperview: UIView?) {
//
// if let _ = newSuperview {
// layoutAnimatedLayer()
// }
// else if let animatedLayer = indefiniteAnimatedLayer{
// animatedLayer.removeFromSuperlayer()
// indefiniteAnimatedLayer = nil
// }
// }
//
// override func sizeThatFits(size: CGSize) -> CGSize {
// if let thickness = self.strokeThickness, rad = self.radius {
// return CGSizeMake((rad + thickness / 2 + 5) * 2, (rad + thickness / 2 + 5) * 2);
// }
//
// return CGSize()
// }
//
// func resetIndefiniteAnimatedLayerIfExists(){
//
// if let layer = indefiniteAnimatedLayer {
// layer.removeFromSuperlayer()
// indefiniteAnimatedLayer = nil
//
// layoutIfSuperviewExists()
// }
// }
//
// func layoutIfSuperviewExists(){
// if let _ = superview {
// self.layoutAnimatedLayer()
// }
// }
//
// func layoutAnimatedLayer() {
//
// if let animationLayer = indefiniteAnimatedLayer {
// self.layer.addSublayer(animationLayer)
//
// let widthDiff = CGRectGetWidth(self.bounds) - CGRectGetWidth(layer.bounds)
// let heightDiff = CGRectGetHeight(self.bounds) - CGRectGetHeight(layer.bounds)
// animationLayer.position = CGPointMake(CGRectGetWidth(self.bounds) - CGRectGetWidth(layer.bounds) / 2 - widthDiff / 2, CGRectGetHeight(self.bounds) - CGRectGetHeight(layer.bounds) / 2 - heightDiff / 2)
// }
// }
//
// func getLayer() -> CAShapeLayer? {
//
// if let (center, rad) = getArcCenter(), thickness = self.strokeThickness, color = strokeColor{
//
// let smoothedPath = getSmoothedPath(center, rad: rad)
// let rect = CGRectMake(0.0, 0.0, center.x * 2, center.y * 2)
//
// let maskLayer = CALayer(contents: (UIImage(contentsOfFile: getImagePath()!)?.CGImage)!, frame: (indefiniteAnimatedLayer?.bounds)!)
//
// indefiniteAnimatedLayer = CAShapeLayer(contentsScale: UIScreen.mainScreen().scale, frame: rect, fillColor: UIColor.clearColor().CGColor, strokeColor: color.CGColor, lineWidth: thickness, lineCap: kCALineCapRound, lineJoin: kCALineJoinBevel, path: smoothedPath.CGPath, mask: maskLayer)
//
// let animation = CABasicAnimation(keyPath: "transform.rotation", fromValue: 0, toValue: M_PI * 2, duration: animationDuration, timingFunction: linearCurve, removedOnCompletion: false, repeatCount: Float.infinity, fillMode: kCAFillModeForwards, autoreverses: false)
//
// indefiniteAnimatedLayer?.mask?.addAnimation(animation, forKey: "rotate")
//
// indefiniteAnimatedLayer?.addAnimation(animationGroup, forKey: "progress")
// }
//
// return indefiniteAnimatedLayer
// }
//
// func getImagePath() -> String? {
//
// let bundle = NSBundle(forClass: self.classForCoder)
// let url = bundle.URLForResource("SVProgressHUD", withExtension: "bundle")
// let imageBundle = NSBundle(URL: url!)
// return imageBundle?.pathForResource("angle-mask", ofType: "png")
// }
//
// func getSmoothedPath(arcCenter: CGPoint, rad: CGFloat) -> UIBezierPath {
//
// return UIBezierPath( arcCenter: arcCenter, radius: rad, startAngle: CGFloat(M_PI * 3 / 2), endAngle: CGFloat(M_PI / 2 + M_PI * 5), clockwise: true)
//
// }
//
// func getArcCenter() -> (CGPoint, CGFloat)? {
//
// if let rad = self.radius, thickness = self.strokeThickness{
// return (CGPointMake(rad + thickness / 2 + 5, rad + thickness / 2 + 5), rad)
// }
// else{
// return nil
// }
// }
//
// func refresh(radius: CGFloat, strokeThickness: CGFloat){
// self.radius = radius
// self.strokeThickness = strokeThickness
// self.sizeToFit()
// }
//}
//
//
//
//
//
| mit | 6059c33dcc642f3de8e19c7144b55d3b | 28.755682 | 289 | 0.678442 | 3.380891 | false | false | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Newfeature/WelcomeViewController.swift | 1 | 1489 | //
// WelcomeViewController.swift
// weibo_wjq
//
// Created by landixing on 2017/5/29.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
import SDWebImage
class WelcomeViewController: UIViewController {
@IBOutlet var avatorImageView: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var iconBottomConstaint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
avatorImageView.layer.cornerRadius = 40
avatorImageView.layer.masksToBounds = true
assert(UserAccount.loadAccount() != nil,"必须授权之后才能显示欢迎界面")
guard let url = URL(string: (UserAccount.loadAccount()?.avatar_large)!) else {
return
}
avatorImageView.sd_setImage(with: url)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
iconBottomConstaint.constant = (UIScreen.main.bounds.height - iconBottomConstaint.constant)
UIView.animate(withDuration: 2.0, animations: {
self.view.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 2.0, animations: { () -> Void in
self.nameLabel.alpha = 1.0
}, completion: { (_) -> Void in
//动画结束,进入欢迎界面
NotificationCenter.default.post(name: Notification.Name(rawValue: SwitchRootViewController), object: true)
})
}
}
}
| apache-2.0 | 65c9b4af0b1d28f3cc2b687cc1ee51a7 | 26.132075 | 119 | 0.631433 | 4.608974 | false | false | false | false |
ontouchstart/swift3-playground | single/say说.playgroundbook/Contents/Chapters/say说.playgroundchapter/Pages/say说.playgroundpage/Contents.swift | 1 | 683 | //#-hidden-code
import UIKit
import AVFoundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let synthesizer = AVSpeechSynthesizer()
func say(_ sentence :String) {
let voice = AVSpeechSynthesisVoice(language: "en-US")
let utterance = AVSpeechUtterance(string: sentence)
utterance.voice = voice
synthesizer.speak(utterance)
}
func 说(_ 话:String) {
let voice = AVSpeechSynthesisVoice(language: "zh-CN")
let utterance = AVSpeechUtterance(string: 话)
utterance.voice = voice
synthesizer.speak(utterance)
}
//#-end-hidden-code
say("Gia is a good girl")
说("刘佳是个好孩子")
say("Thank you")
说("谢谢")
| mit | 11432521778b159b49296980bf72211b | 24.192308 | 57 | 0.732824 | 3.852941 | false | false | false | false |
DAloG/BlueCap | BlueCap/Central/PeripheralAdvertisementsViewController.swift | 1 | 2373 | //
// PeripheralAdvertisements.swift
// BlueCap
//
// Created by Troy Stribling on 6/19/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class PeripheralAdvertisementsViewController : UITableViewController {
weak var peripheral : Peripheral?
var names : Array<String> = []
var values : Array<String> = []
struct MainStoryboard {
static let peripheralAdvertisementCell = "PeripheralAdvertisementCell"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let peripheral = self.peripheral {
self.names = peripheral.advertisements.keys.array
self.values = peripheral.advertisements.values.array
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didResignActive() {
self.navigationController?.popToRootViewControllerAnimated(false)
Logger.debug()
}
func didBecomeActive() {
Logger.debug()
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int {
return self.names.count
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralAdvertisementCell, forIndexPath: indexPath) as! PeripheralAdvertisementCell
cell.nameLabel.text = self.names[indexPath.row]
cell.valueLabel.text = self.values[indexPath.row]
return cell
}
// UITableViewDelegate
// PRIVATE INTERFACE
}
| mit | e471abac922186c3af9583780fb3266e | 30.64 | 163 | 0.687737 | 5.356659 | false | false | false | false |
IC2017/NewsWatch | NewsSeconds/NewsSeconds/AppDelegate.swift | 1 | 15657 | //
// AppDelegate.swift
// NewsSeconds
//
// Created by Anantha Krishnan K G on 02/03/17.
// Copyright © 2017 Ananth. All rights reserved.
//
import UIKit
import BMSPush
import BMSCore
import SwiftMessages
import AVFoundation
import RestKit
import TextToSpeechV1
import UserNotifications
import UserNotificationsUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,AVAudioPlayerDelegate {
//OpenWhisk Credentials
var whiskAccessKey:String = "OpenWhisk Key"
var whiskAccessToken:String = "OpenWhisk token"
var whiskActionName:String = "Swift action name"
var whiskNameSpace:String = "space name"
//Push Service Credentials
var pushAppGUID:String = "Your push appGUID"
var pushAppClientSecret:String = "Your push appSecret"
var pushAppRegion:String = "Your push appregion"
//Watson Text-to-speech credentials
var watsonTextToSpeachUsername:String = "Watson Text to Speech username"
var watsonTextToSpeachPassword:String = "Watson Text to Speech password"
//News API key - From https://newsapi.org/
var newsAPIKey:String = "News Api key"
weak var gameTimer: Timer?
var soundPlayer: AVAudioPlayer?
var audioPlayer = AVAudioPlayer() // see note below
var window: UIWindow?
var urlToOpen:String = UserDefaults.standard.value(forKey: "urlToOpen") != nil ? UserDefaults.standard.value(forKey: "urlToOpen") as! String : ""
var sourceDescription:String = UserDefaults.standard.value(forKey: "sourceDescription") != nil ? UserDefaults.standard.value(forKey: "sourceDescription") as! String : "ABC News"
var source:String = UserDefaults.standard.value(forKey: "sourceValue") != nil ? UserDefaults.standard.value(forKey: "sourceValue") as! String : "abc-news-au"
var sourceID:Int = UserDefaults.standard.value(forKey: "sourceValueID") != nil ? UserDefaults.standard.integer(forKey:"sourceValueID") : 0
var oldSource:String = UserDefaults.standard.value(forKey: "oldSourceValue") != nil ? UserDefaults.standard.value(forKey: "oldSourceValue") as! String :"abc-news-au"
var valueChanged:Bool = false
var doIt = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
doIt = false
if let path = Bundle.main.path(forResource: "bluemixCredentials", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
// use swift dictionary as normal
whiskAccessKey = dict["whiskAccessKey"] as! String;
whiskAccessToken = dict["whiskAccessToken"] as! String;
whiskActionName = dict["whiskActionName"] as! String;
whiskNameSpace = dict["whiskNameSpace"] as! String;
pushAppGUID = dict["pushAppGUID"] as! String;
pushAppClientSecret = dict["pushAppClientSecret"] as! String;
pushAppRegion = dict["pushAppRegion"] as! String;
watsonTextToSpeachUsername = dict["watsonTextToSpeachUsername"] as! String;
watsonTextToSpeachPassword = dict["watsonTextToSpeachPassword"] as! String;
newsAPIKey = dict["newsAPIKey"] as! String;
}
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UserDefaults.standard.set("", forKey: "newsURL")
UserDefaults.standard.synchronize()
urlToOpen = ""
UIApplication.shared.applicationIconBadgeNumber = 0;
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
if (UserDefaults.standard.bool(forKey: "isPushEnabled")){
registerForPush()
}
gameTimer?.invalidate()
let ff = Date()
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year,.month,.weekOfYear,.day,.hour,.minute,.second]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = .full
dateComponentsFormatter.string(from: Date(), to: ff)
return true
}
func registerForPush () {
let myBMSClient = BMSClient.sharedInstance
myBMSClient.initialize(bluemixRegion: pushAppRegion)
let push = BMSPushClient.sharedInstance
push.initializeWithAppGUID(appGUID: pushAppGUID, clientSecret:pushAppClientSecret)
}
func unRegisterPush () {
// MARK: RETRIEVING AVAILABLE SUBSCRIPTIONS
let push = BMSPushClient.sharedInstance
push.unregisterDevice(completionHandler: { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during unregistering device : \(response)")
print( "status code during unregistering device : \(statusCode)")
UIApplication.shared.unregisterForRemoteNotifications()
}
else{
print( "Error during unregistering device \(error) ")
}
})
}
func registerForTag(){
if (UserDefaults.standard.bool(forKey:"isPushEnabled")){
let push = BMSPushClient.sharedInstance
push.unsubscribeFromTags(tagsArray: [self.oldSource]) { (response, status, error) in
if error.isEmpty {
print( "Response during device Unsubscribing : \(response)")
print( "status code during device Unsubscribing : \(status)")
push.subscribeToTags(tagsArray: [self.source]) { (response, status, error) in
if error.isEmpty {
print( "Response during device subscription : \(response)")
print( "status code during device subscription : \(status)")
}
else{
print( "Error during device subscription \(error) ")
}
}
}
else{
print( "Error during Unsubscribing \(error) ")
}
}
}else{
self.showAlert(title: "Error !!!", message: "Enable Push Service",theme: .error)
}
}
func application (_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
let push = BMSPushClient.sharedInstance
push.registerWithDeviceToken(deviceToken: deviceToken) { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during device registration : \(response)")
print( "status code during device registration : \(statusCode)")
push.subscribeToTags(tagsArray: [self.source]) { (response, status, error) in
if error.isEmpty {
print( "Response during device subscription : \(response)")
print( "status code during device subscription : \(status)")
}
else{
print( "Error during device subscription \(error) ")
}
}
}
else{
print( "Error during device registration \(error) ")
}
}
}
//Called if unable to register for APNS.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
let message:String = "Error registering for push notifications: \(error.localizedDescription)" as String
self.showAlert(title: "Registering for notifications", message: message, theme: .warning)
}
func showTimer(date:Date) -> Bool {
while(Date().minutes(from:date) < 1){
print(Date().minutes(from:date))
}
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let payLoad = ((((userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary).value(forKey: "alert") as! NSDictionary).value(forKey: "body") as! String)
self.showAlert(title: "Recieved Push notifications", message: payLoad, theme: .info)
if(UIApplication.shared.applicationState == .active){
print("Will not play the sound")
}else if(UserDefaults.standard.bool(forKey: "isWatsonEnabled")) {
doIt = true
if(showTimer(date: Date()) && doIt){
//Timer.scheduledTimer(withTimeInterval: 10, repeats: false){_ in
let payLoadAlert = (((userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary).value(forKey: "alert") as! NSDictionary)
let respJson = (userInfo as NSDictionary).value(forKey: "payload") as! String
let data = respJson.data(using: String.Encoding.utf8)
let jsonResponse:NSDictionary = try! JSONSerialization.jsonObject(with: data! , options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
let messageValue:String = jsonResponse.value(forKey: "data") as! String
let newsURL:String = jsonResponse.value(forKey: "newsURL") as! String
UserDefaults.standard.set(newsURL, forKey: "newsURL")
UserDefaults.standard.synchronize()
self.urlToOpen = newsURL
let title = "Latest News From \(self.sourceDescription)"
let subtitle = payLoadAlert.value(forKey: "body") as! String;
let alert = messageValue
let watsonMessage = "\(title), \(subtitle), \(alert)"
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.shared.beginReceivingRemoteControlEvents()
let textToSpeech = TextToSpeech(username:watsonTextToSpeachUsername, password: watsonTextToSpeachPassword)
textToSpeech.synthesize(watsonMessage as String, success: { data in
self.audioPlayer = try! AVAudioPlayer(data: data)
self.audioPlayer.prepareToPlay()
//self.audioPlayer.play()
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.body = alert
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "watsonPush", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.delegate = self
center.removeAllPendingNotificationRequests()
center.removeAllDeliveredNotifications()
// self.audioPlayer.play()
completionHandler(UIBackgroundFetchResult.newData)
center.add(request) { (error) in
print("Success")
self.audioPlayer.play()
}
} else {
// Fallback on earlier versions
}
print("should have been added")
})
}
catch {}
}
}
}
func showAlert (title:String , message:String, theme:Theme){
// create the alert
let view = MessageView.viewFromNib(layout: .CardView)
// Theme message elements with the warning style.
view.configureTheme(theme)
var iconText = "😊"
switch theme {
case .error:
iconText = "😱"
break;
case .success:
iconText = "👏"
break;
case .warning:
iconText = "🙄"
break;
case .info:
iconText = "😊"
break;
}
// Add a drop shadow.
view.configureDropShadow()
// Set message title, body, and icon. Here, we're overriding the default warning
// image with an emoji character.
view.configureContent(title: title, body: message, iconText: iconText)
view.button?.isHidden = true
// Show the message.
SwiftMessages.show(view: view)
}
func applicationDidBecomeActive(_ application: UIApplication) {
doIt = false
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if(urlToOpen.isEmpty) == false{
UIApplication.shared.open(URL(string: urlToOpen)!, options: [:], completionHandler: nil)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UserDefaults.standard.set("", forKey: "newsURL")
UserDefaults.standard.synchronize()
urlToOpen = ""
doIt = false
audioPlayer.stop()
UIApplication.shared.applicationIconBadgeNumber = 0;
UIApplication.shared.cancelAllLocalNotifications()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
UIApplication.shared.beginReceivingRemoteControlEvents()
}
}
extension Date {
/// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
/// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
if minutes(from: date) >= 0 { return "\(minutes(from: date))" }
if seconds(from: date) >= 0 { return "\(seconds(from: date))" }
return ""
}
}
| apache-2.0 | 567c2a85db65e136ba46b891478f8695 | 40.269129 | 199 | 0.575347 | 5.642496 | false | false | false | false |
nebhale/CacheCache | CacheCache/InMemoryCache.swift | 1 | 3275 | /*
Copyright 2015 the original author or authors.
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 LoggerLogger
/**
An implementation of `Cache` that persists data in memory. This persistence is not durable across restarts of an application and therefore should not be used as a production caching mechanism.
*/
public final class InMemoryCache<T>: Cache {
public typealias Deserializer = Any -> T?
public typealias Serializer = T -> Any
private var cache: Any?
private let logger = Logger()
private let type: String
/**
Creates a new instance of `InMemoryCache`
- parameter type: A user-readable representation of the type being cached
*/
public init(type: String) {
self.type = type
}
/**
Creates a new instance of `InMemoryCache`
- parameter type: Type being cached
*/
convenience public init(type: T.Type) {
self.init(type: "\(type)")
}
/**
Persists a payload for later retrieval
- parameter payload: The payload to persist
- parameter serializer: The serializer to use to map the payload into cached data. Will only be called if the payload is non-`nil`. The default is an *identity* implementation that makes no changes to the payload.
*/
public func persist(payload: T?, serializer serialize: Serializer = InMemoryCache.identitySerializer) {
guard let payload = payload else {
self.logger.warn("Did not persist \(self.type) payload")
return
}
self.logger.info("Persisting \(self.type) payload")
self.cache = serialize(payload)
self.logger.debug("Persisted \(self.type) payload")
}
/**
Retrieves a payload from an earlier persistence. If `persist()` has never been called, then it will always return `nil`.
- parameter deserializer: The deserializer to use to mapt the cached data into the payload. Will only be called if the cached data is non-`nil`. The default is an *identity* implementation that makes no changes to the payload.
- returns: The payload if one has been persisted and it can be properly deserialized
*/
public func retrieve(deserializer deserialize: Deserializer = InMemoryCache.identityDeserializer) -> T? {
guard let cache = self.cache else {
self.logger.warn("Did not retrieve \(self.type) payload")
return nil
}
self.logger.info("Retrieving \(self.type) payload")
let payload = deserialize(cache)
self.logger.debug("Retrieved \(self.type) payload")
return payload
}
private static func identityDeserializer(cache: Any) -> T? {
return cache as? T
}
private static func identitySerializer(payload: T) -> Any {
return payload
}
} | apache-2.0 | 337edd624127f975d526da386d4e39fb | 33.125 | 232 | 0.690076 | 4.599719 | false | false | false | false |
phimage/SLF4Swift | Backend/CocoaLumberJack/CocoaLumberJack.swift | 1 | 4002 | //
// CocoaLumberJack.swift
// SLF4Swift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
#if EXTERNAL
import SLF4Swift
#endif
import CocoaLumberjack
/* Log with SwiftLogMacro from CocoaLumberjack */
open class CocoaLumberjackMacroLogger: LoggerType {
open class var instance = CocoaLumberjackMacroLogger()
open var level: SLFLogLevel {
get {
return CocoaLumberjackMacroLogger.toLevel(defaultDebugLevel)
}
set {
defaultDebugLevel = CocoaLumberjackMacroLogger.fromLevel(newValue)
}
}
open var name: LoggerKeyType = "macro"
open var isAsynchronous = true
open func info(_ message: LogMessageType) {
DDLogInfo(message, asynchronous: isAsynchronous)
}
open func error(_ message: LogMessageType) {
DDLogError(message, asynchronous: isAsynchronous)
}
open func severe(_ message: LogMessageType) {
error(message) // no fatal or severe level
}
open func warn(_ message: LogMessageType) {
DDLogWarn(message, asynchronous: isAsynchronous)
}
open func debug(_ message: LogMessageType) {
DDLogDebug(message, asynchronous: isAsynchronous)
}
open func verbose(_ message: LogMessageType) {
DDLogVerbose(message, asynchronous: isAsynchronous)
}
open func log(_ level: SLFLogLevel,_ message: LogMessageType) {
SwiftLogMacro(self.isAsynchronous, level: defaultDebugLevel, flag: DDLogFlag.fromLogLevel(CocoaLumberjackMacroLogger.fromLevel(level)), string: message)
}
open func isLoggable(_ level: SLFLogLevel) -> Bool {
return level <= self.level
}
open static func toLevel(_ level:DDLogLevel) -> SLFLogLevel {
switch(level){
case .Off: return SLFLogLevel.Off
case .Error: return SLFLogLevel.Error
case .Warning: return SLFLogLevel.Warn
case .Info: return SLFLogLevel.Info
case .Debug: return SLFLogLevel.Debug
case .Verbose: return SLFLogLevel.Verbose
case .All: return SLFLogLevel.Off
}
}
open static func fromLevel(_ level:SLFLogLevel) -> DDLogLevel {
switch(level){
case .Off: return DDLogLevel.Off
case .Severe: return DDLogLevel.Error
case .Error: return DDLogLevel.Error
case .Warn: return DDLogLevel.Warning
case .Info: return DDLogLevel.Info
case .Debug: return DDLogLevel.Debug
case .Verbose: return DDLogLevel.Verbose
case .All: return DDLogLevel.Off
}
}
}
open class CocoaLumberjackMacroLoggerFactory: SingleLoggerFactory {
open class var instance = CocoaLumberjackMacroLoggerFactory()
public init(logger: CocoaLumberjackMacroLogger = CocoaLumberjackMacroLogger.instance) {
super.init(logger: logger)
}
open override func removeAllLoggers() {
// DDLog.removeAllLoggers()
}
}
| mit | f4e9f901e3a43667e4960dfe6ec4a9b2 | 33.5 | 160 | 0.704398 | 4.686183 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Foundation/DesignPatterns/DesignPatterns/Render Tree/UIView.swift | 1 | 553 | //
// UIView.swift
// DesignPatterns
//
// Created by 朱双泉 on 2018/4/21.
// Copyright © 2018 Castie!. All rights reserved.
//
import CoreGraphics
class UIView {
var _origin: CGPoint
var _size: CGSize
static var head: UIView?
var next: UIView?
func description() {}
init(_ origin: CGPoint, _ size: CGSize) {
_origin = origin
_size = size
}
static func renderTreeList() {
var t = head
while t != nil {
t?.description()
t = t?.next
}
}
}
| mit | 11cfa4701e5c85491a910a9e1582be69 | 17.2 | 50 | 0.53663 | 3.84507 | false | false | false | false |
jiangboLee/huangpian | liubai/Camera/View/AllPhotoesFlowLayout.swift | 1 | 665 | //
// AllPhotoesFlowLayout.swift
// liubai
//
// Created by 李江波 on 2017/3/23.
// Copyright © 2017年 lijiangbo. All rights reserved.
//
import UIKit
class AllPhotoesFlowLayout: UICollectionViewFlowLayout {
let margin: CGFloat = 3
override init() {
super.init()
let itemW = (SCREENW - 2 * margin) / 3
let itemH = itemW
itemSize = CGSize(width: itemW, height: itemH)
scrollDirection = .vertical
minimumLineSpacing = margin
minimumInteritemSpacing = margin
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | fec6af699cd885c8bee7148bfe32c0b2 | 22.428571 | 59 | 0.626524 | 4.232258 | false | false | false | false |
ragnar/VindsidenApp | version.swift | 1 | 2249 | #!/usr/bin/swift
import Foundation
enum ExitCodes : Int32 {
case Success = 0, Failure = 1
}
func runAgvtool( arguments: [String]! ) -> (Bool, Int32) {
let task = Process()
task.launchPath = "/usr/bin/agvtool"
task.arguments = arguments
task.launch()
task.waitUntilExit()
if task.terminationStatus == ExitCodes.Success.rawValue {
return (true, task.terminationStatus)
} else {
return (false, task.terminationStatus)
}
}
func showHelp( errorMessage: String = "" ) -> Void {
let name = (CommandLine.arguments.first! as String)
if errorMessage.isEmpty == false {
print("\(errorMessage)")
}
print("\n\(name) - Convenience program to simplify setting version and bumping build numbers")
print("\n usage:")
print("\t\(name) help")
print("\t\(name) bump-build")
print("\t\(name) set-build <build number>")
print("\t\(name) set-version <version>")
print("\t\(name) print-current")
print("\n")
}
if CommandLine.arguments.count <= 1 {
showHelp()
exit(ExitCodes.Failure.rawValue)
}
let command = CommandLine.arguments[1]
var arguments: [String]
switch ( command.lowercased() ) {
case "bump-build":
arguments = ["bump", "-all"]
case "set-build":
if CommandLine.arguments.count >= 3 {
let buildNumber = CommandLine.arguments[2]
arguments = ["new-version", "-all", buildNumber]
} else {
showHelp(errorMessage: "Missing <build number> parameter.")
exit(ExitCodes.Failure.rawValue)
}
case "set-version":
if CommandLine.arguments.count >= 3 {
let version = CommandLine.arguments[2]
arguments = ["new-marketing-version", version]
} else {
showHelp(errorMessage: "Missing <version> parameter.")
exit(ExitCodes.Failure.rawValue)
}
case "print-current":
let _ = runAgvtool( arguments: ["mvers"] )
let _ = runAgvtool( arguments: ["vers"] )
exit(ExitCodes.Success.rawValue)
case "help":
showHelp()
exit(ExitCodes.Failure.rawValue)
default:
showHelp(errorMessage: "Unrecognized operation specifier \"\(command)\".")
exit(ExitCodes.Failure.rawValue)
}
let (status, exitCode) = runAgvtool( arguments: arguments)
exit(exitCode)
| bsd-2-clause | 641df812a8ec6e1e0214093e55ba3de5 | 25.458824 | 98 | 0.645176 | 3.805415 | false | false | false | false |
srn214/Floral | Floral/Pods/Then/Sources/Then/Then.swift | 1 | 2685 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit.UIGeometry
#endif
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing and copying the value types.
///
/// let frame = CGRect().with {
/// $0.origin.x = 10
/// $0.size.width = 100
/// }
public func with(_ block: (inout Self) throws -> Void) rethrows -> Self {
var copy = self
try block(©)
return copy
}
/// Makes it available to execute something with closures.
///
/// UserDefaults.standard.do {
/// $0.set("devxoul", forKey: "username")
/// $0.set("[email protected]", forKey: "email")
/// $0.synchronize()
/// }
public func `do`(_ block: (Self) throws -> Void) rethrows {
try block(self)
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .center
/// $0.textColor = UIColor.black
/// $0.text = "Hello, World!"
/// }
public func then(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
}
extension NSObject: Then {}
extension CGPoint: Then {}
extension CGRect: Then {}
extension CGSize: Then {}
extension CGVector: Then {}
#if os(iOS) || os(tvOS)
extension UIEdgeInsets: Then {}
extension UIOffset: Then {}
extension UIRectEdge: Then {}
#endif
| mit | ea3fa6d80c75f14546bf2c0f4ab2f350 | 30.588235 | 109 | 0.674115 | 4.086758 | false | false | false | false |
BasThomas/Sombrero | SombreroKit/Quantity.swift | 1 | 1794 | //
// Quantity.swift
// Sombrero
//
// Created by Bas Broek on 26/04/15.
// Copyright (c) 2015 Bas Broek. All rights reserved.
//
import Foundation
// MARK: - Quantity
/// Holds the quantity of the ingredient
public struct Quantity {
/// The amount of the quantity.
public var amount: Double
/// The type of the quantity.
public var type: QuantityType
/**
The designated initializer.
:param: amount The amount of the quantity.
:param: type The type of the quantity.
*/
public init(amount: Double, type: QuantityType) {
self.amount = amount
self.type = type
}
}
// MARK: - Hashable
extension Quantity: Hashable {
/// The hash value.
public var hashValue: Int {
return amount.hashValue ^ type.hashValue
}
}
public func ==(lhs: Quantity, rhs: Quantity) -> Bool {
return lhs.amount == rhs.amount && lhs.type == rhs.type
}
public func +=(lhs: Quantity, rhs: Quantity) -> Double {
return lhs.amount + rhs.amount
}
public func -=(lhs: Quantity, rhs: Quantity) -> Double? {
let updatedAmount = lhs.amount - rhs.amount
return (updatedAmount) >= 0 ? updatedAmount : nil
}
// MARK: - Printable
extension Quantity: Printable {
/// A textual representation of `self`.
public var description: String {
return " ".join(["\(self.amount)", "\(self.type)"])
}
}
// MARK: - QuantityType
/// Holds the quantity-type of the ingredient.
public enum QuantityType: String {
case Weight = "Weight"
case Spoon = "Spoon"
case None = ""
}
// MARK: - Printable
extension QuantityType: Printable {
/// A textual representation of `self`.
public var description: String {
return self.rawValue
}
} | mit | f2e124fa154ed38f2fec51274d4b0166 | 20.369048 | 59 | 0.615942 | 4.022422 | false | false | false | false |
sochalewski/TinySwift | Example/Tests/FloatingPointTests.swift | 1 | 938 | //
// FloatingPointTests.swift
// TinySwift
//
// Created by Piotr Sochalewski on 28.10.2016.
// Copyright © 2016 Piotr Sochalewski. All rights reserved.
//
import XCTest
class FloatingPointTests: XCTestCase {
private let zero = 0.0
private let five = 5.0
private let minusFive = -5.0
func testAdditiveInverse() {
XCTAssertTrue(zero.additiveInverse == 0)
XCTAssertTrue(five.additiveInverse == minusFive)
XCTAssertTrue(minusFive.additiveInverse == five)
}
func testMultiplicativeInverse() {
XCTAssertNil(zero.multiplicativeInverse)
XCTAssertTrue(five.multiplicativeInverse == 0.2)
XCTAssertTrue(minusFive.multiplicativeInverse == -0.2)
}
func testAngles() {
let fiveDegToRad = five.degreesToRadians
XCTAssertEqual(fiveDegToRad, 0.087, accuracy: 0.01)
XCTAssert(fiveDegToRad.radiansToDegrees == five)
}
}
| mit | 6f4bcc8b2bb77e251c39b3037e17cef0 | 26.558824 | 62 | 0.673426 | 4.183036 | false | true | false | false |
abhibeckert/Tacho | Tacho/TachView.swift | 1 | 7440 | //
// TachView.swift
// Tacho
//
// Created by Abhi Beckert on 15/08/2014.
//
// This is free and unencumbered software released into the public domain.
// See unlicense.org
//
import UIKit
import QuartzCore
import CoreText
class TachView: UIView
{
var currentRPM: CGFloat = 0
var stalled: Bool = false
var pitSpeedLimiter = false
var revLimiter = false
var recentMaxRPM: CGFloat = 0
let tachMinStrokeStart: CGFloat = 0.52
let tachMaxStrokeEnd: CGFloat = 0.745
let tachBackgroundLayer = CAShapeLayer()
let tachLayer = CAShapeLayer()
let tachRecentMaxLayer = CAShapeLayer()
let tachCutoutLayer = CAShapeLayer()
let tachBackgroundColor = UIColor(white: 0.2, alpha: 1.0).CGColor
let lowRPMColor = UIColor.whiteColor().CGColor
let midRPMColor = UIColor.cyanColor().CGColor
let highRPMColor = UIColor.yellowColor().CGColor
let shiftNowColor = UIColor.greenColor().CGColor
let limiterColor = UIColor.redColor().CGColor
let limiterAltColor = UIColor.blackColor().CGColor
let pitLimiterColor = UIColor.orangeColor().CGColor
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.contentsScale = 2.0
self.isAccessibilityElement = true
}
required init(coder decoder: NSCoder) {
super.init(coder: decoder)
self.layer.contentsScale = 2.0
self.isAccessibilityElement = true
}
func createLayers()
{
self.backgroundColor = UIColor.blackColor()
let tachPath = UIBezierPath(ovalInRect: CGRect(x: 40, y: self.bounds.size.height * 0.2, width: self.bounds.width * 1.85, height: self.bounds.height * 0.9))
let tachCutoutPath = UIBezierPath(ovalInRect: CGRect(x: 0 - 80, y: (self.bounds.size.height * 0.2) + 35, width: self.bounds.width * 2.3, height: self.bounds.height * 0.9))
tachBackgroundLayer.contentsScale = 2.0
tachBackgroundLayer.path = tachPath.CGPath
tachBackgroundLayer.strokeColor = self.tachBackgroundColor
tachBackgroundLayer.fillColor = UIColor.clearColor().CGColor
tachBackgroundLayer.lineWidth = 75
tachBackgroundLayer.strokeStart = tachMinStrokeStart
tachBackgroundLayer.strokeEnd = tachMaxStrokeEnd
self.layer.addSublayer(tachBackgroundLayer)
tachLayer.path = tachPath.CGPath
tachLayer.contentsScale = 2.0
if (currentRPM < shiftGreenMinRPM) {
tachLayer.strokeColor = self.lowRPMColor
} else if (currentRPM < shiftRedMinRPM) {
tachLayer.strokeColor = self.midRPMColor
} else if (currentRPM < shiftBlueMinRPM) {
tachLayer.strokeColor = self.highRPMColor
} else {
tachLayer.strokeColor = self.shiftNowColor
}
tachLayer.fillColor = UIColor.clearColor().CGColor
tachLayer.lineWidth = 75
tachLayer.strokeStart = tachMinStrokeStart
tachLayer.strokeEnd = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / currentRPM))
self.layer.addSublayer(tachLayer)
tachRecentMaxLayer.contentsScale = 2.0
tachRecentMaxLayer.path = tachPath.CGPath
if (recentMaxRPM < shiftGreenMinRPM) {
tachRecentMaxLayer.strokeColor = self.lowRPMColor
} else if (recentMaxRPM < shiftRedMinRPM) {
tachRecentMaxLayer.strokeColor = UIColor.cyanColor().CGColor
} else if (recentMaxRPM < shiftBlueMinRPM) {
tachRecentMaxLayer.strokeColor = self.highRPMColor
} else {
tachRecentMaxLayer.strokeColor = self.shiftNowColor
}
tachRecentMaxLayer.fillColor = UIColor.clearColor().CGColor
tachRecentMaxLayer.lineWidth = 75
tachRecentMaxLayer.strokeStart = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / recentMaxRPM)) - ((tachMaxStrokeEnd - tachMinStrokeStart) * 0.0017)
tachRecentMaxLayer.strokeEnd = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / recentMaxRPM)) + ((tachMaxStrokeEnd - tachMinStrokeStart) * 0.0017)
self.layer.addSublayer(tachRecentMaxLayer)
tachCutoutLayer.contentsScale = 2.0
tachCutoutLayer.path = tachCutoutPath.CGPath
tachCutoutLayer.fillColor = UIColor.blackColor().CGColor
self.layer.addSublayer(tachCutoutLayer)
}
func updateLayers()
{
CATransaction.begin()
if (!animateTachChanges) {
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
} else {
CATransaction.setAnimationDuration(1.0 / 5)
}
let tachPath = UIBezierPath(ovalInRect: CGRect(x: 40, y: (self.bounds.size.height * 0.2) + 5, width: self.bounds.width * 1.85, height: self.bounds.height * 0.9))
let tachCutoutPath = UIBezierPath(ovalInRect: CGRect(x: 0 - 80, y: (self.bounds.size.height * 0.2) + 35, width: self.bounds.width * 2.3, height: self.bounds.height * 0.9))
tachBackgroundLayer.path = tachPath.CGPath
tachLayer.path = tachPath.CGPath
tachLayer.strokeEnd = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / currentRPM))
if self.pitSpeedLimiter {
if round(NSDate.timeIntervalSinceReferenceDate() * 4) % 2 == 0 {
tachBackgroundLayer.strokeColor = self.pitLimiterColor
} else {
tachBackgroundLayer.strokeColor = self.tachBackgroundColor
}
} else {
tachBackgroundLayer.strokeColor = self.tachBackgroundColor
}
if (self.stalled) {
tachLayer.strokeColor = UIColor.clearColor().CGColor
} else if (self.revLimiter && !self.pitSpeedLimiter) {
if round(NSDate.timeIntervalSinceReferenceDate() * 12) % 2 == 0 {
tachLayer.strokeColor = self.limiterColor
} else {
tachLayer.strokeColor = self.limiterAltColor
}
} else if (currentRPM < shiftGreenMinRPM) {
tachLayer.strokeColor = self.lowRPMColor
} else if (currentRPM < shiftRedMinRPM) {
tachLayer.strokeColor = self.midRPMColor
} else if (currentRPM < shiftBlueMinRPM) {
tachLayer.strokeColor = self.highRPMColor
} else if (currentRPM <= maxRPM) {
tachLayer.strokeColor = self.shiftNowColor
} else {
if (round(NSDate.timeIntervalSinceReferenceDate() * 12) % 2 == 0) {
tachLayer.strokeColor = self.limiterColor
} else {
tachLayer.strokeColor = self.limiterAltColor
}
}
if fabs(recentMaxRPM - currentRPM) < 0.1 {
tachRecentMaxLayer.opacity = 0
} else {
tachRecentMaxLayer.opacity = 1
tachRecentMaxLayer.path = tachPath.CGPath
if (recentMaxRPM < shiftGreenMinRPM) {
tachRecentMaxLayer.strokeColor = self.lowRPMColor
} else if (recentMaxRPM < shiftRedMinRPM) {
tachRecentMaxLayer.strokeColor = self.midRPMColor
} else if (recentMaxRPM < shiftBlueMinRPM) {
tachRecentMaxLayer.strokeColor = self.highRPMColor
} else {
tachRecentMaxLayer.strokeColor = self.shiftNowColor
}
tachRecentMaxLayer.strokeStart = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / recentMaxRPM)) - ((tachMaxStrokeEnd - tachMinStrokeStart) * 0.0017)
tachRecentMaxLayer.strokeEnd = tachMinStrokeStart + ((tachMaxStrokeEnd - tachMinStrokeStart) / (maxRPM / recentMaxRPM)) + ((tachMaxStrokeEnd - tachMinStrokeStart) * 0.0017)
}
tachCutoutLayer.path = tachCutoutPath.CGPath
CATransaction.commit()
}
func accessibilityLabel() -> String
{
let rpm: Int = Int(self.currentRPM)
return "\(rpm)"
}
}
| unlicense | 4a7168d9cdac599f90dd0de42f6c183c | 34.769231 | 180 | 0.699059 | 3.807574 | false | false | false | false |
griotspeak/PathMath | MyPlayground.playground/Pages/N-Gon.xcplaygroundpage/Contents.swift | 1 | 4674 | import QuartzCore
import PathMath
struct RegularPolygonDescription {
typealias FloatValue = CGFloat
let circumradius: FloatValue
let n: Int
init?(n: Int, radius: FloatValue = 1) {
guard n > 2 else { return nil }
self.n = n
circumradius = radius
}
}
extension RegularPolygonDescription: CustomStringConvertible {
var description: String {
let name: String
switch n {
case Int.min ..< 3:
fatalError("polygon with \(n) sides is invalid")
// case 1:
// name = "Regular monogon"
// case 2:
// name = "Regular digon"
case 3:
name = "Regular triangle"
case 4:
name = "Square"
case 5:
name = "Regular pentagon"
case 6:
name = "Regular hexagon"
case 7:
name = "Regular septagon"
case 8:
name = "Regular octagon"
case 9:
name = "Regular nonagon"
case 10:
name = "Regular decagon"
case 11:
name = "Regular hendecagon"
case 12:
name = "Regular dodecagon"
case 13:
name = "Regular tridecagon"
case 14:
name = "Regular tetradecagon"
case 15:
name = "Regular pentadecagon"
case 16:
name = "Regular hexadecagon"
case let value:
name = "Regular \(value)-gon"
}
return "\(name): r = \(circumradius)"
}
}
extension RegularPolygonDescription {
var incentralSliceAngle: FloatValue {
/* TODO: use `exactly` 2017-06-02 */
360 / FloatValue(n)
}
var something: FloatValue {
(180 - incentralSliceAngle) / 2
}
// var apothem: FloatValue {
// cen
// }
}
let triangle = RegularPolygonDescription(n: 3)!
triangle.incentralSliceAngle == 120
// MARK: - Isosceles Triangles
public struct IsoscelesTriangleDescription {
public typealias FloatValue = CGFloat
public let legLength: FloatValue
public let baseLength: FloatValue
public let axisOfSymmetryLength: FloatValue
public let vertexAngle: FloatValue
public let baseAngle: FloatValue
private init(legLength: FloatValue,
baseLength: FloatValue,
axisOfSymmetryLength: FloatValue,
vertexAngle: FloatValue,
baseAngle: FloatValue) {
self.legLength = legLength
self.baseLength = baseLength
self.axisOfSymmetryLength = axisOfSymmetryLength
self.vertexAngle = vertexAngle
self.baseAngle = baseAngle
}
}
extension IsoscelesTriangleDescription {
public init(vertexAngle: FloatValue, legLenth: FloatValue) {
guard vertexAngle > 0,
vertexAngle < 180 else {
fatalError("invalid vertex angle")
}
let halfVertex: Angle = .degrees(vertexAngle * 0.5)
self.vertexAngle = vertexAngle
baseAngle = (180 - vertexAngle) / 2
legLength = legLenth
baseLength = sin(halfVertex.inRadians) * legLenth * 2
axisOfSymmetryLength = cos(halfVertex.inRadians) * legLenth * 2
}
public init(baseAngle: FloatValue, legLenth: FloatValue) {
guard baseAngle > 0,
baseAngle < 90 else {
fatalError("invalid base angle")
}
let vertex = 180 - (baseAngle * 2)
let halfVertex: Angle = .degrees(vertex * 0.5)
self.baseAngle = baseAngle
vertexAngle = vertex
legLength = legLenth
baseLength = sin(halfVertex.inRadians) * legLenth * 2
axisOfSymmetryLength = cos(halfVertex.inRadians) * legLenth * 2
}
public init?(baseLength: FloatValue, legLength: FloatValue) {
guard legLength > 0,
baseLength > 0,
legLength * 2 < baseLength else {
return nil
}
let halfBase = baseLength / 2
let axisLength = sqrt(pow(legLength, 2) - pow(halfBase, 2))
let vertex = asin(halfBase / axisLength) * 2
self.baseLength = baseLength
self.legLength = legLength
baseAngle = (180 - vertex) / 2
vertexAngle = vertex
axisOfSymmetryLength = axisLength
}
}
let isoTri = IsoscelesTriangleDescription(vertexAngle: 90, legLenth: 1)
isoTri.baseLength
isoTri.baseAngle
sqrt(2)
let equTri = IsoscelesTriangleDescription(baseAngle: 60, legLenth: 1)
equTri.legLength
equTri.vertexAngle
let oneOneRootTwo = RightTriangle(lengthA: 1,
lengthB: 1)
oneOneRootTwo.angleA.inDegrees
| mit | 502390fa5eac57768192a67857ea655d | 26.988024 | 71 | 0.587291 | 4.268493 | false | false | false | false |
bizz84/MVPhotosLoader | MVPhotosLoader/MVPhotosLoader.swift | 1 | 5721 | //
// MVPhotosLoader.swift
// MVPhotosLoader
//
// Created by Andrea Bizzotto on 06/03/2016.
// Copyright © 2016 musevisions. All rights reserved.
//
import UIKit
import Photos
open class MVPhotosLoader: NSObject {
open class func addPhotos(_ sourceData: [String: AnyObject], completion: @escaping (_ error: Error?) -> ()) {
let sourcesMetadata = buildMetadata(sourceData)
updateAlbums(sourcesMetadata, completion: completion)
}
fileprivate class func buildMetadata(_ sourceData: [String: AnyObject]) -> [ MVAssetSourceMetadata ] {
guard let assets = sourceData["assets"] as? [ [String : AnyObject] ] else {
return []
}
return assets.compactMap{ MVAssetSourceMetadata(json: $0) }
}
fileprivate class func updateAlbums(_ sourcesMetadata: [MVAssetSourceMetadata], completion: @escaping (_ error: Error?) -> ()) {
let userAssetCollections = fetchTopLevelUserCollections()
addMissingAlbums(sourcesMetadata, existingAlbums: userAssetCollections) { assetCollections, error in
if let error = error {
print("Error adding missing albums: \(error)")
}
insertAssets(sourcesMetadata, assetCollections: assetCollections, completion:completion)
}
}
fileprivate class func addMissingAlbums(_ assetSources: [MVAssetSourceMetadata], existingAlbums: [PHAssetCollection], completion: @escaping (_ assetCollections: [PHAssetCollection], _ error: Error?) -> ()) {
let missingNames = missingAlbumNames(assetSources, assetCollections: existingAlbums)
if missingNames.count > 0 {
PHPhotoLibrary.shared().performChanges({
let _ = createAlbums(names: missingNames)
}) { success, error in
let userAssetCollections = fetchTopLevelUserCollections()
completion(userAssetCollections, error)
}
}
else {
completion(existingAlbums, nil)
}
}
fileprivate class func insertAssets(_ assetSources: [MVAssetSourceMetadata], assetCollections: [PHAssetCollection], completion: @escaping (_ error: Error?) -> ()) {
PHPhotoLibrary.shared().performChanges({
for assetSource in assetSources {
insertAsset(assetSource, inAssetCollections: assetCollections)
}
}) { success, error in
completion(error)
}
}
fileprivate class func missingAlbumNames(_ sourcesMetadata: [MVAssetSourceMetadata], assetCollections: [PHAssetCollection]) -> [String] {
let targetAlbumNames = Set(sourcesMetadata.flatMap { $0.albums })
let existingAlbumNames = assetCollections.compactMap{ $0.localizedTitle }
var missingAlbumNames: [String] = []
for name in targetAlbumNames {
if !existingAlbumNames.contains(name) {
missingAlbumNames.append(name)
}
}
return missingAlbumNames
}
class func createAlbums(names: [String]) -> [PHAssetCollectionChangeRequest] {
return names.map { PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: $0) }
}
fileprivate class func insertAsset(_ metadata: MVAssetSourceMetadata, inAssetCollections assetCollections: [PHAssetCollection]) {
guard let changeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: metadata.fileURL as URL) else {
return
}
changeRequest.isFavorite = metadata.favorite
let filteredAssetCollections = filterAssetCollections(assetCollections, forAlbumsInMetadata: metadata)
if let placeholder = changeRequest.placeholderForCreatedAsset {
for assetCollection in filteredAssetCollections {
if let assetCollectionChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection) {
assetCollectionChangeRequest.addAssets(NSArray(array: [ placeholder ]))
}
}
}
}
class func filterAssetCollections(_ userCollections: [PHAssetCollection], forAlbumsInMetadata metadata: MVAssetSourceMetadata) -> [PHAssetCollection] {
return userCollections.filter {
return $0.localizedTitle != nil ? metadata.albums.contains($0.localizedTitle!) : false
}
}
}
extension MVPhotosLoader {
fileprivate class func fetchSmartAlbum(_ subtype: PHAssetCollectionSubtype) -> PHAssetCollection? {
let fetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subtype, options: nil)
return fetchResult.firstObject
}
fileprivate class func fetchTopLevelUserCollections() -> [PHAssetCollection] {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "localizedTitle", ascending: true)]
let fetchResult = PHCollectionList.fetchTopLevelUserCollections(with: fetchOptions)
var collections: [PHAssetCollection] = []
fetchResult.enumerateObjects({ object, index, pointer in
if let collection = object as? PHAssetCollection {
collections.append(collection)
}
})
return collections
}
}
| mit | f1a9c6428603330a2719714efb8e27f7 | 34.52795 | 211 | 0.619755 | 5.836735 | false | false | false | false |
xiongxiong/ActionCell | framework/ActionCell/ActionCell.swift | 1 | 36764 | //
// ActionCell.swift
// ActionCell
//
// Created by 王继荣 on 27/12/16.
// Copyright © 2016 WonderBear. All rights reserved.
//
import UIKit
public protocol ActionCellDelegate: NSObjectProtocol {
var tableView: UITableView! { get }
var navigationController: UINavigationController? { get }
/// Do something when action is triggered
func didActionTriggered(cell: UITableViewCell, action: String)
}
extension ActionCellDelegate {
/// Close other cell's actionsheet before open own actionsheet
func closeActionsheet() {
tableView.visibleCells.forEach { (cell) in
cell.subviews.forEach({ (view) in
if let wrapper = view as? ActionCell {
wrapper.closeActionsheet()
}
})
}
}
}
open class ActionCell: UIView {
// MARK: ActionCell - 动作设置
/// ActionCellDelegate
public weak var delegate: ActionCellDelegate? = nil
// MARK: ActionCell - 行为设置
/// Enable default action to be triggered when the content is panned to far enough
public var enableDefaultAction: Bool = true
/// The propotion of (state public to state trigger-prepare / state public to state trigger), about where the default action is triggered
public var defaultActionTriggerPropotion: CGFloat = 0.3 {
willSet {
guard newValue > 0.1 && newValue < 0.5 else {
fatalError("defaultActionTriggerPropotion -- value out of range, value must between 0.1 and 0.5")
}
}
}
// MARK: ActionCell - 动画设置
/// Action 动画形式
public var animationStyle: ActionsheetOpenStyle = .concurrent
/// Spring animation - duration of the animation
public var animationDuration: TimeInterval = 0.3
// MARK: ActionCell - 私有属性
/// cell
weak var cell: UITableViewCell?
/// actionsheet - Left
var actionsheetLeft: Actionsheet = Actionsheet(side: .left)
/// actionsheet - Right
var actionsheetRight: Actionsheet = Actionsheet(side: .right)
/// swipeLeftGestureRecognizer
var swipeLeftGestureRecognizer: UISwipeGestureRecognizer!
/// swipeRightGestureRecognizer
var swipeRightGestureRecognizer: UISwipeGestureRecognizer!
/// panGestureRecognizer
var panGestureRecognizer: UIPanGestureRecognizer!
/// tapGestureRecognizer
var tapGestureRecognizer: UITapGestureRecognizer!
/// tempTapGestureRecognizer
var tempTapGestureRecognizer: UITapGestureRecognizer!
/// Screenshot of the cell
var contentScreenshot: UIImageView?
/// Current actionsheet
var currentActionsheet: Actionsheet?
/// The default action to trigger when content is panned to the far side.
var defaultAction: ActionControl?
/// The default action is triggered or not
var isDefaultActionTriggered: Bool = false
/// Actionsheet opened or not
open var isActionsheetOpened: Bool {
return currentActionsheet != nil
}
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
swipeLeftGestureRecognizer = {
let the = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGestureRecognizer(_:)))
the.delegate = self
the.direction = .left
return the
}()
swipeRightGestureRecognizer = {
let the = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGestureRecognizer(_:)))
the.delegate = self
the.direction = .right
the.require(toFail: swipeLeftGestureRecognizer)
return the
}()
panGestureRecognizer = {
let the = UIPanGestureRecognizer(target: self, action: #selector(handlePanGestureRecognizer(_:)))
the.delegate = self
the.require(toFail: swipeLeftGestureRecognizer)
the.require(toFail: swipeRightGestureRecognizer)
return the
}()
tapGestureRecognizer = {
let the = UITapGestureRecognizer()
the.delegate = self
the.numberOfTapsRequired = 1
the.cancelsTouchesInView = false
the.require(toFail: swipeLeftGestureRecognizer)
the.require(toFail: swipeRightGestureRecognizer)
the.require(toFail: panGestureRecognizer)
the.isEnabled = false
return the
}()
tempTapGestureRecognizer = {
let the = UITapGestureRecognizer(target: self, action: #selector(handleTempTapGestureRecognizer(_:)))
the.numberOfTapsRequired = 1
the.require(toFail: swipeLeftGestureRecognizer)
the.require(toFail: swipeRightGestureRecognizer)
the.require(toFail: panGestureRecognizer)
return the
}()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Wrap
public func wrap(cell target: UITableViewCell, actionsLeft: [ActionControl] = [], actionsRight: [ActionControl] = []) {
cell = target
target.selectionStyle = .none
target.addSubview(self)
target.sendSubview(toBack: self)
translatesAutoresizingMaskIntoConstraints = false
target.addConstraint(NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: target, attribute: .leading, multiplier: 1, constant: 0))
target.addConstraint(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: target, attribute: .trailing, multiplier: 1, constant: 0))
target.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: target, attribute: .top, multiplier: 1, constant: 0))
target.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: target, attribute: .bottom, multiplier: 1, constant: 0))
target.addGestureRecognizer(swipeLeftGestureRecognizer)
target.addGestureRecognizer(swipeRightGestureRecognizer)
target.addGestureRecognizer(panGestureRecognizer)
target.addGestureRecognizer(tapGestureRecognizer)
setupActionsheet(side: .left, actions: actionsLeft)
setupActionsheet(side: .right, actions: actionsRight)
}
// MARK: Actionsheet
/// Setup actionsheet
func setupActionCell(side: ActionSide) {
#if DEVELOPMENT
print("\(#function) -- " + "side: \(side)")
#endif
if isActionsheetValid(side: side) {
cell!.bringSubview(toFront: self)
contentScreenshot = UIImageView(image: screenshotImageOfView(view: cell!))
contentScreenshot?.isUserInteractionEnabled = true
contentScreenshot?.addGestureRecognizer(tempTapGestureRecognizer)
addSubview(contentScreenshot!)
currentActionsheet = actionsheet(side: side)
defaultAction = defaultAction(side: side)
backgroundColor = defaultAction?.backgroundColor
tapGestureRecognizer.isEnabled = true
}
}
/// Clear actionsheet when actionsheet is closed
func clearActionCell(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if isActionsheetOpened {
setActionsheet(for: .close, orientation: .close)
}
tapGestureRecognizer.isEnabled = false
isDefaultActionTriggered = false
defaultAction = nil
contentScreenshot?.removeFromSuperview()
contentScreenshot?.removeGestureRecognizer(tempTapGestureRecognizer)
contentScreenshot = nil
backgroundColor = UIColor.clear
cell!.sendSubview(toBack: self)
completionHandler?()
}
/// Setup action sheet
func setupActionsheet(side: ActionSide, actions: [ActionControl]) {
#if DEVELOPMENT
print("\(#function) -- " + "side: \(side)")
#endif
actionsheet(side: side).actions.forEach {
$0.removeFromSuperview()
}
actionsheet(side: side).actions = actions
actionsheet(side: side).actions.reversed().forEach {
$0.delegate = self
addSubview($0)
}
resetActionConstraints(side: side)
resetActionAttributes(side: side)
}
/// Open action sheet
public func openActionsheet(side: ActionSide, completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "side: \(side)")
#endif
setupActionCell(side: side)
animateCloseToOpen(completionHandler)
}
/// Close opened action sheet
public func closeActionsheet(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if isActionsheetOpened {
animateOpenToClose(completionHandler)
}
}
/// Set actions' constraints for beginning
func resetActionConstraints(side: ActionSide) {
#if DEVELOPMENT
print("\(#function) -- " + "side: \(side)")
#endif
actionsheet(side: side).actions.enumerated().forEach { (index, action) in
action.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: action, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: action, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
switch side {
case .left:
let constraintHead = NSLayoutConstraint(item: action, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: -1 * action.width)
action.constraintHead = constraintHead
addConstraint(constraintHead)
let constraintTail = NSLayoutConstraint(item: action, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
action.constraintTail = constraintTail
addConstraint(constraintTail)
case .right:
let constraintHead = NSLayoutConstraint(item: action, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: action.width)
action.constraintHead = constraintHead
addConstraint(constraintHead)
let constraintTail = NSLayoutConstraint(item: action, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
action.constraintTail = constraintTail
addConstraint(constraintTail)
}
}
setNeedsLayout()
layoutIfNeeded()
}
/// Setup actions' attributes
func resetActionAttributes(side: ActionSide) {
#if DEVELOPMENT
print("\(#function) -- " + "side: \(side)")
#endif
actionsheet(side: side).actions.forEach {
$0.update(position: .close)
$0.update(state: .active)
}
}
/// Set action sheet according to it's state
func setActionsheet(for state: ActionsheetState, orientation: AnimateOrientation) {
#if DEVELOPMENT
print("\(#function) -- " + "state: \(state)")
#endif
if let side = currentActionsheet?.side {
switch state {
case .close:
actionsheet(side: side).actions.enumerated().forEach({ (index, action) in
updateActionConstraints(action: action, orientation: .close, constantHead: (side == .left ? -1 : 1) * action.width, constantTail: 0)
action.update(position: .close)
})
resetActionAttributes(side: side)
currentActionsheet = nil
case .open:
actionsheet(side: side).actions.enumerated().forEach({ (index, action) in
let widthPre = currentActionsheet?.actionWidthBefore(actionIndex: index) ?? 0
updateActionConstraints(action: action, orientation: orientation, constantHead: (side == .left ? 1 : -1) * widthPre, constantTail: (side == .left ? 1 : -1) * (widthPre + action.width))
action.update(position: .open)
})
case .position(let position):
actionsheet(side: side).actions.enumerated().forEach({ (index, action) in
let widthPre = currentActionsheet?.actionWidthBefore(actionIndex: index) ?? 0
switch positionSection(side: side, position: position) {
case .close_OpenPre, .openPre_Open:
switch animationStyle {
case .ladder_emergence:
let currentLadderIndex = ladderingIndex(side: side, position: position)
if index == currentLadderIndex {
let progress = ((abs(position) - widthPre) / action.width).truncatingRemainder(dividingBy: 1)
action.update(position: .opening(progress: progress))
} else if index < currentLadderIndex {
action.update(position: .open)
}
fallthrough
case .ladder:
let currentActionIndex = ladderingIndex(side: side, position: position)
if index >= currentActionIndex {
updateActionConstraints(action: action, orientation: orientation, constantHead: position + (side == .left ? -1 : 1) * action.width, constantTail: position)
} else {
updateActionConstraints(action: action, orientation: orientation, constantHead: (side == .left ? 1 : -1) * widthPre, constantTail: (side == .left ? 1 : -1) * (widthPre + action.width))
action.update(position: .open)
}
case .concurrent:
var targetPosition = position
if abs(targetPosition) > abs(positionForOpen(side: side)) {
targetPosition = positionForOpen(side: side)
}
let actionAnchorPosition = targetPosition * (actionsheet(side: side).actionWidthBefore(actionIndex: index) + action.width) / actionsheet(side: side).width
updateActionConstraints(action: action, orientation: orientation, constantHead: actionAnchorPosition + (side == .left ? -1 : 1) * action.width, constantTail: actionAnchorPosition)
action.update(position: .open)
}
case .open_TriggerPre:
if isDefaultActionTriggered {
if action == defaultAction {
updateActionConstraints(action: action, orientation: orientation, constantHead: position + (side == .left ? -1 : 1) * action.width, constantTail: position)
}
} else {
updateActionConstraints(action: action, orientation: orientation, constantHead: position + (side == .left ? -1 : 1) * (actionsheet(side: side).actionWidthAfter(actionIndex: index) + action.width), constantTail: position + (side == .left ? -1 : 1) * actionsheet(side: side).actionWidthAfter(actionIndex: index))
}
case .triggerPre_Trigger:
if isDefaultActionTriggered && action == defaultAction {
updateActionConstraints(action: action, orientation: orientation, constantHead: position + (side == .left ? -1 : 1) * action.width, constantTail: position)
}
}
})
}
}
}
/// Get actionsheet
func actionsheet(side: ActionSide) -> Actionsheet {
switch side {
case .left:
return actionsheetLeft
case .right:
return actionsheetRight
}
}
/// Get action sheet actions
func actionsheetActions(side: ActionSide) -> [ActionControl] {
return actionsheet(side: side).actions
}
/// Get default action
func defaultAction(side: ActionSide) -> ActionControl? {
switch side {
case .left:
return actionsheetActions(side: side).first
case .right:
return actionsheetActions(side: side).first
}
}
/// Does action sheet have actions to show
func isActionsheetValid(side: ActionSide) -> Bool {
return actionsheet(side: side).actions.count > 0
}
/// Update action's constraints
func updateActionConstraints(action: ActionControl, orientation: AnimateOrientation,constantHead: CGFloat, constantTail: CGFloat) {
switch orientation {
case .close:
action.constraintHead?.constant = constantHead
action.constraintTail?.constant = constantTail
case .triggered:
action.constraintTail?.constant = constantTail
action.constraintHead?.constant = constantHead
}
setNeedsLayout()
}
// MARK: Default Action
/// Animate when default action is triggered
func animateDefaultActionTriggered(completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let side = currentActionsheet?.side {
actionsheet(side: side).actions.forEach {
if $0 != self.defaultAction {
$0.update(state: .inactive)
}
}
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
let position = self.positionForTriggerPrepare(side: side)
if let action = self.defaultAction {
self.updateActionConstraints(action: action, orientation: .triggered, constantHead: position + (side == .left ? -1 : 1) * action.width, constantTail: position)
}
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
completionHandler?()
})
}
}
/// Animate when default action's trigger is cancelled
func animateDefaultActionCancelled(completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let side = currentActionsheet?.side, let contentScreenshot = contentScreenshot {
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
self.setActionsheet(for: .position(contentScreenshot.frame.origin.x), orientation: .close)
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
self.actionsheet(side: side).actions.forEach {
$0.update(state: .active)
}
completionHandler?()
})
}
}
// MARK: Action Animate
/// Animate actions & contentScreenshot with orientation Open to Close
func animateOpenToClose(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let contentScreenshot = contentScreenshot {
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
contentScreenshot.frame.origin.x = self.positionForClose()
self.setActionsheet(for: .close, orientation: .close)
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
self.clearActionCell()
completionHandler?()
})
}
}
/// Animate actions & contentScreenshot with orientation Close to Open
func animateCloseToOpen(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let contentScreenshot = contentScreenshot, let side = currentActionsheet?.side {
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
contentScreenshot.frame.origin.x = self.positionForOpen(side: side)
self.setActionsheet(for: .open, orientation: .triggered)
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
completionHandler?()
})
}
}
/// Animate actions & contentScreenshot with orientation Trigger to Open
func animateTriggerToOpen(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let contentScreenshot = contentScreenshot, let side = currentActionsheet?.side {
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
contentScreenshot.frame.origin.x = self.positionForOpen(side: side)
self.setActionsheet(for: .open, orientation: .close)
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
completionHandler?()
})
}
}
/// Animate actions & contentScreenshot with orientation Open to Trigger
func animateOpenToTrigger(_ completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let contentScreenshot = contentScreenshot, let side = currentActionsheet?.side {
actionsheet(side: side).actions.forEach {
if $0 != self.defaultAction {
$0.update(state: .inactive)
}
}
self.cell!.isUserInteractionEnabled = false
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveLinear], animations: { [unowned self] in
contentScreenshot.frame.origin.x = self.positionForTrigger(side: side)
let position = self.positionForTrigger(side: side)
if let action = self.defaultAction {
self.updateActionConstraints(action: action, orientation: .triggered, constantHead: position + (side == .left ? -1 : 1) * action.width, constantTail: position)
}
self.layoutIfNeeded()
}, completion: { [unowned self] _ in
self.cell!.isUserInteractionEnabled = true
let action = self.defaultAction
self.clearActionCell {
action?.actionTriggered()
}
completionHandler?()
})
}
}
/// Animate actions to position, when the cell is panned
func animateToPosition(_ position: CGFloat, orientation: AnimateOrientation, completionHandler: (() -> ())? = nil) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
if let side = currentActionsheet?.side {
switch positionSection(side: side, position: position) {
case .close_OpenPre, .openPre_Open, .open_TriggerPre:
if isDefaultActionTriggered == true {
isDefaultActionTriggered = false
animateDefaultActionCancelled(completionHandler: completionHandler)
} else {
setActionsheet(for: .position(position), orientation: orientation)
completionHandler?()
}
case .triggerPre_Trigger:
if isDefaultActionTriggered == false {
isDefaultActionTriggered = true
animateDefaultActionTriggered(completionHandler: completionHandler)
} else {
setActionsheet(for: .position(position), orientation: orientation)
completionHandler?()
}
}
}
}
// MARK: Handle Gestures
@objc func handleSwipeGestureRecognizer(_ gestureRecognizer: UISwipeGestureRecognizer) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
switch gestureRecognizer.state {
case .ended:
if gestureRecognizer.direction == UISwipeGestureRecognizerDirection.left {
respondToSwipe(side: .right)
} else {
respondToSwipe(side: .left)
}
default:
break
}
}
func respondToSwipe(side: ActionSide) {
if let currentActionsheet = currentActionsheet {
if currentActionsheet.side == side {
if enableDefaultAction {
animateOpenToTrigger()
}
} else {
animateOpenToClose()
}
} else {
openActionsheet(side: side)
}
}
@objc func handlePanGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
let translation = gestureRecognizer.translation(in: cell!)
let velocity = gestureRecognizer.velocity(in: cell!)
switch gestureRecognizer.state {
case .began, .changed:
#if DEVELOPMENT
print("state -- " + "began | changed")
#endif
var actionSide: ActionSide? = nil
if let contentScreenshot = contentScreenshot {
let contentPosition = contentScreenshot.frame.origin.x
actionSide = contentPosition == 0 ? (velocity.x == 0 ? nil : (velocity.x > 0 ? .left : .right)) : (contentPosition > 0 ? .left : .right)
} else {
actionSide = velocity.x > 0 ? .left : .right
}
if actionSide != currentActionsheet?.side {
clearActionCell()
if let actionSide = actionSide {
setupActionCell(side: actionSide)
}
}
if let contentScreenshot = contentScreenshot, let side = currentActionsheet?.side, isActionsheetValid(side: side) {
switch positionSection(side: side, position: contentScreenshot.frame.origin.x) {
case .open_TriggerPre, .triggerPre_Trigger:
if enableDefaultAction == true { fallthrough }
default:
contentScreenshot.frame.origin.x += translation.x
gestureRecognizer.setTranslation(CGPoint.zero, in: self)
let orientation: AnimateOrientation = (side == .left) ? (velocity.x > 0 ? .triggered : .close) : (velocity.x < 0 ? .triggered : .close)
animateToPosition(contentScreenshot.frame.origin.x, orientation: orientation)
}
}
case .ended, .cancelled:
#if DEVELOPMENT
print("state -- " + "ended | cancelled")
#endif
var closure: (() -> ())? = nil
if let contentScreenshot = contentScreenshot, let side = currentActionsheet?.side {
switch positionSection(side: side, position: contentScreenshot.frame.origin.x) {
case .close_OpenPre:
closure = { [weak self] in
self?.animateOpenToClose()
}
case .openPre_Open:
closure = { [weak self] in
self?.animateCloseToOpen()
}
case .open_TriggerPre:
closure = enableDefaultAction ? { [weak self] in
self?.animateTriggerToOpen()
} : nil
case .triggerPre_Trigger:
closure = enableDefaultAction ? { [weak self] in
self?.animateOpenToTrigger()
} : nil
}
let orientation: AnimateOrientation = (side == .left) ? (velocity.x > 0 ? .triggered : .close) : (velocity.x < 0 ? .triggered : .close)
animateToPosition(contentScreenshot.frame.origin.x, orientation: orientation, completionHandler: closure)
}
default:
break
}
}
@objc func handleTempTapGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) {
#if DEVELOPMENT
print("\(#function) -- " + "")
#endif
animateOpenToClose()
}
// MARK: Position of cell state
/// Threshold for state Close
func positionForClose() -> CGFloat {
return 0
}
/// Threshold for state Open
func positionForOpen(side: ActionSide) -> CGFloat {
switch side {
case .left:
return actionsheet(side: side).width
case .right:
return -1 * actionsheet(side: side).width
}
}
/// Threshold for state OpenPrepare
func positionForOpenPrepare(side: ActionSide) -> CGFloat {
return positionForOpen(side: side) / 2.0
}
/// Threshold for state Trigger
func positionForTrigger(side: ActionSide) -> CGFloat {
switch side {
case .left:
return cell!.frame.width
case .right:
return -1 * cell!.frame.width
}
}
/// Threshold for state TriggerPrepare
func positionForTriggerPrepare(side: ActionSide) -> CGFloat {
let actionsheetWidth = actionsheet(side: side).width
switch side {
case .left:
return actionsheetWidth + (bounds.width - actionsheetWidth) * defaultActionTriggerPropotion
case .right:
return -1 * (actionsheetWidth + (bounds.width - actionsheetWidth) * defaultActionTriggerPropotion)
}
}
/// Get the section of current position
func positionSection(side: ActionSide, position: CGFloat) -> PositionSection {
let absPosition = abs(position)
if absPosition <= abs(positionForOpenPrepare(side: side)) {
return .close_OpenPre
} else if absPosition <= abs(positionForOpen(side: side)) {
return .openPre_Open
} else if absPosition <= abs(positionForTriggerPrepare(side: side)) {
return .open_TriggerPre
} else {
return .triggerPre_Trigger
}
}
/// Get laddering index
func ladderingIndex(side: ActionSide, position: CGFloat) -> Int {
let position = abs(position)
var result: [(Int, ActionControl)] = []
result = actionsheetActions(side: side).enumerated().filter({ (index, action) -> Bool in
let widthPre = actionsheet(side: side).actionWidthBefore(actionIndex: index)
return abs(position) >= widthPre && abs(position) < widthPre + action.width
})
if let currentAction = result.first {
return currentAction.0
} else {
return actionsheetActions(side: side).count
}
}
// MARK: Auxiliary
/// 创建视图的截图
func screenshotImageOfView(view: UIView) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
extension ActionCell: UIGestureRecognizerDelegate {
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGestureRecognizer, let gesture = gestureRecognizer as? UIPanGestureRecognizer {
let velocity = gesture.velocity(in: self)
return abs(velocity.x) > abs(velocity.y)
}
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if (gestureRecognizer == panGestureRecognizer || gestureRecognizer == tapGestureRecognizer || gestureRecognizer == swipeLeftGestureRecognizer || gestureRecognizer == swipeRightGestureRecognizer) && ( otherGestureRecognizer == delegate?.tableView.panGestureRecognizer || otherGestureRecognizer == delegate?.navigationController?.barHideOnSwipeGestureRecognizer || otherGestureRecognizer == delegate?.navigationController?.barHideOnTapGestureRecognizer) {
return true
}
return false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if (gestureRecognizer == panGestureRecognizer || gestureRecognizer == tapGestureRecognizer || gestureRecognizer == swipeLeftGestureRecognizer || gestureRecognizer == swipeRightGestureRecognizer) && ( otherGestureRecognizer == delegate?.tableView.panGestureRecognizer || otherGestureRecognizer == delegate?.navigationController?.barHideOnSwipeGestureRecognizer || otherGestureRecognizer == delegate?.navigationController?.barHideOnTapGestureRecognizer) {
return false
}
return true
}
}
extension ActionCell: ActionControlDelegate {
public func didActionTriggered(action: String) {
#if DEVELOPMENT
print("\(#function) -- " + "action: \(action)")
#endif
if currentActionsheet != nil {
closeActionsheet() { [unowned self] in
self.delegate?.didActionTriggered(cell: self.cell!, action: action)
}
} else {
delegate?.didActionTriggered(cell: cell!, action: action)
}
}
}
public class Actionsheet {
var side: ActionSide
var actions: [ActionControl] = []
/// sum of all actions' width
var width: CGFloat {
return actions.reduce(0, { (result, action) -> CGFloat in
result + action.width
})
}
init(side: ActionSide) {
self.side = side
}
/// sum of width of actions which is previous to the action
func actionWidthBefore(actionIndex index: Int) -> CGFloat {
return actions.prefix(upTo: index).reduce(0, { (result, action) -> CGFloat in
result + action.width
})
}
/// sum of width of actions which is previous to the action
func actionWidthAfter(actionIndex index: Int) -> CGFloat {
return actions.suffix(from: index + 1).reduce(0, { (result, action) -> CGFloat in
result + action.width
})
}
}
public enum ActionSide {
case left
case right
}
public enum ActionsheetOpenStyle {
/// 动作按钮阶梯滑出
case ladder
/// 动作按钮阶梯滑出 + 图标文字渐显效果
case ladder_emergence
/// 动作按钮并列滑出
case concurrent
}
public enum ActionsheetState {
case close
case open
case position(CGFloat)
}
public enum AnimateOrientation {
case close
case triggered
}
public enum PositionSection {
case close_OpenPre
case openPre_Open
case open_TriggerPre
case triggerPre_Trigger
}
| mit | f8d0d1b9f89a22e542c80ea65362ae72 | 41.40625 | 461 | 0.589263 | 5.288539 | false | false | false | false |
ReactiveX/RxSwift | RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift | 7 | 2009 | //
// NSObject+Rx+KVORepresentable.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import Foundation
import RxSwift
/// Key value observing options
public struct KeyValueObservingOptions: OptionSet {
/// Raw value
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// Whether a sequence element should be sent to the observer immediately, before the subscribe method even returns.
public static let initial = KeyValueObservingOptions(rawValue: 1 << 0)
/// Whether to send updated values.
public static let new = KeyValueObservingOptions(rawValue: 1 << 1)
}
extension Reactive where Base: NSObject {
/**
Specialization of generic `observe` method.
This is a special overload because to observe values of some type (for example `Int`), first values of KVO type
need to be observed (`NSNumber`), and then converted to result type.
For more information take a look at `observe` method.
*/
public func observe<Element: KVORepresentable>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<Element?> {
return self.observe(Element.KVOType.self, keyPath, options: options, retainSelf: retainSelf)
.map(Element.init)
}
}
#if !DISABLE_SWIZZLING && !os(Linux)
// KVO
extension Reactive where Base: NSObject {
/**
Specialization of generic `observeWeakly` method.
For more information take a look at `observeWeakly` method.
*/
public func observeWeakly<Element: KVORepresentable>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable<Element?> {
return self.observeWeakly(Element.KVOType.self, keyPath, options: options)
.map(Element.init)
}
}
#endif
#endif
| mit | 85430c08d56d591cfc06b32be8a0de29 | 32.466667 | 196 | 0.684263 | 4.462222 | false | false | false | false |
connienguyen/volunteers-iOS | VOLA/VOLA/Helpers/Constants+Firebase.swift | 1 | 933 | //
// Constants+Firebase.swift
// VOLA
//
// Created by Connie Nguyen on 8/5/17.
// Copyright © 2017 Systers-Opensource. All rights reserved.
//
import Foundation
/// Protocol for values that are used as parameter keys in API requests
protocol ParameterKey {
var key: String { get }
}
/// Parameter keys used with Firebase requests
struct FirebaseKeys {
enum User: String, ParameterKey {
case firstName = "first_name"
case lastName = "last_name"
case affiliation
case title
var key: String {
return rawValue
}
}
enum EventRegistration: String, ParameterKey {
case eventID = "event_id"
case attendeeType = "attendee_type"
case firstName = "first_name"
case lastName = "last_name"
case email
case affiliation
case title
var key: String {
return rawValue
}
}
}
| gpl-2.0 | eb8022296bc7adc8d213ec6f6584cfb8 | 21.190476 | 71 | 0.607296 | 4.275229 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/Logging/SentryStartupEvent.swift | 2 | 2153 | import Foundation
import AutomatticTracks
import Sentry
private struct ErrorWithCaller {
let error: NSError
let caller: String
}
/**
WARNING: This class was created to track events of failures during
startup time. This will block the thread. Do not use unless you're sure.
*/
@objc class SentryStartupEvent: NSObject {
private typealias UserInfo = [String: Any]
private var errors = [ErrorWithCaller]()
func add(error: NSError, file: String = #file, function: String = #function, line: UInt = #line) {
let filename = (file as NSString).lastPathComponent
errors.append(ErrorWithCaller(error: error, caller: "\(function) (\(filename):\(line))"))
}
func add(error: Error, file: String = #file, function: String = #function, line: UInt = #line) {
add(error: error as NSError, file: file, function: function, line: line)
}
@objc(addError:file:function:line:)
func _objc_add(error: NSError, file: UnsafePointer<CChar>, function: UnsafePointer<CChar>, line: UInt) {
add(error: error, file: String(cString: file), function: String(cString: function), line: line)
}
// Send the event and block the thread until it was actually sent
@objc func send(title: String) {
let userInfo = errors.enumerated().reduce(into: [String: Any](), { (result, arg1) in
let (index, errorWithCaller) = arg1
let error = errorWithCaller.error
result["Error \(index + 1)"] = [
"Method": errorWithCaller.caller,
"Domain": error.domain,
"Code": error.code,
"Description": error.localizedDescription,
"User Info": error.userInfo.description
]
})
let error = NSError(domain: title, code: -1, userInfo: [NSLocalizedDescriptionKey: title])
do {
try WordPressAppDelegate.crashLogging?.logErrorAndWait(error, userInfo: userInfo, level: SentryLevel.fatal)
} catch let err {
DDLogError("⛔️ Unable to send startup error message to Sentry:")
DDLogError(err.localizedDescription)
}
}
}
| gpl-2.0 | be9be2789d25078eeb2c6372a70ad872 | 37.375 | 119 | 0.638436 | 4.376782 | false | false | false | false |
redlock/SwiftyDeepstream | SwiftyDeepstream/Classes/deepstream/utils/Reflection/Metadata+Tuple.swift | 13 | 783 | extension Metadata {
struct Tuple : MetadataType {
static let kind: Kind? = .tuple
var pointer: UnsafePointer<Int>
var labels: [String?] {
guard var pointer = UnsafePointer<CChar>(bitPattern: pointer[2]) else { return [] }
var labels = [String?]()
var string = ""
while pointer.pointee != 0 {
guard pointer.pointee != 32 else {
labels.append(string.isEmpty ? nil : string)
string = ""
pointer.advance()
continue
}
string.append(String(UnicodeScalar(UInt8(bitPattern: pointer.pointee))))
pointer.advance()
}
return labels
}
}
}
| mit | 652c1fbb9e5f47ebe9ce5d89d5826ff8 | 34.590909 | 95 | 0.48659 | 5.363014 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/LibaryFile/ThPullRefresh/Head/ThHeadBounceRefreshView.swift | 1 | 10836 | //
// ThHeadBounceRefreshView.swift
// PullRefresh
//
// Created by tanhui on 16/1/7.
// Copyright © 2016年 tanhui. All rights reserved.
//
import UIKit
class ThHeadBounceRefreshView: ThHeadRefreshView {
let l1 = UIView()
let l2 = UIView()
let r1 = UIView()
let r2 = UIView()
let c = UIView()
var progress = 0.0
let KeyPathX = "pathx"
let KeyPathY = "pathy"
var focusX : CGFloat?
var focusY : CGFloat?
var shapeLayer = CAShapeLayer()
var circleView = UIView()
var circleLayer = CAShapeLayer()
var loadingColor : UIColor? {
willSet{
circleLayer.strokeColor = newValue!.CGColor
}
}
var bgColor : UIColor? {
willSet{
shapeLayer.fillColor = newValue!.CGColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.configeShapeLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:private Methods
private func configeCircleLayer(){
self.circleView.size = CGSizeMake(ThHeadRefreshingCircleRadius * 2.0, ThHeadRefreshingCircleRadius*2.0)
circleView.center = self.center
circleView.backgroundColor=UIColor.clearColor()
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = self.loadingColor?.CGColor
circleLayer.lineWidth = 1;
circleLayer.frame = circleView.bounds
self.circleView.layer.addSublayer(circleLayer)
self.addSubview(circleView)
}
private func configeShapeLayer(){
shapeLayer.frame = self.bounds
self.layer.addSublayer(shapeLayer)
}
private func updateShapeLayerPath (){
let bezierPath = UIBezierPath()
if(self.height<=self.oringalheight){
let lControlPoint1 = CGPoint(x:0,y:self.oringalheight!)
let lControlPoint2 = CGPoint(x:0,y:self.oringalheight!)
let rControlPoint1 = CGPoint(x:self.width,y:self.oringalheight!)
let rControlPoint2 = CGPoint(x:self.width,y:self.oringalheight!)
l1.center = lControlPoint1
l2.center = lControlPoint2
r1.center = rControlPoint1
r2.center = rControlPoint2
c.center = CGPoint(x:self.width*0.5 , y:self.oringalheight!)
bezierPath .moveToPoint(CGPoint(x: 0, y: 0))
bezierPath .addLineToPoint(CGPoint(x:self.width, y: 0))
bezierPath .addLineToPoint(rControlPoint1)
bezierPath.addLineToPoint(lControlPoint1)
bezierPath.addLineToPoint(CGPoint(x: 0, y: 0))
bezierPath.closePath()
}else{
self.focusY = self.height
let rate :CGFloat = 0.75
let marginHeight = ( self.height - self.oringalheight! ) * 0.3 + self.oringalheight!
let controlHeight = ( self.height - self.oringalheight! ) * 1 + self.oringalheight!
let leftWidth = self.focusX!
let rightWidth = self.width - self.focusX!
let lControlPoint1 = CGPoint(x:leftWidth*rate ,y:marginHeight)
let lControlPoint2 = CGPoint(x:leftWidth * rate,y:controlHeight)
let rControlPoint1 = CGPoint(x:rightWidth*(1-rate)+leftWidth,y:marginHeight)
let rControlPoint2 = CGPoint(x:rightWidth*(1-rate)+leftWidth,y:controlHeight)
l1.center = lControlPoint1
l2.center = lControlPoint2
r1.center = rControlPoint1
r2.center = rControlPoint2
c.center = CGPoint(x:leftWidth , y:self.focusY!)
bezierPath .moveToPoint(CGPoint(x: 0, y: 0))
bezierPath .addLineToPoint(CGPoint(x:self.width, y: 0))
bezierPath .addLineToPoint(CGPoint(x: self.width,y: marginHeight))
bezierPath.addCurveToPoint(CGPoint(x: leftWidth+1,y: self.focusY!), controlPoint1: rControlPoint1, controlPoint2: rControlPoint2)
bezierPath.addLineToPoint(CGPoint(x:leftWidth-1 , y:self.focusY!))
bezierPath.addCurveToPoint(CGPoint(x: 0,y: marginHeight), controlPoint1: lControlPoint2, controlPoint2: lControlPoint1)
bezierPath.closePath()
}
shapeLayer.path = bezierPath.CGPath
}
func updateCirclePath(){
circleView.centerY = self.height*0.5
circleView.centerX = self.centerX
if self.state == .Pulling||self.state == .Idle{
let loadingBezier = UIBezierPath()
let center = CGPointMake(circleView.width*0.5, circleView.height*0.5)
loadingBezier.addArcWithCenter(center, radius: ThHeadRefreshingCircleRadius , startAngle: CGFloat(-M_PI_2), endAngle:CGFloat((M_PI * 2) * progress - M_PI_2) , clockwise: true)
circleLayer.path = loadingBezier.CGPath
}else if(self.state == .Refreshing){
//刷新的动画
if(circleLayer.animationForKey("refreshing") != nil){
return
}
let loadingBezier = UIBezierPath()
let center = CGPointMake(circleView.width*0.5, circleView.height*0.5)
loadingBezier.addArcWithCenter(center, radius: ThHeadRefreshingCircleRadius , startAngle: CGFloat(-M_PI_2), endAngle:CGFloat((M_PI * 2) * 0.9 - M_PI_2) , clockwise: true)
circleLayer.path = loadingBezier.CGPath
let animate = CABasicAnimation(keyPath: "transform.rotation")
animate.byValue = M_PI_2*3
animate.repeatCount=999
animate.duration = 0.5
animate.fillMode = kCAFillModeForwards
circleLayer.addAnimation(animate, forKey: "refreshing")
}
}
private func removePath(){
if circleLayer.path != nil{
circleLayer.removeAnimationForKey("refreshing")
circleLayer.path = nil
}
}
private func startAnimating(){
if(self.displayLink == nil){
displayLink = CADisplayLink(target: self, selector: "updateCirclePath")
displayLink!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
}
private func stopAnimating(){
displayLink?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
displayLink?.paused = true
displayLink = nil
if circleLayer.path != nil{
circleLayer.removeAnimationForKey("refreshing")
circleLayer.path = nil
}
}
//MARK:Overrides
override func setStates(state: ThHeadRefreshState,oldState : ThHeadRefreshState) {
super.setStates(state, oldState: oldState)
if state==oldState{
return
}
switch(state){
case .Refreshing:
self.startAnimating()
break;
case .Idle:
if oldState == .Refreshing{
self.stopAnimating()
self.removePath()
}
break
default:
break
}
}
override func adjustStateWithContentOffset(){
if self.state == .Refreshing&&self.scrollView?.dragging==true{
if( self.scrollView?.th_offsetY < 0-(self.scrollView?.th_insetT)! ){
self.scrollView?.th_offsetY = -(self.scrollView?.th_insetT)!
}
}
progress = Double( (self.height-self.oringalheight!)/self.oringalheight!)
if(self.scrollView?.dragging == true){
self.startAnimating()
if(self.state == .Idle && progress>0.9){
self.state = .Pulling
}else if (self.state == .Pulling && progress<=0.9){
self.state = .Idle
}
}else if (self.state == .Pulling){
self.state = .Refreshing
// self.stopAnimating()
// self.startAnimating()
}else if(self.state == .Idle){
self.stopAnimating()
self.removePath()
}
let offY = 0 - Double((self.scrollView?.th_offsetY)!)
let culheight = (self.scrollView?.th_insetT)!+self.oringalheight!
if (offY > Double( culheight )){
if(self.scrollView?.dragging==true||self.state == .Idle){
self.height = CGFloat( offY - Double((self.scrollView?.th_insetT)!) )
let pan = self.scrollView?.panGestureRecognizer
let point = pan?.locationInView(self)
self.focusX = point?.x
if(self.scrollView?.dragging==true){
self.startAnimating()
}
}
}else if(self.state == .Refreshing||self.state == .Idle){
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.height = self.oringalheight!;
})
}
self.layoutSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
self.updateShapeLayerPath()
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if (newSuperview != nil){
//initial circleView after self
self.configeCircleLayer()
self.focusX = self.width * 0.5
self.focusY = self.oringalheight
shapeLayer.frame = self.bounds
self.addObserver(self, forKeyPath: KeyPathX, options: .New, context: nil)
self.addObserver(self, forKeyPath: KeyPathY, options: .New, context: nil)
self.l1.size = CGSizeMake(3, 3)
self.l2.size = CGSizeMake(3, 3)
self.r1.size = CGSizeMake(3, 3)
self.r2.size = CGSizeMake(3, 3)
c.size = CGSizeMake(3, 3)
l1.backgroundColor = UIColor.clearColor()
l2.backgroundColor = UIColor.clearColor()
r1.backgroundColor = UIColor.clearColor()
r2.backgroundColor = UIColor.clearColor()
c.backgroundColor = UIColor.clearColor()
self.addSubview(l1)
self.addSubview(l2)
self.addSubview(r1)
self.addSubview(r2)
self.addSubview(c)
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath == KeyPathX || keyPath == KeyPathY){
}else if keyPath == ThHeadRefreshContentOffset {
self.adjustStateWithContentOffset()
}
}
deinit{
self.removeObserver(self, forKeyPath: KeyPathX, context: nil)
self.removeObserver(self, forKeyPath: KeyPathY, context: nil)
}
var displayLink : CADisplayLink?
}
| mit | bf296499c4932e449e1efaa882c291de | 38.213768 | 187 | 0.593366 | 4.551304 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Settings/Acknowledgement List/AcknowledgementListDataSource.swift | 1 | 1454 | //
// AcknowledgementListDataSource.swift
// ScoreReporter
//
// Created by Bradley Smith on 10/4/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import ScoreReporterCore
struct Acknowledgement {
let title: String
let info: String
let URL: URL?
init?(dictionary: [String: AnyObject]) {
guard let title = dictionary["Title"] as? String,
let info = dictionary["FooterText"] as? String,
!title.isEmpty else {
return nil
}
self.title = title
self.info = info
URL = nil
}
}
class AcknowledgementListDataSource: ArrayDataSource {
typealias ModelType = Acknowledgement
fileprivate(set) var items = [Acknowledgement]()
init() {
configureItems()
}
}
// MARK: - Private
private extension AcknowledgementListDataSource {
func configureItems() {
guard let bundlePath = Bundle.main.path(forResource: "Settings", ofType: "bundle"),
let bundle = Bundle(path: bundlePath),
let plistPath = bundle.path(forResource: "Acknowledgements", ofType: "plist"),
let plist = NSDictionary(contentsOfFile: plistPath) as? [String: AnyObject],
var pods = plist["PreferenceSpecifiers"] as? [[String: AnyObject]] else {
return
}
pods.removeFirst()
items = pods.flatMap { Acknowledgement(dictionary: $0) }
}
}
| mit | 4599f60f73efd332fc34ef4c4937fc25 | 24.946429 | 92 | 0.623538 | 4.627389 | false | false | false | false |
VicFrolov/Markit | iOS/Markit/Pods/PromiseKit/Extensions/Foundation/Sources/URLDataPromise.swift | 6 | 4444 | import Foundation
#if !COCOAPODS
import PromiseKit
#endif
public enum Encoding {
/// Decode as JSON
case json(JSONSerialization.ReadingOptions)
}
/**
A promise capable of decoding common Internet data types.
Used by:
- PromiseKit/Foundation
- PromiseKit/Social
- PromiseKit/OMGHTTPURLRQ
But probably of general use to any promises that receive HTTP `Data`.
*/
public class URLDataPromise: Promise<Data> {
/// Convert the promise to a tuple of `(Data, URLResponse)`
public func asDataAndResponse() -> Promise<(Data, Foundation.URLResponse)> {
return then(on: zalgo) { ($0, self.URLResponse) }
}
/// Decode the HTTP response to a String, the string encoding is read from the response.
public func asString() -> Promise<String> {
return then(on: waldo) { data -> String in
guard let str = String(bytes: data, encoding: self.URLResponse.stringEncoding ?? .utf8) else {
throw PMKURLError.stringEncoding(self.URLRequest, data, self.URLResponse)
}
return str
}
}
/// Decode the HTTP response as a JSON array
public func asArray(_ encoding: Encoding = .json(.allowFragments)) -> Promise<NSArray> {
return then(on: waldo) { data -> NSArray in
switch encoding {
case .json(let options):
guard !data.b0rkedEmptyRailsResponse else { return NSArray() }
let json = try JSONSerialization.jsonObject(with: data, options: options)
guard let array = json as? NSArray else { throw JSONError.unexpectedRootNode(json) }
return array
}
}
}
/// Decode the HTTP response as a JSON dictionary
public func asDictionary(_ encoding: Encoding = .json(.allowFragments)) -> Promise<NSDictionary> {
return then(on: waldo) { data -> NSDictionary in
switch encoding {
case .json(let options):
guard !data.b0rkedEmptyRailsResponse else { return NSDictionary() }
let json = try JSONSerialization.jsonObject(with: data, options: options)
guard let dict = json as? NSDictionary else { throw JSONError.unexpectedRootNode(json) }
return dict
}
}
}
fileprivate var URLRequest: Foundation.URLRequest!
fileprivate var URLResponse: Foundation.URLResponse!
/// Internal
public class func go(_ request: URLRequest, body: (@escaping (Data?, URLResponse?, Error?) -> Void) -> Void) -> URLDataPromise {
let (p, fulfill, reject) = URLDataPromise.pending()
let promise = p as! URLDataPromise
body { data, rsp, error in
promise.URLRequest = request
promise.URLResponse = rsp
if let error = error {
reject(error)
} else if let data = data, let rsp = rsp as? HTTPURLResponse, rsp.statusCode >= 200, rsp.statusCode < 300 {
fulfill(data)
} else if let data = data, !(rsp is HTTPURLResponse) {
fulfill(data)
} else {
reject(PMKURLError.badResponse(request, data, rsp))
}
}
return promise
}
}
#if os(iOS)
import UIKit.UIImage
extension URLDataPromise {
/// Decode the HTTP response as a UIImage
public func asImage() -> Promise<UIImage> {
return then(on: waldo) { data -> UIImage in
guard let img = UIImage(data: data), let cgimg = img.cgImage else {
throw PMKURLError.invalidImageData(self.URLRequest, data)
}
// this way of decoding the image limits main thread impact when displaying the image
return UIImage(cgImage: cgimg, scale: img.scale, orientation: img.imageOrientation)
}
}
}
#endif
extension URLResponse {
fileprivate var stringEncoding: String.Encoding? {
guard let encodingName = textEncodingName else { return nil }
let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString)
guard encoding != kCFStringEncodingInvalidId else { return nil }
return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding))
}
}
extension Data {
fileprivate var b0rkedEmptyRailsResponse: Bool {
return count == 1 && withUnsafeBytes{ $0[0] == " " }
}
}
| apache-2.0 | 7d0c49073dee9d98937ed5dc4795d596 | 35.727273 | 132 | 0.619937 | 4.778495 | false | false | false | false |
codeOfRobin/Components-Personal | Sources/ChevronCascadeNode.swift | 1 | 795 | //
// ChevronCascadeNode.swift
// BuildingBlocks-iOS
//
// Created by Robin Malhotra on 13/09/17.
// Copyright © 2017 BuildingBlocks. All rights reserved.
//
import AsyncDisplayKit
class ChevronTextNode: ASCellNode {
let imageNode = ASImageNode()
let textNode: DefaultTextNode
init(text: String) {
self.textNode = DefaultTextNode(text: text)
super.init()
imageNode.style.width = ASDimensionMake(8)
imageNode.style.height = ASDimensionMake(13)
imageNode.image = FrameworkImage.chevron
self.automaticallyManagesSubnodes = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
return ASStackLayoutSpec(direction: .horizontal, spacing: 0.0, justifyContent: .spaceBetween, alignItems: .center, children: [textNode, imageNode])
}
}
| mit | ad9228d6ac8c54afbcf927fab948a1d7 | 27.357143 | 149 | 0.756927 | 3.763033 | false | false | false | false |
jboullianne/EndlessTunes | Pods/SwiftOverlays/SwiftOverlays/SwiftOverlays.swift | 1 | 19116 | //
// SwiftOverlays.swift
// SwiftTest
//
// Created by Peter Prokop on 15/10/14.
// Copyright (c) 2014 Peter Prokop. All rights reserved.
//
import Foundation
import UIKit
// For convenience methods
public extension UIViewController {
/**
Shows wait overlay with activity indicator, centered in the view controller's main view
Do not use this method for **UITableViewController** or **UICollectionViewController**
- returns: Created overlay
*/
@discardableResult
func showWaitOverlay() -> UIView {
return SwiftOverlays.showCenteredWaitOverlay(self.view)
}
/**
Shows wait overlay with activity indicator *and text*, centered in the view controller's main view
Do not use this method for **UITableViewController** or **UICollectionViewController**
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
@discardableResult
func showWaitOverlayWithText(_ text: String) -> UIView {
return SwiftOverlays.showCenteredWaitOverlayWithText(self.view, text: text)
}
/**
Shows *text-only* overlay, centered in the view controller's main view
Do not use this method for **UITableViewController** or **UICollectionViewController**
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
@discardableResult
func showTextOverlay(_ text: String) -> UIView {
return SwiftOverlays.showTextOverlay(self.view, text: text)
}
/**
Shows overlay with text and progress bar, centered in the view controller's main view
Do not use this method for **UITableViewController** or **UICollectionViewController**
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
@discardableResult
func showProgressOverlay(_ text: String) -> UIView {
return SwiftOverlays.showProgressOverlay(self.view, text: text)
}
/**
Shows overlay *with image and text*, centered in the view controller's main view
Do not use this method for **UITableViewController** or **UICollectionViewController**
- parameter image: Image to be added to overlay
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
@discardableResult
func showImageAndTextOverlay(_ image: UIImage, text: String) -> UIView {
return SwiftOverlays.showImageAndTextOverlay(self.view, image: image, text: text)
}
/**
Shows notification on top of the status bar, similar to native local or remote notifications
- parameter notificationView: View that will be shown as notification
- parameter duration: Amount of time until notification disappears
- parameter animated: Should appearing be animated
*/
class func showNotificationOnTopOfStatusBar(_ notificationView: UIView, duration: TimeInterval, animated: Bool = true) {
SwiftOverlays.showAnnoyingNotificationOnTopOfStatusBar(notificationView, duration: duration, animated: animated)
}
/**
Removes all overlays from view controller's main view
*/
func removeAllOverlays() {
SwiftOverlays.removeAllOverlaysFromView(self.view)
}
/**
Updates text on the current overlay.
Does nothing if no overlay is present.
- parameter text: Text to set
*/
func updateOverlayText(_ text: String) {
SwiftOverlays.updateOverlayText(self.view, text: text)
}
/**
Updates progress on the current overlay.
Does nothing if no overlay is present.
- parameter progress: Progress to set 0.0 .. 1.0
*/
func updateOverlayProgress(_ progress: Float) {
SwiftOverlays.updateOverlayProgress(self.view, progress: progress)
}
}
open class SwiftOverlays: NSObject {
// You can customize these values
// Some random number
static let containerViewTag = 456987123
static let cornerRadius = CGFloat(10)
static let padding = CGFloat(10)
static let backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
static let textColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
static let font = UIFont.systemFont(ofSize: 14)
// Annoying notifications on top of status bar
static let bannerDissapearAnimationDuration = 0.5
static var bannerWindow : UIWindow?
open class Utils {
/**
Adds autolayout constraints to innerView to center it in its superview and fix its size.
`innerView` should have a superview.
- parameter innerView: View to set constraints on
*/
open static func centerViewInSuperview(_ view: UIView) {
assert(view.superview != nil, "`view` should have a superview")
view.translatesAutoresizingMaskIntoConstraints = false
let constraintH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: view.superview,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0)
let constraintV = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: view.superview,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0)
let constraintWidth = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: view.frame.size.width)
let constraintHeight = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: view.frame.size.height)
view.superview!.addConstraints([constraintV, constraintH, constraintWidth, constraintHeight])
}
}
// MARK: - Public class methods -
// MARK: Blocking
/**
Shows *blocking* wait overlay with activity indicator, centered in the app's main window
- returns: Created overlay
*/
@discardableResult
open class func showBlockingWaitOverlay() -> UIView {
let blocker = addMainWindowBlocker()
showCenteredWaitOverlay(blocker)
return blocker
}
/**
Shows wait overlay with activity indicator *and text*, centered in the app's main window
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
@discardableResult
open class func showBlockingWaitOverlayWithText(_ text: String) -> UIView {
let blocker = addMainWindowBlocker()
showCenteredWaitOverlayWithText(blocker, text: text)
return blocker
}
/**
Shows *blocking* overlay *with image and text*,, centered in the app's main window
- parameter image: Image to be added to overlay
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
open class func showBlockingImageAndTextOverlay(_ image: UIImage, text: String) -> UIView {
let blocker = addMainWindowBlocker()
showImageAndTextOverlay(blocker, image: image, text: text)
return blocker
}
/**
Shows *text-only* overlay, centered in the app's main window
- parameter text: Text to be shown on overlay
- returns: Created overlay
*/
open class func showBlockingTextOverlay(_ text: String) -> UIView {
let blocker = addMainWindowBlocker()
showTextOverlay(blocker, text: text)
return blocker
}
/**
Removes all *blocking* overlays from application's main window
*/
open class func removeAllBlockingOverlays() {
let window = UIApplication.shared.delegate!.window!!
removeAllOverlaysFromView(window)
}
// MARK: Non-blocking
@discardableResult
open class func showCenteredWaitOverlay(_ parentView: UIView) -> UIView {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
ai.startAnimating()
let containerViewRect = CGRect(x: 0,
y: 0,
width: ai.frame.size.width * 2,
height: ai.frame.size.height * 2)
let containerView = UIView(frame: containerViewRect)
containerView.tag = containerViewTag
containerView.layer.cornerRadius = cornerRadius
containerView.backgroundColor = backgroundColor
containerView.center = CGPoint(x: parentView.bounds.size.width/2,
y: parentView.bounds.size.height/2);
ai.center = CGPoint(x: containerView.bounds.size.width/2,
y: containerView.bounds.size.height/2);
containerView.addSubview(ai)
parentView.addSubview(containerView)
Utils.centerViewInSuperview(containerView)
return containerView
}
@discardableResult
open class func showCenteredWaitOverlayWithText(_ parentView: UIView, text: String) -> UIView {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
ai.startAnimating()
return showGenericOverlay(parentView, text: text, accessoryView: ai)
}
@discardableResult
open class func showImageAndTextOverlay(_ parentView: UIView, image: UIImage, text: String) -> UIView {
let imageView = UIImageView(image: image)
return showGenericOverlay(parentView, text: text, accessoryView: imageView)
}
open class func showGenericOverlay(_ parentView: UIView, text: String, accessoryView: UIView, horizontalLayout: Bool = true) -> UIView {
let label = labelForText(text)
var actualSize = CGSize.zero
if horizontalLayout {
actualSize = CGSize(width: accessoryView.frame.size.width + label.frame.size.width + padding * 3,
height: max(label.frame.size.height, accessoryView.frame.size.height) + padding * 2)
label.frame = label.frame.offsetBy(dx: accessoryView.frame.size.width + padding * 2, dy: padding)
accessoryView.frame = accessoryView.frame.offsetBy(dx: padding, dy: (actualSize.height - accessoryView.frame.size.height)/2)
} else {
actualSize = CGSize(width: max(accessoryView.frame.size.width, label.frame.size.width) + padding * 2,
height: label.frame.size.height + accessoryView.frame.size.height + padding * 3)
label.frame = label.frame.offsetBy(dx: padding, dy: accessoryView.frame.size.height + padding * 2)
accessoryView.frame = accessoryView.frame.offsetBy(dx: (actualSize.width - accessoryView.frame.size.width)/2, dy: padding)
}
// Container view
let containerViewRect = CGRect(x: 0,
y: 0,
width: actualSize.width,
height: actualSize.height)
let containerView = UIView(frame: containerViewRect)
containerView.tag = containerViewTag
containerView.layer.cornerRadius = cornerRadius
containerView.backgroundColor = backgroundColor
containerView.center = CGPoint(x: parentView.bounds.size.width/2,
y: parentView.bounds.size.height/2)
containerView.addSubview(accessoryView)
containerView.addSubview(label)
parentView.addSubview(containerView)
Utils.centerViewInSuperview(containerView)
return containerView
}
@discardableResult
open class func showTextOverlay(_ parentView: UIView, text: String) -> UIView {
let label = labelForText(text)
label.frame = label.frame.offsetBy(dx: padding, dy: padding)
let actualSize = CGSize(width: label.frame.size.width + padding * 2,
height: label.frame.size.height + padding * 2)
// Container view
let containerViewRect = CGRect(x: 0,
y: 0,
width: actualSize.width,
height: actualSize.height)
let containerView = UIView(frame: containerViewRect)
containerView.tag = containerViewTag
containerView.layer.cornerRadius = cornerRadius
containerView.backgroundColor = backgroundColor
containerView.center = CGPoint(x: parentView.bounds.size.width/2,
y: parentView.bounds.size.height/2);
containerView.addSubview(label)
parentView.addSubview(containerView)
Utils.centerViewInSuperview(containerView)
return containerView
}
open class func showProgressOverlay(_ parentView: UIView, text: String) -> UIView {
let pv = UIProgressView(progressViewStyle: .default)
return showGenericOverlay(parentView, text: text, accessoryView: pv, horizontalLayout: false)
}
open class func removeAllOverlaysFromView(_ parentView: UIView) {
var overlay: UIView?
while true {
overlay = parentView.viewWithTag(containerViewTag)
if overlay == nil {
break
}
overlay!.removeFromSuperview()
}
}
open class func updateOverlayText(_ parentView: UIView, text: String) {
if let overlay = parentView.viewWithTag(containerViewTag) {
for subview in overlay.subviews {
if let label = subview as? UILabel {
label.text = text as String
break
}
}
}
}
open class func updateOverlayProgress(_ parentView: UIView, progress: Float) {
if let overlay = parentView.viewWithTag(containerViewTag) {
for subview in overlay.subviews {
if let pv = subview as? UIProgressView {
pv.progress = progress
break
}
}
}
}
// MARK: Status bar notification
open class func showAnnoyingNotificationOnTopOfStatusBar(_ notificationView: UIView, duration: TimeInterval, animated: Bool = true) {
if bannerWindow == nil {
bannerWindow = UIWindow()
bannerWindow!.windowLevel = UIWindowLevelStatusBar + 1
bannerWindow!.backgroundColor = UIColor.clear
}
bannerWindow!.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: notificationView.frame.size.height)
bannerWindow!.isHidden = false
let selector = #selector(closeAnnoyingNotificationOnTopOfStatusBar)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
notificationView.addGestureRecognizer(gestureRecognizer)
bannerWindow!.addSubview(notificationView)
if animated {
let frame = notificationView.frame
let origin = CGPoint(x: 0, y: -frame.height)
notificationView.frame = CGRect(origin: origin, size: frame.size)
// Show appearing animation, schedule calling closing selector after completed
UIView.animate(withDuration: bannerDissapearAnimationDuration, animations: {
let frame = notificationView.frame
notificationView.frame = frame.offsetBy(dx: 0, dy: frame.height)
}, completion: { (finished) in
self.perform(selector, with: notificationView, afterDelay: duration)
})
} else {
// Schedule calling closing selector right away
self.perform(selector, with: notificationView, afterDelay: duration)
}
}
open class func closeAnnoyingNotificationOnTopOfStatusBar(_ sender: AnyObject) {
NSObject.cancelPreviousPerformRequests(withTarget: self)
var notificationView: UIView?
if sender.isKind(of: UITapGestureRecognizer.self) {
notificationView = (sender as! UITapGestureRecognizer).view!
} else if sender.isKind(of: UIView.self) {
notificationView = (sender as! UIView)
}
UIView.animate(withDuration: bannerDissapearAnimationDuration,
animations: { () -> Void in
if let frame = notificationView?.frame {
notificationView?.frame = frame.offsetBy(dx: 0, dy: -frame.size.height)
}
},
completion: { (finished) -> Void in
notificationView?.removeFromSuperview()
bannerWindow?.isHidden = true
}
)
}
// MARK: - Private class methods -
fileprivate class func labelForText(_ text: String) -> UILabel {
let textSize = text.size(attributes: [NSFontAttributeName: font])
let labelRect = CGRect(x: 0,
y: 0,
width: textSize.width,
height: textSize.height)
let label = UILabel(frame: labelRect)
label.font = font
label.textColor = textColor
label.text = text as String
label.numberOfLines = 0
return label;
}
fileprivate class func addMainWindowBlocker() -> UIView {
let window = UIApplication.shared.delegate!.window!!
let blocker = UIView(frame: window.bounds)
blocker.backgroundColor = backgroundColor
blocker.tag = containerViewTag
blocker.translatesAutoresizingMaskIntoConstraints = false
window.addSubview(blocker)
let viewsDictionary = ["blocker": blocker]
// Add constraints to handle orientation change
let constraintsV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[blocker]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDictionary)
let constraintsH = NSLayoutConstraint.constraints(withVisualFormat: "|-0-[blocker]-0-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDictionary)
window.addConstraints(constraintsV + constraintsH)
return blocker
}
}
| gpl-3.0 | d95f33f5fe624c1399b3f66f6ce1f104 | 35.204545 | 140 | 0.619481 | 5.386306 | false | false | false | false |
CraigSiemens/DividerView | Example/Tests/Tests.swift | 1 | 1707 | // https://github.com/Quick/Quick
import Quick
import Nimble
import DividerView
class DividerViewSpec: QuickSpec {
override func spec() {
describe("horizontal divider") {
let divider = DividerView(axis: .horizontal)
it("should have a intrinsic content height of 1") {
expect(divider.intrinsicContentSize.height).to(equal(1))
}
it("should have a intrinsic content width of UIViewNoIntrinsicMetric") {
expect(divider.intrinsicContentSize.width).to(equal(UIView.noIntrinsicMetric))
}
}
describe("vertical divider") {
let divider = DividerView(axis: .vertical)
it("should have a intrinsic content height of UIViewNoIntrinsicMetric") {
expect(divider.intrinsicContentSize.height).to(equal(UIView.noIntrinsicMetric))
}
it("should have a intrinsic content width of 1") {
expect(divider.intrinsicContentSize.width).to(equal(1))
}
}
describe("content hugging priority") {
let divider = DividerView()
it("should have required priority for vertical") {
let priority = divider.contentHuggingPriority(for: .vertical)
expect(priority).to(equal(UILayoutPriority.required))
}
it("should have required priority for horizontal") {
let priority = divider.contentHuggingPriority(for: .horizontal)
expect(priority).to(equal(UILayoutPriority.required))
}
}
}
}
| mit | c3c8cceeb99083c0f58c5ed1c3a64694 | 33.836735 | 95 | 0.570592 | 5.560261 | false | false | false | false |
Johennes/firefox-ios | Client/Frontend/Browser/MetadataParserHelper.swift | 1 | 1388 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import WebKit
import WebMetadataKit
private let log = Logger.browserLogger
class MetadataParserHelper: TabHelper {
private weak var tab: Tab?
private let profile: Profile
private var parser: WebMetadataParser?
class func name() -> String {
return "MetadataParserHelper"
}
required init(tab: Tab, profile: Profile) {
self.tab = tab
self.profile = profile
self.parser = WebMetadataParser()
self.parser?.addUserScriptsIntoWebView(tab.webView!)
}
func scriptMessageHandlerName() -> String? {
return "metadataMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let dict = message.body as? [String: AnyObject] else {
return
}
var userInfo = [String: AnyObject]()
userInfo["isPrivate"] = self.tab?.isPrivate ?? true
userInfo["metadata"] = dict
NSNotificationCenter.defaultCenter().postNotificationName(NotificationOnPageMetadataFetched, object: nil, userInfo: userInfo)
}
}
| mpl-2.0 | ea990347aa3e20e12073916cbc62fdc5 | 31.27907 | 133 | 0.691643 | 4.819444 | false | false | false | false |
coodly/ios-gambrinus | Packages/Sources/KioskCore/Config/Constants.swift | 1 | 927 | /*
* Copyright 2018 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
internal let RunningOnPad = UIDevice.current.userInterfaceIdiom == .pad
extension Notification.Name {
public static let postsSortChanged = Notification.Name(rawValue: "com.coodly.kiosk.posts.sort.changed")
public static let postsModification = Notification.Name(rawValue: "com.coodly.kiosk.posts.modification")
}
| apache-2.0 | 950c4686c3ab2fe0696fb7e51b058efa | 37.625 | 108 | 0.760518 | 4.138393 | false | false | false | false |
CodaFi/Bedrock | BedrockTests/ColorTests.swift | 1 | 1262 | //
// ColorTests.swift
// Bedrock
//
// Created by Robert S Mozayeni on 6/12/15.
// Copyright (c) 2015 Robert Mozayeni. All rights reserved.
//
import XCTest
import Bedrock
class ColorTests: XCTestCase {
func testExample() {
let color = Color(red: 0, green: 0, blue: 0, alpha: 0)
XCTAssertEqual(color.redComponent, 0, "IDEK") //Example
}
func testHexInit() {
scope {
let color = Color(hex: 0xFFFFFF0)
XCTAssertTrue(color == nil, "Hex init should be nil with out-of-range input") //XCTAssertNil doesn't work with structs
}
scope {
let color = Color(hex: 0xFFFFFF)
XCTAssertTrue(color != nil, "Should form from hex properly")
let (r,g,b,a) = color!.colorsA()
XCTAssertEqual(r == g, b == a)
XCTAssertEqual(r, 1.0)
}
scope {
let color = Color(hex: 0x000000)
XCTAssertTrue(color != nil, "Should form from hex properly")
let (r2,g2,b2,a2) = color!.colorsA()
XCTAssertEqual(r2 == g2, g2 == b2)
XCTAssertEqual(r2, 0)
XCTAssertEqual(a2, 1)
}
}
}
func scope(x: Void -> Void) {
x()
}
| mit | 75765b2af80cdbc6f95bda3dcba6434d | 25.291667 | 130 | 0.537242 | 3.733728 | false | true | false | false |
warrenm/slug-swift-metal | SwiftMetalDemo/MBEDemoOne.swift | 1 | 3995 | //
// MBEDemoOne.swift
// SwiftMetalDemo
//
// Created by Warren Moore on 10/23/14.
// Copyright (c) 2014 Warren Moore. All rights reserved.
//
import UIKit
class MBEDemoOneViewController : MBEDemoViewController {
var vertexBuffer: MTLBuffer! = nil
var uniformBuffer: MTLBuffer! = nil
var rotationAngle: Float = 0.0
override func buildPipeline() {
let library = device.makeDefaultLibrary()!
let vertexFunction = library.makeFunction(name: "vertex_demo_one")
let fragmentFunction = library.makeFunction(name: "fragment_demo_one")
let vertexDescriptor = MTLVertexDescriptor()
vertexDescriptor.attributes[0].offset = 0
vertexDescriptor.attributes[0].format = .float4
vertexDescriptor.attributes[0].bufferIndex = 0
vertexDescriptor.attributes[1].offset = MemoryLayout<ColorRGBA>.stride
vertexDescriptor.attributes[1].format = .float4
vertexDescriptor.attributes[1].bufferIndex = 0
vertexDescriptor.layouts[0].stepFunction = .perVertex
vertexDescriptor.layouts[0].stride = MemoryLayout<ColoredVertex>.stride
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.vertexDescriptor = vertexDescriptor
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipeline = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
commandQueue = device.makeCommandQueue()
}
override func buildResources() {
let vertices: [ColoredVertex] = [ ColoredVertex(position:Vector4(x: 0.000, y: 0.50, z: 0, w: 1),
color:ColorRGBA(r: 1, g: 0, b: 0, a: 1)),
ColoredVertex(position:Vector4(x: -0.433, y: -0.25, z: 0, w: 1),
color:ColorRGBA(r: 0, g: 1, b: 0, a: 1)),
ColoredVertex(position:Vector4(x: 0.433, y: -0.25, z: 0, w: 1),
color:ColorRGBA(r: 0, g: 0, b: 1, a: 1))]
vertexBuffer = device.makeBuffer(bytes: vertices, length: MemoryLayout<ColoredVertex>.stride * 3, options:[])
uniformBuffer = device.makeBuffer(length: MemoryLayout<Matrix4x4>.stride, options:[])
}
override func draw() {
if let drawable = metalLayer.nextDrawable() {
let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = drawable.texture
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1, 1, 1, 1)
passDescriptor.colorAttachments[0].loadAction = .clear
passDescriptor.colorAttachments[0].storeAction = .store
let zAxis = Vector4(x: 0, y: 0, z: -1, w: 0)
let rotationMatrix = [Matrix4x4.rotationAboutAxis(zAxis, byAngle: rotationAngle)]
memcpy(uniformBuffer.contents(), rotationMatrix, MemoryLayout<Matrix4x4>.stride)
let commandBuffer = commandQueue.makeCommandBuffer()
let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: passDescriptor)
commandEncoder?.setRenderPipelineState(pipeline)
commandEncoder?.setFrontFacing(.counterClockwise)
commandEncoder?.setCullMode(.back)
commandEncoder?.setVertexBuffer(vertexBuffer, offset:0, index:0)
commandEncoder?.setVertexBuffer(uniformBuffer, offset:0, index:1)
commandEncoder?.drawPrimitives(type: .triangle, vertexStart:0, vertexCount:3)
commandEncoder?.endEncoding()
commandBuffer?.present(drawable)
commandBuffer?.commit()
rotationAngle += 0.01
}
}
}
| mit | 15f13f8a625e89271b0c8efcd6cc8597 | 44.397727 | 117 | 0.627284 | 5.025157 | false | false | false | false |
gustavoavena/BandecoUnicamp | BandecoUnicamp/NotificationTimeViewController.swift | 1 | 3405 | //
// NotificationTimeViewController.swift
// BandecoUnicamp
//
// Created by Julianny Favinha on 1/11/18.
// Copyright © 2018 Gustavo Avena. All rights reserved.
//
import UIKit
protocol NotificationTimeDisplayDelegate {
func updateTimeString(time: String, refeicao: TipoRefeicao)
}
class NotificationTimeViewController: UIViewController {
var refeicao: TipoRefeicao!
var selectedTime: String!
var notificationTimeDisplayDelegate: NotificationTimeDisplayDelegate?
@IBOutlet weak var pickerView: UIPickerView!
/*
Almoco: 07:00-13:59
Jantar: 14:00-19:00
*/
let ALMOCO_TIME_OPTIONS = [
NENHUMA_NOTIFICACAO_STRING, "7:00", "7:30",
"8:00", "8:30",
"9:00", "9:30",
"10:00", "10:30",
"11:00", "11:30",
"12:00", "12:30",
"13:00", "13:30",
"14:00"
]
let JANTAR_TIME_OPTIONS = [
NENHUMA_NOTIFICACAO_STRING, "14:00", "14:30",
"15:00", "15:30",
"16:00", "16:30",
"17:00", "17:30",
"18:00", "18:30",
"19:00"
]
var pickerTimeOptions: [String]!
override func viewDidLoad() {
super.viewDidLoad()
let currentNotificationTime: String? = UserDefaults.standard.object(forKey: refeicao == .almoco ? ALMOCO_TIME_KEY_STRING : JANTAR_TIME_KEY_STRING) as? String
if let currentTime = currentNotificationTime, let row = pickerTimeOptions!.index(of: currentTime) {
self.pickerView.selectRow(row, inComponent: 0, animated: true)
} else {
self.pickerView.selectRow(0, inComponent: 0, animated: true)
}
print("Recebi cardapio \(self.refeicao.rawValue)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
print("Usuário definiu horário \(selectedTime)")
// so salva quando o usuario realmente terminar de escolher e o VC for desaparecer.
OperationQueue.main.addOperation {
UserDefaults.standard.set(self.selectedTime, forKey: self.refeicao == .almoco ? ALMOCO_TIME_KEY_STRING : JANTAR_TIME_KEY_STRING)
CardapioServices.shared.registerDeviceToken()
}
}
}
extension NotificationTimeViewController: UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerTimeOptions.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.pickerTimeOptions[row]
}
}
extension NotificationTimeViewController: UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedTime = self.pickerTimeOptions[row]
if let delegate = self.notificationTimeDisplayDelegate {
OperationQueue.main.addOperation {
delegate.updateTimeString(time: self.pickerTimeOptions[row], refeicao: self.refeicao)
}
}
print("Usuário selecionou horário \(selectedTime)")
}
}
| mit | f6bdc49d696d03c31dfd1d90aa6b1a1c | 29.357143 | 165 | 0.624118 | 4.062127 | false | false | false | false |
ripventura/VCHTTPConnect | Example/Pods/EFQRCode/Source/BCHUtil.swift | 2 | 2384 | //
// BCHUtil.swift
// EFQRCode
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS) || os(macOS)
#else
struct BCHUtil {
private static let g15 = 0b10100110111
private static let g18 = 0b1111100100101
private static let g15Mask = 0b101010000010010
private static let g15BCHDigit = bchDigit(of: g15)
private static let g18BCHDigit = bchDigit(of: g18)
static func bchTypeInfo(of data: Int) -> Int {
var d = data << 10
while bchDigit(of: d) - g15BCHDigit >= 0 {
d ^= (g15 << (bchDigit(of: d) - g15BCHDigit))
}
return ((data << 10) | d) ^ g15Mask
}
static func bchTypeNumber(of data: Int) -> Int {
var d = data << 12
while bchDigit(of: d) - g18BCHDigit >= 0 {
d ^= (g18 << (bchDigit(of: d) - g18BCHDigit))
}
return (data << 12) | d
}
private static func bchDigit(of data: Int) -> Int {
var digit = 0
var data = UInt(data)
while (data != 0) {
digit += 1
data >>= 1
}
return digit
}
}
#endif
| mit | e04dfe17a750d5f8b76b7cace4ead415 | 37.451613 | 81 | 0.613674 | 3.94702 | false | false | false | false |
chrisjmendez/swift-exercises | Menus/Pinterest/PinterestSwift/CHTCollectionViewWaterfallLayout.swift | 1 | 14833 | //
// CHTCollectionViewWaterfallLayout.swift
// PinterestSwift
//
// Created by Nicholas Tau on 6/30/14.
// Copyright (c) 2014 Nicholas Tau. All rights reserved.
//
import Foundation
import UIKit
@objc protocol CHTCollectionViewDelegateWaterfallLayout: UICollectionViewDelegate{
func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
optional func colletionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForHeaderInSection section: NSInteger) -> CGFloat
optional func colletionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForFooterInSection section: NSInteger) -> CGFloat
optional func colletionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: NSInteger) -> UIEdgeInsets
optional func colletionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: NSInteger) -> CGFloat
}
enum CHTCollectionViewWaterfallLayoutItemRenderDirection : NSInteger{
case CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst
case CHTCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight
case CHTCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft
}
class CHTCollectionViewWaterfallLayout : UICollectionViewLayout{
let CHTCollectionElementKindSectionHeader = "CHTCollectionElementKindSectionHeader"
let CHTCollectionElementKindSectionFooter = "CHTCollectionElementKindSectionFooter"
var columnCount : NSInteger{
didSet{
invalidateLayout()
}}
var minimumColumnSpacing : CGFloat{
didSet{
invalidateLayout()
}}
var minimumInteritemSpacing : CGFloat{
didSet{
invalidateLayout()
}}
var headerHeight : CGFloat{
didSet{
invalidateLayout()
}}
var footerHeight : CGFloat{
didSet{
invalidateLayout()
}}
var sectionInset : UIEdgeInsets{
didSet{
invalidateLayout()
}}
var itemRenderDirection : CHTCollectionViewWaterfallLayoutItemRenderDirection{
didSet{
invalidateLayout()
}}
// private property and method above.
weak var delegate : CHTCollectionViewDelegateWaterfallLayout?{
get{
return self.collectionView!.delegate as? CHTCollectionViewDelegateWaterfallLayout
}
}
var columnHeights : NSMutableArray
var sectionItemAttributes : NSMutableArray
var allItemAttributes : NSMutableArray
var headersAttributes : NSMutableDictionary
var footersAttributes : NSMutableDictionary
var unionRects : NSMutableArray
let unionSize = 20
override init(){
self.headerHeight = 0.0
self.footerHeight = 0.0
self.columnCount = 2
self.minimumInteritemSpacing = 10
self.minimumColumnSpacing = 10
self.sectionInset = UIEdgeInsetsZero
self.itemRenderDirection =
CHTCollectionViewWaterfallLayoutItemRenderDirection.CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst
headersAttributes = NSMutableDictionary()
footersAttributes = NSMutableDictionary()
unionRects = NSMutableArray()
columnHeights = NSMutableArray()
allItemAttributes = NSMutableArray()
sectionItemAttributes = NSMutableArray()
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func itemWidthInSectionAtIndex (section : NSInteger) -> CGFloat {
let width:CGFloat = self.collectionView!.frame.size.width - sectionInset.left-sectionInset.right
let spaceColumCount:CGFloat = CGFloat(self.columnCount-1)
return floor((width - (spaceColumCount*self.minimumColumnSpacing)) / CGFloat(self.columnCount))
}
override func prepareLayout(){
super.prepareLayout()
let numberOfSections = self.collectionView!.numberOfSections()
if numberOfSections == 0 {
return
}
self.headersAttributes.removeAllObjects()
self.footersAttributes.removeAllObjects()
self.unionRects.removeAllObjects()
self.columnHeights.removeAllObjects()
self.allItemAttributes.removeAllObjects()
self.sectionItemAttributes.removeAllObjects()
var idx = 0
while idx<self.columnCount{
self.columnHeights.addObject(0)
idx++
}
var top : CGFloat = 0.0
var attributes = UICollectionViewLayoutAttributes()
for var section = 0; section < numberOfSections; ++section{
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
var minimumInteritemSpacing : CGFloat
if let miniumSpaceing = self.delegate?.colletionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAtIndex: section){
minimumInteritemSpacing = miniumSpaceing
}else{
minimumInteritemSpacing = self.minimumColumnSpacing
}
let width = self.collectionView!.frame.size.width - sectionInset.left - sectionInset.right
let spaceColumCount = CGFloat(self.columnCount-1)
let itemWidth = floor((width - (spaceColumCount*self.minimumColumnSpacing)) / CGFloat(self.columnCount))
/*
* 2. Section header
*/
var heightHeader : CGFloat
if let height = self.delegate?.colletionView?(self.collectionView!, layout: self, heightForHeaderInSection: section){
heightHeader = height
}else{
heightHeader = self.headerHeight
}
if heightHeader > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKindSectionHeader, withIndexPath: NSIndexPath(forRow: 0, inSection: section))
attributes.frame = CGRectMake(0, top, self.collectionView!.frame.size.width, heightHeader)
self.headersAttributes.setObject(attributes, forKey: (section))
self.allItemAttributes.addObject(attributes)
top = CGRectGetMaxX(attributes.frame)
}
top += sectionInset.top
for var idx = 0; idx < self.columnCount; idx++ {
self.columnHeights[idx]=top;
}
/*
* 3. Section items
*/
let itemCount = self.collectionView!.numberOfItemsInSection(section)
let itemAttributes = NSMutableArray(capacity: itemCount)
// Item will be put into shortest column.
for var idx = 0; idx < itemCount; idx++ {
let indexPath = NSIndexPath(forItem: idx, inSection: section)
let columnIndex = self.nextColumnIndexForItem(idx)
let xOffset = sectionInset.left + (itemWidth + self.minimumColumnSpacing) * CGFloat(columnIndex)
let yOffset = self.columnHeights.objectAtIndex(columnIndex).doubleValue
let itemSize = self.delegate?.collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: indexPath)
var itemHeight : CGFloat = 0.0
if itemSize?.height > 0 && itemSize?.width > 0 {
itemHeight = floor(itemSize!.height*itemWidth/itemSize!.width)
}
attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = CGRectMake(xOffset, CGFloat(yOffset), itemWidth, itemHeight)
itemAttributes.addObject(attributes)
self.allItemAttributes.addObject(attributes)
self.columnHeights[columnIndex]=CGRectGetMaxY(attributes.frame) + minimumInteritemSpacing;
}
self.sectionItemAttributes.addObject(itemAttributes)
/*
* 4. Section footer
*/
var footerHeight : CGFloat = 0.0
let columnIndex = self.longestColumnIndex()
top = CGFloat(self.columnHeights.objectAtIndex(columnIndex).floatValue) - minimumInteritemSpacing + sectionInset.bottom
if let height = self.delegate?.colletionView?(self.collectionView!, layout: self, heightForFooterInSection: section){
footerHeight = height
}else{
footerHeight = self.footerHeight
}
if footerHeight > 0 {
attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CHTCollectionElementKindSectionFooter, withIndexPath: NSIndexPath(forItem: 0, inSection: section))
attributes.frame = CGRectMake(0, top, self.collectionView!.frame.size.width, footerHeight)
self.footersAttributes.setObject(attributes, forKey: section)
self.allItemAttributes.addObject(attributes)
top = CGRectGetMaxY(attributes.frame)
}
for var idx = 0; idx < self.columnCount; idx++ {
self.columnHeights[idx] = top
}
}
idx = 0;
let itemCounts = self.allItemAttributes.count
while(idx < itemCounts){
let rect1 = self.allItemAttributes.objectAtIndex(idx).frame as CGRect
idx = min(idx + unionSize, itemCounts) - 1
let rect2 = self.allItemAttributes.objectAtIndex(idx).frame as CGRect
self.unionRects.addObject(NSValue(CGRect:CGRectUnion(rect1,rect2)))
idx++
}
}
override func collectionViewContentSize() -> CGSize{
let numberOfSections = self.collectionView!.numberOfSections()
if numberOfSections == 0{
return CGSizeZero
}
var contentSize = self.collectionView!.bounds.size as CGSize
let height = self.columnHeights.objectAtIndex(0) as! NSNumber
contentSize.height = CGFloat(height.doubleValue)
return contentSize
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?{
if indexPath.section >= self.sectionItemAttributes.count{
return nil
}
if indexPath.item >= self.sectionItemAttributes.objectAtIndex(indexPath.section).count{
return nil;
}
let list = self.sectionItemAttributes.objectAtIndex(indexPath.section) as! NSArray
return list.objectAtIndex(indexPath.item) as? UICollectionViewLayoutAttributes
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes{
var attribute = UICollectionViewLayoutAttributes()
if elementKind == CHTCollectionElementKindSectionHeader{
attribute = self.headersAttributes.objectForKey(indexPath.section) as! UICollectionViewLayoutAttributes
}else if elementKind == CHTCollectionElementKindSectionFooter{
attribute = self.footersAttributes.objectForKey(indexPath.section) as! UICollectionViewLayoutAttributes
}
return attribute
}
override func layoutAttributesForElementsInRect (rect : CGRect) -> [UICollectionViewLayoutAttributes] {
var begin = 0, end = self.unionRects.count
let attrs = NSMutableArray()
for var i = 0; i < end; i++ {
if CGRectIntersectsRect(rect, self.unionRects.objectAtIndex(i).CGRectValue){
begin = i * unionSize;
break
}
}
for var i = self.unionRects.count - 1; i>=0; i-- {
if CGRectIntersectsRect(rect, self.unionRects.objectAtIndex(i).CGRectValue){
end = min((i+1)*unionSize,self.allItemAttributes.count)
break
}
}
for var i = begin; i < end; i++ {
let attr = self.allItemAttributes.objectAtIndex(i) as! UICollectionViewLayoutAttributes
if CGRectIntersectsRect(rect, attr.frame) {
attrs.addObject(attr)
}
}
return NSArray(array: attrs) as! [UICollectionViewLayoutAttributes]
}
override func shouldInvalidateLayoutForBoundsChange (newBounds : CGRect) -> Bool {
let oldBounds = self.collectionView!.bounds
if CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds){
return true
}
return false
}
/**
* Find the shortest column.
*
* @return index for the shortest column
*/
func shortestColumnIndex () -> NSInteger {
var index = 0
var shorestHeight = MAXFLOAT
self.columnHeights.enumerateObjectsUsingBlock({(object : AnyObject, idx : NSInteger,pointer :UnsafeMutablePointer<ObjCBool>) in
let height = object.floatValue
if (height<shorestHeight){
shorestHeight = height
index = idx
}
})
return index
}
/**
* Find the longest column.
*
* @return index for the longest column
*/
func longestColumnIndex () -> NSInteger {
var index = 0
var longestHeight:CGFloat = 0.0
self.columnHeights.enumerateObjectsUsingBlock({(object : AnyObject, idx : NSInteger,pointer :UnsafeMutablePointer<ObjCBool>) in
let height = CGFloat(object.floatValue)
if (height > longestHeight){
longestHeight = height
index = idx
}
})
return index
}
/**
* Find the index for the next column.d *
* @return index for the next column
*/
func nextColumnIndexForItem (item : NSInteger) -> Int {
var index = 0
switch (self.itemRenderDirection){
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionShortestFirst :
index = self.shortestColumnIndex()
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionLeftToRight :
index = (item%self.columnCount)
case .CHTCollectionViewWaterfallLayoutItemRenderDirectionRightToLeft:
index = (self.columnCount - 1) - (item % self.columnCount);
default:
index = self.shortestColumnIndex()
}
return index
}
} | mit | 32072a3b6a891b4d732c0a5149f47fec | 38.876344 | 188 | 0.647812 | 5.731453 | false | false | false | false |
myste1tainn/nUI | Pod/Classes/nUIImageView.swift | 2 | 3883 | //
// nUIImageView.swift
// Pods
//
// Created by A. Keereena on 3/4/16.
//
//
import UIKit
public protocol nUIImageViewDelegate {
func imageView(_ imageView: nUIImageView, willSetImage image: UIImage)
func imageView(_ imageView: nUIImageView, didSetImage image: UIImage)
}
@IBDesignable
open class nUIImageView: UIImageView {
open var delegate: nUIImageViewDelegate?
open override var image: UIImage? {
didSet {
guard
let _ = delegate,
let _ = image
else { return }
delegate?.imageView(self, didSetImage: image!)
}
}
// MARK: - Designable view manipulation
@IBInspectable open var circle: Bool = false
@IBInspectable open var borderRadiusAsRatio: Bool = false
@IBInspectable open var borderColor: UIColor = UIColor.clear
@IBInspectable open var borderWidth: CGFloat = 0.0
@IBInspectable open var borderRadius: CGFloat = 0.0
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if circle {
let smallerOne = Math.smallerOneA(frame.size.width, orB: frame.size.height)
layer.cornerRadius = smallerOne / 2
clipsToBounds = true
}
if borderRadius > 0
{
let cornerRadius = borderRadiusAsRatio ? frame.size.height * borderRadius : borderRadius
layer.cornerRadius = cornerRadius
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
clipsToBounds = true
}
}
open func setImageWithURL(_ url: URL, doCache cache: Bool = true) {
let imageCache = nUIImageCache.defaultCache()
if let image = imageCache.imageForURL(url) {
self.image = image
} else {
let mainQueue = OperationQueue.main
self.showActivityIndicator()
URLSession.shared
.dataTask(
with: url,
completionHandler: { (data, _, error) -> Void in
let setImageblock = BlockOperation { () -> Void in
// Whether setting image success/fails remove the activity indicator
defer {
self.hideActivityIndicator()
}
// Parse data to image with guard
guard
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
// Set the downloaded image
self.image = image
// Do cache, if needed
if cache {
imageCache.cacheImage(image, withURL: url)
}
}
mainQueue.addOperation(setImageblock)
}
).resume()
}
}
/// Return height that fits the current view's width as compared to
/// actual image width so that it fits perfectly into view
open func heightThatFits() -> CGFloat {
if let _ = self.image {
let ratio = self.frame.size.width / self.image!.size.width
let expectedViewHeight = self.image!.size.height * ratio
return expectedViewHeight
} else {
return 0
}
}
}
| mit | e082a80959b0fa6f83234c2b7abe54d6 | 32.188034 | 100 | 0.501931 | 5.727139 | false | false | false | false |
trill-lang/trill | Sources/IRGen/TypeIRGen.swift | 2 | 11570 | ///
/// TypeIRGen.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import AST
import LLVM
import Foundation
extension IRGenerator {
/// Declares the prototypes of all methods and initializers,
/// and deinitializer, in a type.
/// - parameters:
/// - expr: The TypeDecl to declare.
@discardableResult
func codegenTypePrototype(_ expr: TypeDecl) -> IRType {
if let existing = module.type(named: expr.name.name) {
return existing
}
let structure = builder.createStruct(name: expr.name.name)
typeIRBindings[expr.type] = structure
let fieldTypes = expr.storedProperties
.map { resolveLLVMType($0.type) }
structure.setBody(fieldTypes)
for method in expr.methods + expr.staticMethods {
codegenFunctionPrototype(method)
}
if let deinitiailizer = expr.deinitializer {
codegenFunctionPrototype(deinitiailizer)
}
return structure
}
/// Generates type metadata for a given protocol and caches it.
///
/// These are layout-compatible with the structs declared in
/// `metadata_private.h`, namely:
///
/// ```
/// typedef struct ProtocolMetadata {
/// const char *name;
/// const char **methodNames;
/// size_t methodCount;
/// } ProtocolMetadata;
/// ```
/// There is a unique metadata record for every protocol at compile time.
func codegenProtocolMetadata(_ proto: ProtocolDecl) -> Global {
let symbol = Mangler.mangle(proto) + ".metadata"
if let cached = module.global(named: symbol) { return cached }
let name = builder.buildGlobalStringPtr(proto.name.name)
let methodNames = proto.methods.map { $0.formattedName }.map {
builder.buildGlobalStringPtr($0)
}
let methodNamesType = ArrayType(elementType: PointerType.toVoid,
count: proto.methods.count)
var metaNames = builder.addGlobal("\(symbol).methods", type: methodNamesType)
metaNames.initializer = ArrayType.constant(methodNames, type: PointerType.toVoid)
let metadata = StructType.constant(values: [
name,
builder.buildBitCast(metaNames, type: PointerType.toVoid),
IntType.int64.constant(proto.methods.count)
])
var metaGlobal = builder.addGlobal(symbol, type: metadata.type)
metaGlobal.initializer = metadata
return metaGlobal
}
/// Generates type metadata for a given type and caches it.
///
/// These are layout-compatible with the structs declared in
/// `metadata_private.h`, namely:
///
/// ```
/// typedef struct FieldMetadata {
/// const char *name;
/// const void *type;
/// } FieldMetadata;
///
/// typedef struct TypeMetadata {
/// const char *name;
/// const void *fields;
/// uint8_t isReferenceType;
/// uint64_t sizeInBits;
/// uint64_t fieldCount;
/// uint64_t pointerLevel;
/// } TypeMetadata;
/// ```
///
/// There is a unique metadata record for every type at compile time.
func codegenTypeMetadata(_ type: DataType) -> Global {
let type = context.canonicalType(type)
if let cached = typeMetadataMap[type] { return cached }
var pointerLevel = 0
let fullName = type.description
let name = Mangler.mangle(type)
var properties = [(String, DataType)]()
switch type {
case .pointer:
pointerLevel = type.pointerLevel()
case .custom:
guard let decl = context.decl(for: type) else {
fatalError("no decl?")
}
properties = decl.storedProperties
.map { ($0.name.name, $0.type) }
case .tuple(let types):
properties = types.enumerated().map { (".\($0.offset)", $0.element) }
default:
break
}
var irType = resolveLLVMType(type)
var isIndirect = storage(for: type) == .reference
if case .custom = type, let pointerType = irType as? PointerType {
isIndirect = true
irType = pointerType.pointee
}
let metaName = name + ".metadata"
let nameValue = codegenGlobalStringPtr(fullName).ptr
let elementPtrs: [IRType] = [
nameValue.type, // name string
PointerType.toVoid, // field types
IntType.int8, // isReferenceType
IntType.int64, // size of type
IntType.int64, // number of fields
IntType.int64 // pointer level
]
let metaType = StructType(elementTypes: elementPtrs)
var global = builder.addGlobal(metaName, type: metaType)
typeMetadataMap[type] = global
let propertyMetaType = StructType(elementTypes: [
PointerType.toVoid, // name string
PointerType.toVoid, // field type metadata
IntType.int64 // field count
])
var propertyVals = [IRValue]()
for (idx, (propName, type)) in properties.enumerated() {
let meta = codegenTypeMetadata(type)
let name = codegenGlobalStringPtr(propName).ptr
propertyVals.append(StructType.constant(values: [
builder.buildBitCast(name, type: PointerType.toVoid),
builder.buildBitCast(meta, type: PointerType.toVoid),
IntType.int64.constant(
layout.offsetOfElement(at: idx, type: irType as! StructType))
]))
}
let propVec = ArrayType.constant(propertyVals, type: propertyMetaType)
var globalFieldVec = builder.addGlobal("\(metaName).fields.metadata", type: propVec.type)
globalFieldVec.initializer = propVec
let gep = builder.buildInBoundsGEP(globalFieldVec, indices: [IntType.int64.zero()])
global.initializer = StructType.constant(values: [
nameValue,
builder.buildBitCast(gep, type: PointerType.toVoid),
IntType.int8.constant(isIndirect ? 1 : 0, signExtend: true),
IntType.int64.constant(layout.sizeOfTypeInBits(irType), signExtend: true),
IntType.int64.constant(properties.count, signExtend: true),
IntType.int64.constant(pointerLevel, signExtend: true),
])
return global
}
/// Declares the prototypes of all methods in an extension.
/// - parameters:
/// - expr: The ExtensionDecl to declare.
func codegenExtensionPrototype(_ expr: ExtensionDecl) {
for method in expr.methods + expr.staticMethods {
codegenFunctionPrototype(method)
}
}
@discardableResult
public func visitTypeDecl(_ expr: TypeDecl) -> Result {
codegenTypePrototype(expr)
// Visit the synthesized initializers of a type
_ = expr.initializers.map(visitFuncDecl)
if expr.has(attribute: .foreign) { return nil }
_ = expr.methods.map(visitFuncDecl)
_ = expr.deinitializer.map(visitFuncDecl)
_ = expr.subscripts.map(visitFuncDecl)
_ = expr.staticMethods.map(visitFuncDecl)
_ = expr.properties.map(visitPropertyDecl)
_ = codegenWitnessTables(expr)
return nil
}
@discardableResult
public func visitExtensionDecl(_ expr: ExtensionDecl) -> Result {
for method in expr.methods + expr.staticMethods {
_ = visit(method)
}
for subscriptDecl in expr.subscripts {
_ = visit(subscriptDecl)
}
return nil
}
/// Gives a valid pointer to any given Expr.
/// PropertyRefExpr: If the property is a computed property with a getter,
/// it will execute the getter, store the result in a
/// stack variable, and give a pointer to that.
/// Otherwise it will yield a getelementptr instruction to
/// the specific field.
/// VarExpr: it'll look through any variable bindings to find the
/// pointer that represents the value. For reference bindings, it'll
/// yield the underlying pointer. For value bindings, it'll yield the
/// global or stack binding.
/// Dereference: It will get a pointer to the dereferenced value and load it
/// Subscript: It will codegen the argument and get the pointer it represents,
/// and build a getelementptr for the offset.
/// Anything else: It will create a new stack object and return that pointer.
/// This allows you to call a method on an rvalue, even though
/// it doesn't necessarily have a stack variable.
func resolvePtr(_ expr: Expr) -> IRValue {
let createTmpPointer: (Expr) -> IRValue = { expr in
let type = expr.type
guard type != .error else { fatalError("error type in resolvePtr") }
let value = self.visit(expr)!
if case .any = self.context.canonicalType(type) {
return self.codegenAnyValuePtr(value, type: .pointer(type: .int8))
}
let irType = self.resolveLLVMType(type)
let alloca = self.createEntryBlockAlloca(self.currentFunction!.functionRef!,
type: irType, name: "ptrtmp",
storage: .value)
self.builder.buildStore(value, to: alloca.ref)
return alloca.ref
}
switch expr.semanticsProvidingExpr {
case let expr as PropertyRefExpr:
// If we need to indirect through a property getter, then apply the
// getter and store the result in a temporary mutable variable
if let decl = expr.decl as? PropertyDecl, decl.getter != nil {
return createTmpPointer(expr)
}
return elementPtr(expr)
case let expr as VarExpr:
guard let binding = resolveVarBinding(expr) else {
fatalError("no binding?")
}
return binding.ref
case let expr as PrefixOperatorExpr where expr.op == .star:
return builder.buildLoad(resolvePtr(expr.rhs), name: "deref-load")
case let expr as TupleFieldLookupExpr:
let lhs = resolvePtr(expr.lhs)
return builder.buildStructGEP(lhs, index: expr.field, name: "tuple-ptr")
case let expr as CoercionExpr:
if case .any = context.canonicalType(expr.type) {
return codegenAnyValuePtr(visit(expr)!, type: expr.rhs.type)
}
return createTmpPointer(expr)
case let expr as SubscriptExpr:
let lhs = visit(expr.lhs)!
switch expr.lhs.type {
case .pointer, .array:
return builder.buildGEP(lhs, indices: [visit(expr.args[0].val)!],
name: "gep")
default:
return createTmpPointer(expr)
}
default:
return createTmpPointer(expr)
}
}
/// Builds a getelementptr instruction for a PropertyRefExpr.
/// This will perform the arithmetic necessary to get at a struct field.
func elementPtr(_ expr: PropertyRefExpr) -> IRValue {
guard let decl = expr.typeDecl else { fatalError("unresolved type") }
guard let idx = decl.indexOfProperty(named: expr.name) else {
fatalError("invalid index in decl fields")
}
var ptr = resolvePtr(expr.lhs)
let isImplicitSelf = (expr.lhs as? VarExpr)?.isSelf ?? false
if case .reference = storage(for: expr.lhs.type),
!isImplicitSelf {
ptr = builder.buildLoad(ptr, name: "\(expr.name)-load")
}
return builder.buildStructGEP(ptr, index: idx, name: "\(expr.name)-gep")
}
public func visitPropertyRefExpr(_ expr: PropertyRefExpr) -> Result {
if let propDecl = expr.decl as? PropertyDecl,
let getterDecl = propDecl.getter {
let implicitSelf = resolvePtr(expr.lhs)
let getterFn = codegenFunctionPrototype(getterDecl)
return builder.buildCall(getterFn, args: [implicitSelf])
}
return builder.buildLoad(elementPtr(expr), name: expr.name.name)
}
}
| mit | 8681e79a01c3daf42911bbdfc64e75bb | 35.730159 | 93 | 0.649092 | 4.184448 | false | false | false | false |
dengJunior/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendView.swift | 1 | 12911 | //
// CBRecommendView.swift
// TestKitchen
//
// Created by 邓江洲 on 16/8/17.
// Copyright © 2016年 邓江洲. All rights reserved.
//
import UIKit
//实现通用,不用写死。代理和协议
class CBRecommendView: UIView , UITableViewDelegate , UITableViewDataSource{
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var clickClosure: CBCellClosure?
private var tbView: UITableView?
var model :CBRecommendModel?{
didSet{
tbView?.reloadData()
}
}
init(){
super.init(frame: CGRectZero)
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
tbView?.separatorStyle = .None
self.addSubview(tbView!)
tbView?.snp_makeConstraints(closure: { [weak self] (make) in
make.edges.equalTo(self!)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- tableView
extension CBRecommendView{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var sectionNum = 1
if model?.data?.widgetList?.count > 0{
sectionNum += (model?.data?.widgetList?.count)!
}
return sectionNum
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNum = 0
if section == 0{
if model?.data?.banner?.count>0{
rowNum = 1
}
}else{
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYourLike.rawValue{
rowNum = 1
} else if listModel?.widget_type?.integerValue == WidgetType.RedPackage.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Scene.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
rowNum = (listModel?.widget_data?.count)!/4
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
rowNum = (listModel?.widget_data?.count)!/3
}
}
return rowNum
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height: CGFloat = 0
if indexPath.section == 0{
if model?.data?.banner?.count>0{
height = 160
}
}else{
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYourLike.rawValue{
height = 80
} else if listModel?.widget_type?.integerValue == WidgetType.RedPackage.rawValue{
height = 80
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
height = 300
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
height = 200
}else if listModel?.widget_type?.integerValue == WidgetType.Scene.rawValue{
height = 60
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
height = 80
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
height = 240
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
height = 180
}
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if indexPath.section == 0{
if model?.data?.banner?.count > 0{
cell = CBRecommendADCell.createADCellFor(tableView, arIndexPath: indexPath, withModel: model!, cellClosure: clickClosure)
}
}else{
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYourLike.rawValue{
cell = CBRecommendLikeCell.createLikeCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.RedPackage.rawValue{
cell = CBRedPacketCell.createRedPackageCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
cell = CBRecommendNewCell.createNewCellForTableView(tableView, atIndexPath: indexPath, wirhListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
cell = CBSpecialCell.createSpecialCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Scene.rawValue{
cell = CBSceneCell.createSceneCell(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
cell = CBTalentCell.createTalentCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
cell = CBWorksCell.createWorksCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
cell = CBSubjectCell.createSubjectCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}
}
return cell
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headView: UIView? = nil
if section>0{
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYourLike.rawValue{
headView = CBSearchHeaderView(frame: CGRectMake(0,0,kScreenWidth,44))
} else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue || listModel?.widget_type?.integerValue == WidgetType.Special.rawValue || listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue || listModel?.widget_type?.integerValue == WidgetType.Works.rawValue || listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue {
let tempView = CBHeaderView(frame: CGRectMake(0,0,kScreenWidth,44))
tempView.configTitle((listModel?.title)!)
headView = tempView
}
}
return headView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var height:CGFloat = 0
if section > 0{
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYourLike.rawValue || listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue || listModel?.widget_type?.integerValue == WidgetType.Special.rawValue || listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue || listModel?.widget_type?.integerValue == WidgetType.Works.rawValue || listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue {
height = 44
}
}
return height
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let h: CGFloat = 44
if scrollView.contentOffset.y > h{
scrollView.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0)
}else if scrollView.contentOffset.y > 0 {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0,0 , 0)
}
}
} | mit | 08adcf938827d588b3b9cd0fec1e11ba | 23.323251 | 441 | 0.417224 | 7.163697 | false | false | false | false |
edekhayser/FrostedSidebar | FrostedSidebar/TabBarController.swift | 1 | 2011 | //
// TabBarController.swift
// FrostedSidebar
//
// Created by Evan Dekhayser on 8/28/14.
// Copyright (c) 2014 Evan Dekhayser. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
var sidebar: FrostedSidebar!
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
tabBar.isHidden = true
moreNavigationController.navigationBar.isHidden = true
sidebar = FrostedSidebar(itemImages: [
UIImage(named: "gear")!,
UIImage(named: "globe")!,
UIImage(named: "profile")!,
UIImage(named: "profile")!,
UIImage(named: "profile")!,
UIImage(named: "profile")!,
UIImage(named: "star")!],
colors: [
UIColor(red: 240/255, green: 159/255, blue: 254/255, alpha: 1),
UIColor(red: 255/255, green: 137/255, blue: 167/255, alpha: 1),
UIColor(red: 126/255, green: 242/255, blue: 195/255, alpha: 1),
UIColor(red: 126/255, green: 242/255, blue: 195/255, alpha: 1),
UIColor(red: 126/255, green: 242/255, blue: 195/255, alpha: 1),
UIColor(red: 126/255, green: 242/255, blue: 195/255, alpha: 1),
UIColor(red: 119/255, green: 152/255, blue: 255/255, alpha: 1)],
selectionStyle: .single)
sidebar.actionForIndex = [
0: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 0}) },
1: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 1}) },
2: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 2}) },
3: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 3}) },
4: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 4}) },
5: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 5}) },
6: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 6}) },
7: {self.sidebar.dismissAnimated(true, completion: { finished in self.selectedIndex = 7}) }]
}
}
| mit | 334502f8cb104613897501e2529994cf | 39.22 | 95 | 0.68722 | 3.414261 | false | false | false | false |
manavgabhawala/swift | stdlib/public/core/Builtin.swift | 1 | 31081 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
@available(*, unavailable, message: "use MemoryLayout<T>.size instead.")
public func sizeof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.size(ofValue:)")
public func sizeofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.alignment instead.")
public func alignof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.alignment(ofValue:)")
public func alignofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use MemoryLayout<T>.stride instead.")
public func strideof<T>(_:T.Type) -> Int {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "MemoryLayout.stride(ofValue:)")
public func strideofValue<T>(_:T) -> Int {
Builtin.unreachable()
}
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@_versioned
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@_versioned
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@_versioned
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Only use this function to convert the instance passed as `x` to a
/// layout-compatible type when the conversion is not possible through other
/// means. Common conversions that are supported by the standard library
/// include the following:
///
/// - To convert an integer value from one type to another, use an initializer
/// or the `numericCast(_:)` function.
/// - To perform a bitwise conversion of an integer value to a different type,
/// use an `init(bitPattern:)` or `init(truncatingBitPattern:)` initializer.
/// - To convert between a pointer and an integer value with that bit pattern,
/// or vice versa, use the `init(bitPattern:)` initializer for the
/// destination type.
/// - To perform a reference cast, use the casting operators (`as`, `as!`, or
/// `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of Swift's type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_transparent
func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_transparent
func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_versioned @_transparent internal
func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@_versioned
@_silgen_name("_swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@_versioned
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddress(of object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.")
public func unsafeAddressOf(_ object: AnyObject) -> UnsafeRawPointer {
Builtin.unreachable()
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as! T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_versioned
@_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@_versioned
@_silgen_name("swift_objc_class_usesNativeSwiftReferenceCounting")
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@_versioned
@inline(__always)
func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(s390x)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@_versioned
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@_versioned
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@_versioned
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@_versioned
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@_versioned
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_versioned
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@_versioned
@_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@_versioned
@_transparent
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
@available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.")
public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T {
Builtin.unreachable()
}
/// Extract an object reference from an Any known to contain an object.
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_sanityCheck(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// With a SIL instruction, we could more efficiently grab the object reference
// out of the Any's inline storage.
// On Linux, bridging isn't supported, so this is a force cast.
#if _runtime(_ObjC)
return any as AnyObject
#else
return any as! AnyObject
#endif
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// may be nested inside its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any`, the type
/// declared for the parameter, and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other non-protocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley : Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function, so `type(of:)` can only produce the
/// concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of the dynamic type inside the parameter, `String.self`.
///
/// func printGenericInfo<T>(_ value: T) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let type = type(of: value as Any)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value to find the dynamic type of.
/// - Returns: The dynamic type, which is a value of metatype type.
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function, but
/// even so it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily-escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve this, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed as `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameter closure: A non-escaping closure value that will be made
/// escapable for the duration of the execution of the `body` closure. If
/// `body` has a return value, it is used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - Parameter body: A closure that will be immediately executed, receiving an
/// escapable copy of `closure` as an argument.
/// - Returns: The return value of the `body` closure, if any.
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
| apache-2.0 | 2350e0d1cb4632bafe8d3d04a5ba5102 | 35.731678 | 110 | 0.685857 | 4.058378 | false | false | false | false |
PonyGroup/PonyChatUI-Swift | PonyChatUIDemo/ViewController.swift | 1 | 11381 | //
// ViewController.swift
// PonyChatUIDemo
//
// Created by 崔 明辉 on 15/10/27.
//
//
import UIKit
import PonyChatUI
class ViewController: UIViewController, PonyChatUIDelegate, UITextFieldDelegate {
var preloaded = false
let messageManager = DemoMessageManager()
var chatViewController: PonyChatUI.UserInterface.MainViewController?
var chatView: UIView?
let toolViewController = UIStoryboard(name: "Main",
bundle: nil).instantiateViewControllerWithIdentifier("ToolViewController")
func configureMenu() {
let deleteItem = PonyChatUI.UserInterface.LongPressEntity(title: "删除") { (message, chatViewController) -> Void in
if let messageManager = chatViewController?.eventHandler.interactor.manager {
messageManager.deleteItem(message)
}
}
PonyChatUI.UserInterface.Configure.sharedConfigure.longPressItems = [
deleteItem
]
}
override func viewDidLoad() {
super.viewDidLoad()
configureMenu()
if preloaded {
if let chatViewController = chatViewController, let chatView = chatView {
chatViewController.footerViewHeight = 44
chatViewController.coreDelegate = self
chatViewController.removeFromParentViewController()
chatView.removeFromSuperview()
addChildViewController(chatViewController)
view.addSubview(chatView)
}
}
else {
loadHistory()
toolViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44)
let chatMain = PonyChatUICore.sharedCore.wireframe.main(messageManager,
messagingConfigure: nil,
footerView: toolViewController.view)
chatMain.0.footerViewHeight = 44
chatMain.0.coreDelegate = self
chatViewController = chatMain.0
chatView = chatMain.1
addChildViewController(chatMain.0)
view.addSubview(chatMain.1)
}
if let textField = toolViewController.view.viewWithTag(1000) as? UITextField {
textField.delegate = self
}
}
func loadHistory() {
var items: [PonyChatUI.Entity.Message] = []
let systemMessage = PonyChatUI.Entity.SystemMessage(mID: "system", mDate: NSDate(), text: "[播放] 这是一条系统消息 [垃圾]")
items.append(systemMessage)
func m_0() -> () {
for i in 0...50 {
let random = Double(arc4random() % 200)
let mDate = NSDate(timeIntervalSinceNow: -86400 * 5 + 200 * Double(i) + random)
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
let message = PonyChatUI.Entity.TextMessage(mID: "text\(i)", mDate: mDate, text: "\(mDate.description)")
message.messageSender = aSender
items.append(message)
}
}
func m_1() -> () {
let mDate = NSDate(timeIntervalSinceNow: -86400 * 3 + 200)
let imageMessage = PonyChatUI.Entity.ImageMessage(mID: "image", mDate: mDate, imageURLString: "http://ww1.sinaimg.cn/large/c631b412jw1exizdhe4q2j21kw11x7fm.jpg", thumbURLString: "http://ww1.sinaimg.cn/bmiddle/c631b412jw1exizdhe4q2j21kw11x7fm.jpg", imageSize: CGSize(width: 2048, height: 1365))
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
imageMessage.messageSender = aSender
items.append(imageMessage)
}
func m_2() -> () {
let mDate = NSDate(timeIntervalSinceNow: -86400 * 2 + 200)
let imageMessage = PonyChatUI.Entity.ImageMessage(mID: "gifimage", mDate: mDate, imageURLString: "http://pics.sc.chinaz.com/Files/pic/faces/2425/26.gif", thumbURLString: "http://pics.sc.chinaz.com/Files/pic/faces/2425/26.gif", imageSize: CGSize(width: 75, height: 75))
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
imageMessage.messageSender = aSender
items.append(imageMessage)
}
func m_3() -> () {
for i in 0...50 {
let random = Double(arc4random() % 200)
let mDate = NSDate(timeIntervalSinceNow: -86400 * 4 + 200 * Double(i) + random)
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
let message = PonyChatUI.Entity.VoiceMessage(mID: "voice\(i)", mDate: mDate, voiceURLString: "xxxxx", voiceDuration: Double(arc4random() % 100))
if i > 40 {
message.voicePlayed = false
}
message.messageSender = aSender
items.append(message)
}
}
m_0()
m_3()
m_1()
m_2()
messageManager.insertItems(items)
}
func mockMessage() {
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
let message = PonyChatUI.Entity.TextMessage(mID: "mock\(NSDate().description)", mDate: NSDate(), text: NSDate().description)
message.messageSender = aSender
messageManager.appendItem(message)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let chatView = chatView {
chatView.frame = view.bounds
}
}
@IBAction func handleNextTapped(sender: AnyObject) {
if let nextViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController") as? ViewController {
nextViewController.preloaded = true
nextViewController.loadHistory()
nextViewController.toolViewController.view.frame = CGRect(
x: 0,
y: 0,
width: self.view.bounds.width,
height: 44)
PonyChatUICore.sharedCore.wireframe.preload(nextViewController.messageManager, messagingConfigure: nil, footerView: nextViewController.toolViewController.view, size: CGSize(width: self.view.bounds.width, height: self.view.bounds.height - 64.0), completion: { (mainViewController, mainView) -> Void in
nextViewController.chatViewController = mainViewController
nextViewController.chatView = mainView
self.navigationController?.pushViewController(nextViewController, animated: true)
})
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let text = textField.text {
let textMessage = PonyChatUI.Entity.TextMessage(mID: "Send.\(NSDate().description)", mDate: NSDate(), text: text)
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = true
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
textMessage.messageSender = aSender
messageManager.appendItem(textMessage)
}
textField.text = nil
return true
}
func chatUIRequestOpenURL(URL: NSURL) {
UIApplication.sharedApplication().openURL(URL)
}
func chatUIRequestOpenLargeImage(messageItem: PonyChatUI.Entity.ImageMessage, originRect: CGRect) {
print(messageItem)
print(originRect)
}
var nowPlayingItem: PonyChatUI.Entity.VoiceMessage?
var nowPaused = true
func chatUIRequestPlayVoiceMessages(messageItems: [PonyChatUI.Entity.VoiceMessage]) {
nowPaused = false
var i: UInt64 = 0
for item in messageItems {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * i * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
if self.nowPaused {
return
}
self.nowPlayingItem = item
item.voicePlaying = true
item.voicePlayed = true
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * i + 3 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
item.voicePlaying = false
}
}
i++
}
}
func chatUIRequestPauseVoicePlaying(messageItem: PonyChatUI.Entity.VoiceMessage) {
nowPaused = true
if let nowPlayingItem = nowPlayingItem {
nowPlayingItem.voicePlaying = false
}
messageItem.voicePlaying = false
}
func chatUIRequestOpenUserPage(user: PonyChatUI.Entity.Message.Sender) {
print(user)
}
func chatUIRequestResendMessage(messageItem: PonyChatUI.Entity.Message) {
print(messageItem)
}
}
class DemoMessageManager: PonyChatUI.MessageManager {
override init() {
super.init()
canFetchPreviousItems = true
}
var iii: Double = 10
override func beginFetchPreviousItems() {
if isFetchingPreviousItems {
return
}
super.beginFetchPreviousItems()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
var items: [PonyChatUI.Entity.Message] = []
for i in 0...50 {
let random = Double(arc4random() % 200)
let mDate = NSDate(timeIntervalSinceNow: -86400 * self.iii + 200 * Double(i) + random)
var aSender = PonyChatUI.Entity.Message.Sender()
aSender.isOwnSender = arc4random() % 2 == 0 ? true : false
aSender.senderAvatarURLString = "https://avatars1.githubusercontent.com/u/5013664?v=3&s=460"
aSender.senderNickname = "Pony"
let message = PonyChatUI.Entity.TextMessage(mID: "text\(arc4random())", mDate: mDate, text: "\(mDate.description)")
message.messageSender = aSender
items.append(message)
}
self.insertItems(items)
self.endFetchPreviousItems()
self.iii++
}
}
}
| mit | cac299577e7a6520d2be968e219fa6e5 | 41.657895 | 312 | 0.607826 | 4.524322 | false | false | false | false |
tilltue/FSCalendar | Example-Swift/SwiftExample/TableViewController.swift | 1 | 908 | //
// TableViewController.swift
// SwiftExample
//
// Created by dingwenchao on 10/17/16.
// Copyright © 2016 wenchao. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// super.tableView(tableView, didSelectRowAt: indexPath)
if indexPath.row == 0 {
let viewController = DIVExampleViewController()
self.navigationController?.pushViewController(viewController, animated: true)
} else if indexPath.row == 2 {
let viewController = LoadViewExampleViewController()
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
| mit | ab321fc88e408021effed716d3b2358d | 28.258065 | 92 | 0.673649 | 5.182857 | false | false | false | false |
qianqian2/ocStudy1 | EventView/EventView/ViewController.swift | 1 | 2426 | //
// ViewController.swift
// EventView
//
// Created by arang on 16/12/19.
// Copyright © 2016年 arang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var goBtn: UIButton!
let array = [String]()
// let array = [String]()
// fileprivate lazy var iconDate : imageViewModel = imageViewModel()
lazy var iconDate = [String:Any]()
override func viewDidLoad() {
super.viewDidLoad()
loadDate()
setBtn()
}
func setBtn(){
for i in 1...2 {
goBtn.tag = i
print(goBtn.tag)
// goBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
}
}
@IBAction func btnClick(_ sender: Any) {
let tags = goBtn.tag
print(tags)
switch tags {
case 1:
let detailVC = detailViewController()
detailVC.title = "denglu"
self.navigationController?.pushViewController(detailVC, animated: true)
break
case 2:
let secondVC = SecondViewController()
secondVC.title = "second"
self.navigationController?.pushViewController(secondVC, animated: true)
break
default:
break
}
}
}
extension ViewController {
func loadDate(){
//let url = "https://hub.expertt.cn/161205/161205113832_89337.png
// let url = "https://hub.expertt.cn/data/banner/161205/161205113832_89337.png"
let urlString = "https://hub.expertt.cn/api/banner/detail"
let parameters = ["bn_flag":10]
NetworkTools.requestData(.post, URLString: urlString, parameters: parameters) { (result) in
guard let resultDate = result as?[String : Any] else {
return
}
print(resultDate)
self.iconDate["img_nm"] = resultDate["img_nm"]
print(self.iconDate["img_nm"] ?? [])
self.icon.image = UIImage(named:self.iconDate["img_nm"] as! String)
}
//print(iconDate["img_nm"] ?? [])
}
}
extension ViewController{
}
| apache-2.0 | d41f03e2fb01569229b17ffe6d76a62f | 22.07619 | 103 | 0.518366 | 4.606464 | false | false | false | false |
JohnDuxbury/xcode | Fingers/Fingers/ViewController.swift | 1 | 1253 | //
// ViewController.swift
// Fingers
//
// Created by JD on 09/05/2015.
// Copyright (c) 2015 JDuxbury.me. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var guessResult: UILabel!
@IBOutlet weak var guessEntry: UITextField!
@IBAction func guessButton(sender: AnyObject) {
var randomNumber = arc4random_uniform(6)
var guessInt = guessEntry.text.toInt()
guessResult.text=toString(randomNumber)
if guessInt != nil {
if Int(randomNumber) == guessInt
{
guessResult.text="Good Guess!"
} else
{
guessResult.text="Sorry - the correct number was \(randomNumber)!"
}
}else{
guessResult.text="Please enter a number between 1 - 5!"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 52bdcf03e1923f0f6626de871ecad89e | 21.375 | 82 | 0.557861 | 4.952569 | false | false | false | false |
abouzek/hn_browser | HNBrowser/HNBStoryTableViewCell.swift | 1 | 1270 | //
// HNBStoryTableViewCell.swift
// HNBrowser
//
// Created by Alan Bouzek on 11/18/15.
// Copyright © 2015 abouzek. All rights reserved.
//
import UIKit
protocol HNBStoryTableViewCellDelegate {
func storyCellDidPressCommentsButton(cell: HNBStoryTableViewCell)
}
class HNBStoryTableViewCell: UITableViewCell {
static let nibName = "HNBStoryTableViewCell"
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var commentsLabel: UILabel!
@IBOutlet weak var separatorWidthConstraint: NSLayoutConstraint!
var delegate: HNBStoryTableViewCellDelegate?
override func awakeFromNib() {
self.separatorWidthConstraint.constant = 0.5
}
func styleForStory(story: HNBItem) {
self.titleLabel.text = story.title
self.subtitleLabel.text = story.by
if let score = story.score {
self.scoreLabel.text = "\(score)"
}
self.commentsLabel.text = "\(story.kids.count) c"
}
@IBAction func commentsButtonPressed(sender: UIButton) {
if let delegate = self.delegate {
delegate.storyCellDidPressCommentsButton(self)
}
}
}
| mit | 3a0f72a19ab10c9966474f09bafbf4b7 | 26 | 69 | 0.675335 | 4.437063 | false | false | false | false |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Extensions/UILable+custom.swift | 1 | 3155 | //
// UILabel+custom.swift
// Managin Bundles
//
// Created by Incubasys on 10/07/2017.
// Copyright © 2017 Incubasys. All rights reserved.
//
import UIKit
public class AppLabel: UILabel{
@IBInspectable public var isLight: Bool = false{
didSet{
if self.isLight{
self.textColor = UIColor.appColor(color: .LightText)
}else{
self.textColor = UIColor.appColor(color: .DarkText)
}
}
}
public func config(font: UIFont) {
self.font = font
if isLight{
self.textColor = UIColor.appColor(color: .LightText)
}else{
self.textColor = UIColor.appColor(color: .DarkText)
}
}
}
//Login/Signup
public class HeadlineLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikBold, pontSize: 20))
}
}
//Light Selected
public class SubheadLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikBold, pontSize: 15))
}
}
public class CaptionLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikRegular, pontSize: 14))
}
}
public class NavigationTitleLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: NavigationTitleLabel.font())
}
public static func font() -> UIFont{
return UIFont.appFont(font: .RubikRegular, pontSize: 17)
}
}
public class TitleLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikMedium, pontSize: 17))
}
}
public class TextLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: TextLabel.font())
}
public static func font() -> UIFont{
return UIFont.appFont(font: .RubikRegular, pontSize: 15)
}
}
//aka Dark Caption
public class CalloutLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikRegular, pontSize: 12))
}
}
//Timers/counters
public class ShoutnoteLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: ShoutnoteLabel.font())
}
public static func font() -> UIFont{
return UIFont.appFont(font: .RubikMedium, pontSize: 48)
}
}
//Timers/counters Small
public class ShoutnoteSmallLabel: AppLabel {
public override func awakeFromNib() {
super.config(font: UIFont.appFont(font: .RubikMedium, pontSize: 36))
}
}
/*
case R-R,L = 48(stats),18(home),16(invite friends earn more),14([email protected])
case R-R,D = 18(invite friends),16(recurring),14(Mehram,Home,ride again with abc?,Paragraph),12(SAR 40-70,Cardholder name)
case R-M,D = 48(stats),36,18(king khalid international),16(name),14(SAR 80)
case R-M,L = 24(distance),16(invite COde),14(search ride,destination),12(Details,06:60Am)
case R-B,D = 20(verification code),14(Cash)
case G-B,L = 18,14
case G,L = 14
case G,D = 14,12
case SFU-R,L = 16(Go)
case SFU-R,D = 16(123)
case HN,L = 14(datetime)
case HN,D = 12
*/
| mit | 01f4af26d12b05d6284d3a433790b452 | 24.852459 | 122 | 0.652188 | 3.473568 | false | true | false | false |
RaviiOS/Swift_ReusableCode | RKSwift3Plus/RKSwift3Plus/Extensions/UINavigationBar.swift | 1 | 783 |
import Foundation
import UIKit
public extension UINavigationBar {
public func setTransparent(_ transparent: Bool) {
if transparent {
setBackgroundImage(UIImage(), for: .default)
shadowImage = UIImage()
isTranslucent = true
backgroundColor = .clear
} else {
// By default take values from UINavigationBar appearance
let backImage = UINavigationBar.appearance().backgroundImage(for: .default)
setBackgroundImage(backImage, for: .default)
shadowImage = UINavigationBar.appearance().shadowImage
isTranslucent = UINavigationBar.appearance().isTranslucent
backgroundColor = UINavigationBar.appearance().backgroundColor
}
}
}
| mit | d909f7354553e2b113675deccbcea4cb | 33.043478 | 87 | 0.642401 | 6.418033 | false | false | false | false |
davejlin/treehouse | swift/swift2/fotofun/Pods/ReactiveCocoa/ReactiveCocoa/Swift/ObjectiveCBridging.swift | 21 | 8001 | //
// ObjectiveCBridging.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-07-02.
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
//
import Result
extension RACDisposable: Disposable {}
extension RACScheduler: DateSchedulerType {
public var currentDate: NSDate {
return NSDate()
}
public func schedule(action: () -> Void) -> Disposable? {
let disposable: RACDisposable = self.schedule(action) // Call the Objective-C implementation
return disposable as Disposable?
}
public func scheduleAfter(date: NSDate, action: () -> Void) -> Disposable? {
return self.after(date, schedule: action)
}
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> Void) -> Disposable? {
return self.after(date, repeatingEvery: repeatingEvery, withLeeway: withLeeway, schedule: action)
}
}
extension ImmediateScheduler {
public func toRACScheduler() -> RACScheduler {
return RACScheduler.immediateScheduler()
}
}
extension UIScheduler {
public func toRACScheduler() -> RACScheduler {
return RACScheduler.mainThreadScheduler()
}
}
extension QueueScheduler {
public func toRACScheduler() -> RACScheduler {
return RACTargetQueueScheduler(name: "org.reactivecocoa.ReactiveCocoa.QueueScheduler.toRACScheduler()", targetQueue: queue)
}
}
private func defaultNSError(message: String, file: String, line: Int) -> NSError {
return Result<(), NSError>.error(message, file: file, line: line)
}
extension RACSignal {
/// Creates a SignalProducer which will subscribe to the receiver once for
/// each invocation of start().
public func toSignalProducer(file: String = #file, line: Int = #line) -> SignalProducer<AnyObject?, NSError> {
return SignalProducer { observer, disposable in
let next = { obj in
observer.sendNext(obj)
}
let failed = { nsError in
observer.sendFailed(nsError ?? defaultNSError("Nil RACSignal error", file: file, line: line))
}
let completed = {
observer.sendCompleted()
}
disposable += self.subscribeNext(next, error: failed, completed: completed)
}
}
}
extension SignalType {
/// Turns each value into an Optional.
private func optionalize() -> Signal<Value?, Error> {
return signal.map(Optional.init)
}
}
// MARK: - toRACSignal
extension SignalProducerType where Value: AnyObject {
/// Creates a RACSignal that will start() the producer once for each
/// subscription.
///
/// Any `Interrupted` events will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.lift { $0.optionalize() }
.toRACSignal()
}
}
extension SignalProducerType where Value: OptionalType, Value.Wrapped: AnyObject {
/// Creates a RACSignal that will start() the producer once for each
/// subscription.
///
/// Any `Interrupted` events will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.mapError { $0 as NSError }
.toRACSignal()
}
}
extension SignalProducerType where Value: AnyObject, Error: NSError {
/// Creates a RACSignal that will start() the producer once for each
/// subscription.
///
/// Any `Interrupted` events will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.lift { $0.optionalize() }
.toRACSignal()
}
}
extension SignalProducerType where Value: OptionalType, Value.Wrapped: AnyObject, Error: NSError {
/// Creates a RACSignal that will start() the producer once for each
/// subscription.
///
/// Any `Interrupted` events will be silently discarded.
public func toRACSignal() -> RACSignal {
// This special casing of `Error: NSError` is a workaround for rdar://22708537
// which causes an NSError's UserInfo dictionary to get discarded
// during a cast from ErrorType to NSError in a generic function
return RACSignal.createSignal { subscriber in
let selfDisposable = self.start { event in
switch event {
case let .Next(value):
subscriber.sendNext(value.optional)
case let .Failed(error):
subscriber.sendError(error)
case .Completed:
subscriber.sendCompleted()
case .Interrupted:
break
}
}
return RACDisposable {
selfDisposable.dispose()
}
}
}
}
extension SignalType where Value: AnyObject {
/// Creates a RACSignal that will observe the given signal.
///
/// Any `Interrupted` event will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.optionalize()
.toRACSignal()
}
}
extension SignalType where Value: AnyObject, Error: NSError {
/// Creates a RACSignal that will observe the given signal.
///
/// Any `Interrupted` event will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.optionalize()
.toRACSignal()
}
}
extension SignalType where Value: OptionalType, Value.Wrapped: AnyObject {
/// Creates a RACSignal that will observe the given signal.
///
/// Any `Interrupted` event will be silently discarded.
public func toRACSignal() -> RACSignal {
return self
.mapError { $0 as NSError }
.toRACSignal()
}
}
extension SignalType where Value: OptionalType, Value.Wrapped: AnyObject, Error: NSError {
/// Creates a RACSignal that will observe the given signal.
///
/// Any `Interrupted` event will be silently discarded.
public func toRACSignal() -> RACSignal {
// This special casing of `Error: NSError` is a workaround for rdar://22708537
// which causes an NSError's UserInfo dictionary to get discarded
// during a cast from ErrorType to NSError in a generic function
return RACSignal.createSignal { subscriber in
let selfDisposable = self.observe { event in
switch event {
case let .Next(value):
subscriber.sendNext(value.optional)
case let .Failed(error):
subscriber.sendError(error)
case .Completed:
subscriber.sendCompleted()
case .Interrupted:
break
}
}
return RACDisposable {
selfDisposable?.dispose()
}
}
}
}
// MARK: -
extension RACCommand {
/// Creates an Action that will execute the receiver.
///
/// Note that the returned Action will not necessarily be marked as
/// executing when the command is. However, the reverse is always true:
/// the RACCommand will always be marked as executing when the action is.
public func toAction(file: String = #file, line: Int = #line) -> Action<AnyObject?, AnyObject?, NSError> {
let enabledProperty = MutableProperty(true)
enabledProperty <~ self.enabled.toSignalProducer()
.map { $0 as! Bool }
.flatMapError { _ in SignalProducer<Bool, NoError>(value: false) }
return Action(enabledIf: enabledProperty) { input -> SignalProducer<AnyObject?, NSError> in
let executionSignal = RACSignal.`defer` {
return self.execute(input)
}
return executionSignal.toSignalProducer(file, line: line)
}
}
}
extension ActionType {
private var commandEnabled: RACSignal {
return self.enabled.producer
.map { $0 as NSNumber }
.toRACSignal()
}
}
/// Creates a RACCommand that will execute the action.
///
/// Note that the returned command will not necessarily be marked as
/// executing when the action is. However, the reverse is always true:
/// the Action will always be marked as executing when the RACCommand is.
public func toRACCommand<Output: AnyObject, Error>(action: Action<AnyObject?, Output, Error>) -> RACCommand {
return RACCommand(enabled: action.commandEnabled) { input -> RACSignal in
return action
.apply(input)
.toRACSignal()
}
}
/// Creates a RACCommand that will execute the action.
///
/// Note that the returned command will not necessarily be marked as
/// executing when the action is. However, the reverse is always true:
/// the Action will always be marked as executing when the RACCommand is.
public func toRACCommand<Output: AnyObject, Error>(action: Action<AnyObject?, Output?, Error>) -> RACCommand {
return RACCommand(enabled: action.commandEnabled) { input -> RACSignal in
return action
.apply(input)
.toRACSignal()
}
}
| unlicense | ec5a07228d8f1cbfeddbfd4d1085b893 | 28.743494 | 137 | 0.716785 | 3.9375 | false | false | false | false |
dongdongSwift/guoke | gouke/果壳/mainView.swift | 1 | 11811 | //
// mainView.swift
// 果壳
//
// Created by qianfeng on 2016/10/21.
// Copyright © 2016年 张冬. All rights reserved.
//
import UIKit
import Alamofire
import MJRefresh
class mainView: UIViewController,NavigationProtocol,UMSocialUIDelegate {
var center:CGPoint!
var leftBtnClickClosure:(()->())?
var currentPage:CGFloat=0
var edgepan:UIScreenEdgePanGestureRecognizer?
var pan:UIPanGestureRecognizer?
var tableArray:[UITableView]=[]
var newsList:ScrollPage?
var titlels:titlelist?
var currentOffSetArray:[Int]=[0,0,0,0,0,0,0,0]
let categoryArray=["all","science","life","health","learning","humanities","nature","entertainment"]
var dataAll:[String:allModel]=["all":allModel(),"science":allModel(),"life":allModel(),"health":allModel(),"learning":allModel(),"humanities":allModel(),"nature":allModel(),"entertainment":allModel()]
let titlenames=["全部","科技","生活","健康","学习","人文","自然","娱乐"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor=UIColor.whiteColor()
let titlels=titlelist(frame: CGRect(x: 0, y: 64, width: screenWidth, height:40), titlies: titlenames)
self.view.addSubview(titlels)
initTitleList()
initNewsList()
// addengePan(false)
loadData(currentPage: 0)
}
//MARK:init TitleList
func initTitleList(){
print("tlist")
let titlenames=["全部","科技","生活","健康","学习","人文","自然","娱乐"]
titlels=titlelist(frame: CGRect(x: 0, y: 64, width: screenWidth, height:40), titlies: titlenames)
self.view.addSubview(titlels!)
self.view.addSubview((navigationController?.navigationBar)!)
// let image=UIImage()
// self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: .Default)
self.navigationController?.navigationBar.barTintColor=UIColor.brownColor()
center=self.view.center
addTitle("果壳精选")
addBarButton( imageName: "bar_back_icon", postion: .left, select: #selector(leftBtnClick))
addBarButton(imageName: "search_ic", postion: .right, select: #selector(rightBtnClick))
}
func leftBtnClick(){
leftBtnClickClosure!()
}
func rightBtnClick(){
let vc=searchViewController()
navigationController?.pushViewController(vc, animated: true)
}
/*********************数据加载*******************************/
func initData(){
}
func loadData(currentPage n:Int){
let downloader=DownLoader()
downloader.download(currentPage: n, dataAll: dataAll, categoryArray: categoryArray,tableArray:tableArray,currentOffSetArray:currentOffSetArray,closure: {
self.tableArray[n].reloadData()
})
}
/***********************页面初始化*******************************/
func initNewsList(){
automaticallyAdjustsScrollViewInsets = false
// MARK:create scrollowview *************************/
newsList=ScrollPage(frame: CGRect(x: 0, y:104, width: screenWidth, height: screenHeight-104), pageNum: titlenames.count)
self.tableArray=newsList!.tableArray
newsList!.tag=200
newsList!.delegate=self
let pageWidth=newsList!.frame.width
// let pageHeight=newsList!.frame.height
newsList!.bounces=false
newsList!.showsVerticalScrollIndicator=false
newsList!.pagingEnabled=true
self.view.addSubview(newsList!)
//MARK:config tableview****************************/
tableArray[0].tableHeaderView=TJScrollView(frame: CGRect(x: 0, y: 0, width: pageWidth, height: pageWidth/2))
for i in 0..<titlenames.count{
tableArray[i].dataSource=self
tableArray[i].delegate=self
tableArray[i].tag=100+i
tableArray[i].registerNib(UINib(nibName: "Customcell", bundle: nil), forCellReuseIdentifier: "customCell")
tableArray[i].registerNib(UINib(nibName: "customCell1", bundle: nil), forCellReuseIdentifier:"customCell1")
tableArray[i].registerNib(UINib(nibName: "CustomCell2", bundle: nil), forCellReuseIdentifier: "CustomCell2")
/***********************加刷新***********************/
tableArray[i].mj_header=MJRefreshNormalHeader(refreshingBlock: {
self.currentOffSetArray[i]=0
self.loadData(currentPage: i)
self.tableArray[i].reloadData()
})
tableArray[i].mj_footer=MJRefreshAutoNormalFooter(refreshingBlock: {
self.currentOffSetArray[i]+=20
self.loadData(currentPage: i)
self.tableArray[i].reloadData()
})
}
/***********************加刷新***********************/
/**************titlels的闭包控制换页*********************/
titlels?.pageChangeClosure={
[unowned self](labeltag) in
self.currentPage=CGFloat(labeltag)
self.newsList!.setContentOffset(CGPoint(x: pageWidth*self.currentPage, y: 0), animated: false)
self.tableArray[labeltag].mj_header.beginRefreshingWithCompletionBlock({
[weak self] (a) in
self!.loadData(currentPage: labeltag)
})
}
}
/**************titlels的闭包控制换页*********************/
/*************手势的添加********************************/
// func btnClick(){
// show()
// }
//
// func addengePan(haveshow:Bool){
// if haveshow{
// pan=UIPanGestureRecognizer(target: self, action: #selector(panChange(_:)))
// pan!.minimumNumberOfTouches=1
// view.addGestureRecognizer(pan!)
// }else{
// edgepan=UIScreenEdgePanGestureRecognizer(target: self, action: #selector(panChange(_:)))
// edgepan!.edges=UIRectEdge.Left
// edgepan!.minimumNumberOfTouches=1
// view.addGestureRecognizer(edgepan!)
// }
// }
//
//
// func show(){
//
// UIView.animateWithDuration(0.1) {
// [unowned self](a) in
//
// self.view.superview!.frame.origin.x = 2*self.view.bounds.width/3
//
// }
// center=self.view.center
// self.view.removeGestureRecognizer(edgepan!)
// addengePan(true)
//
// }
// func hide(){
// UIView.animateWithDuration(0.1) {
//
// self.view.frame.origin.x = 0
//
// }
// center=self.view.center
// if pan != nil{
// self.view.removeGestureRecognizer(pan!)}
// addengePan(false)
// }
//
// func panChange(pan:UIPanGestureRecognizer){
// // view.userInteractionEnabled=false
// let chgpoint=pan.translationInView(view)
// pan.view?.center.x=center.x+chgpoint.x
// if pan.state == .Ended{
// if view.frame.origin.x<self.view.bounds.width/3{
// hide()
// }
// if view.frame.origin.x>self.view.bounds.width/3{
// show()
// }
//
// }
}
//MARK:scrollowview代理
extension mainView:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.tag==200 {
let pagewidth=scrollView.frame.width
currentPage=scrollView.contentOffset.x/pagewidth
titlels?.titleChange(Int(currentPage))
loadData(currentPage: Int(currentPage))
}
}
}
//MARK:UITableView代理
extension mainView:UITableViewDelegate,UITableViewDataSource{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
guard dataAll[categoryArray[tableView.tag-100]]?.result.count>0 else{
return 20
}
return (dataAll[categoryArray[tableView.tag-100]]?.result.count)!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row==0{
return 20
}
else{
if dataAll[categoryArray[tableView.tag-100]]?.result.count>0&&(((dataAll[categoryArray[tableView.tag-100]]?.result[indexPath.section])?.category == "pic")||((dataAll[categoryArray[tableView.tag-100]]?.result[indexPath.section])?.category == "calendar")){
return 355
}else{
return 115
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let data=dataAll[categoryArray[tableView.tag-100]]! as allModel
guard data.now != nil else{
let cell=UITableViewCell()
return cell
}
if indexPath.row==0{
let cell=Customcell.createHeadCell(tableView, atIndexPath: indexPath, dataAll: dataAll[categoryArray[tableView.tag-100]]!)
return cell
}else if indexPath.row==1{
if data.result[indexPath.section].category=="pic"||data.result[indexPath.section].category=="calendar"{
let cell=CustomCell2.createCustomCell2(tableView, atIndexPath: indexPath, dataAll: data)
cell.closure={
[weak self](a) in
UMSocialSnsService.presentSnsIconSheetView(self, appKey: "57b1797067e58e3aab002deb", shareText: "果壳", shareImage:nil, shareToSnsNames: [UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite], delegate: self)
}
return cell
}else{
let cell=customCell1.createCell1(tableView, atIndexPath: indexPath, dataAll: dataAll[categoryArray[tableView.tag-100]]!)
cell.closure={
[weak self](a) in
UMSocialSnsService.presentSnsIconSheetView(self, appKey: "57b1797067e58e3aab002deb", shareText: "果壳", shareImage:nil, shareToSnsNames: [UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite], delegate: self)
}
return cell
}
}else{
let cell=UITableViewCell(frame:CGRect(x: 0, y: 0, width: screenWidth, height: 10))
cell.backgroundColor=UIColor(white: 0.6, alpha: 0.8)
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row==1{
let vc=DetailController()
let cnt=dataAll[categoryArray[tableView.tag-100]]?.result.count
var array:[resultModel]=[]
for i in indexPath.section..<cnt!{
array.append((dataAll[categoryArray[tableView.tag-100]]?.result[i])!)
}
vc.dataResult=array
presentViewController(vc, animated: true, completion: nil)
}else if indexPath.row==0{
let vc=sourceGroupViewController()
vc.group=dataAll[categoryArray[tableView.tag-100]]?.result[indexPath.section].source_data!
presentViewController(vc, animated: true, completion: nil)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 7a83751c1ee5b101c5705a14c04ad1f1 | 33.654762 | 266 | 0.575661 | 4.564485 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift | 12 | 4704 | //
// CurrentThreadScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSObject
import protocol Foundation.NSCopying
import class Foundation.Thread
import Dispatch
#if os(Linux)
import struct Foundation.pthread_key_t
import func Foundation.pthread_setspecific
import func Foundation.pthread_getspecific
import func Foundation.pthread_key_create
fileprivate enum CurrentThreadSchedulerQueueKey {
fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue"
}
#else
private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying {
static let instance = CurrentThreadSchedulerQueueKey()
private override init() {
super.init()
}
override var hash: Int {
return 0
}
public func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
#endif
/// Represents an object that schedules units of work on the current thread.
///
/// This is the default scheduler for operators that generate elements.
///
/// This scheduler is also sometimes called `trampoline scheduler`.
public class CurrentThreadScheduler : ImmediateSchedulerType {
typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>>
/// The singleton instance of the current thread scheduler.
public static let instance = CurrentThreadScheduler()
private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in
let key = UnsafeMutablePointer<pthread_key_t>.allocate(capacity: 1)
defer { key.deallocate() }
guard pthread_key_create(key, nil) == 0 else {
rxFatalError("isScheduleRequired key creation failed")
}
return key.pointee
}()
private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in
return UnsafeRawPointer(UnsafeMutablePointer<Int>.allocate(capacity: 1))
}()
static var queue : ScheduleQueue? {
get {
return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance)
}
set {
Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance)
}
}
/// Gets a value that indicates whether the caller must call a `schedule` method.
public static fileprivate(set) var isScheduleRequired: Bool {
get {
return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil
}
set(isScheduleRequired) {
if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 {
rxFatalError("pthread_setspecific failed")
}
}
}
/**
Schedules an action to be executed as soon as possible on current thread.
If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be
automatically installed and uninstalled after all work is performed.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
if CurrentThreadScheduler.isScheduleRequired {
CurrentThreadScheduler.isScheduleRequired = false
let disposable = action(state)
defer {
CurrentThreadScheduler.isScheduleRequired = true
CurrentThreadScheduler.queue = nil
}
guard let queue = CurrentThreadScheduler.queue else {
return disposable
}
while let latest = queue.value.dequeue() {
if latest.isDisposed {
continue
}
latest.invoke()
}
return disposable
}
let existingQueue = CurrentThreadScheduler.queue
let queue: RxMutableBox<Queue<ScheduledItemType>>
if let existingQueue = existingQueue {
queue = existingQueue
}
else {
queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
CurrentThreadScheduler.queue = queue
}
let scheduledItem = ScheduledItem(action: action, state: state)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
}
| mit | a3aa06bd044b9caeabb03ef75ced7a6a | 33.07971 | 142 | 0.652987 | 5.618877 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/ConversationMessage+Deletion.swift | 1 | 4001 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCryptobox
extension ZMConversation {
static func appendHideMessageToSelfConversation(_ message: ZMMessage) throws {
guard
let messageId = message.nonce,
let conversation = message.conversation,
let conversationId = conversation.remoteIdentifier
else {
return
}
let genericMessage = GenericMessage(content: MessageHide(conversationId: conversationId, messageId: messageId))
_ = try ZMConversation.appendMessageToSelfConversation(genericMessage, in: message.managedObjectContext!)
}
}
extension ZMMessage {
// NOTE: This is a free function meant to be called from Obj-C because you can't call protocol extension from it
@objc public static func hideMessage(_ message: ZMConversationMessage) {
// when deleting ephemeral, we must delete for everyone (only self & sender will receive delete message)
// b/c deleting locally will void the destruction timer completion.
guard !message.isEphemeral else { deleteForEveryone(message); return }
guard let castedMessage = message as? ZMMessage else { return }
castedMessage.hideForSelfUser()
}
@objc public func hideForSelfUser() {
guard !isZombieObject else { return }
do {
try ZMConversation.appendHideMessageToSelfConversation(self)
} catch {
Logging.messageProcessing.warn("Failed to append hide message. Reason: \(error.localizedDescription)")
return
}
// To avoid reinserting when receiving an edit we delete the message locally
removeClearingSender(true)
managedObjectContext?.delete(self)
}
@discardableResult @objc public static func deleteForEveryone(_ message: ZMConversationMessage) -> ZMClientMessage? {
guard let castedMessage = message as? ZMMessage else { return nil }
return castedMessage.deleteForEveryone()
}
@discardableResult @objc func deleteForEveryone() -> ZMClientMessage? {
guard !isZombieObject, let sender = sender, (sender.isSelfUser || isEphemeral) else { return nil }
guard let conversation = conversation, let messageNonce = nonce else { return nil}
do {
let genericMessage = GenericMessage(content: MessageDelete(messageId: messageNonce))
let message = try conversation.appendClientMessage(with: genericMessage, expires: false, hidden: true)
removeClearingSender(false)
updateCategoryCache()
return message
} catch {
Logging.messageProcessing.warn("Failed delete message for everyone. Reason: \(error.localizedDescription)")
return nil
}
}
@objc var isEditableMessage: Bool {
return false
}
}
extension ZMClientMessage {
override var isEditableMessage: Bool {
guard
let genericMessage = underlyingMessage,
let sender = sender, sender.isSelfUser,
let content = genericMessage.content else {
return false
}
switch content {
case .edited:
return true
case .text:
return !isEphemeral && isSent
default:
return false
}
}
}
| gpl-3.0 | b4cdd9e34c3b3b6bcc8e4c8db7d7b2ef | 36.745283 | 121 | 0.674581 | 5.129487 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Notifications/Changes.swift | 1 | 1754 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
struct Changes: Mergeable {
// MARK: - Properties
let changedKeys: Set<String>
let originalChanges: [String: NSObject?]
let mayHaveUnknownChanges: Bool
// MARK: - Life cycle
init(
changedKeys: Set<String> = [],
originalChanges: [String: NSObject?] = [:],
mayHaveUnknownChanges: Bool = false
) {
self.changedKeys = changedKeys
self.originalChanges = originalChanges
self.mayHaveUnknownChanges = mayHaveUnknownChanges
}
// MARK: - Methods
var hasChangeInfo: Bool {
return !changedKeys.isEmpty || !originalChanges.isEmpty || mayHaveUnknownChanges
}
func merged(with other: Changes) -> Changes {
guard other.hasChangeInfo else { return self }
return Changes(
changedKeys: changedKeys.union(other.changedKeys),
originalChanges: originalChanges.updated(other: other.originalChanges),
mayHaveUnknownChanges: mayHaveUnknownChanges || other.mayHaveUnknownChanges
)
}
}
| gpl-3.0 | 242c8ca213d1d7c3afa1317521a837bf | 29.77193 | 88 | 0.688712 | 4.508997 | false | false | false | false |
classmere/app | Classmere/Classmere/Utilities.swift | 1 | 3591 | import Foundation
enum UtilitiesError: Error {
case sortTerms(String)
}
/**
A model representation of a date formatter.
*/
struct Utilities {
/**
Returns a user friendly formatted term string
- Parameter term: An unformatted term string (eg. F16)
- Returns: A formatted term string (eg. Fall 2016)
*/
static func parseTerm(_ term: String?) -> String {
if let unparsedTerm = term, unparsedTerm.count > 2 {
let season = unparsedTerm[..<unparsedTerm.index(unparsedTerm.startIndex, offsetBy: 2)]
let year = unparsedTerm[unparsedTerm.index(unparsedTerm.endIndex, offsetBy: -2)...]
var parsedTerm: String = ""
if season.contains("F") {
parsedTerm += "Fall"
} else if season.contains("W") {
parsedTerm += "Winter"
} else if season.contains("Sp") {
parsedTerm += "Spring"
} else if season.contains("Su") {
parsedTerm += "Summer"
}
if Int(year) != nil {
parsedTerm += " 20\(year)"
}
return parsedTerm
} else {
return ""
}
}
/**
Parses a title to remove the subject code and course number
- Parameter title: An unformatted title string
- Returns: Formatted title string
*/
static func parseTitle(_ title: String?) -> String {
if let unparsedTitle = title {
var spaceIndexes = [Int]()
for (index, value) in unparsedTitle.enumerated() where value == " " {
spaceIndexes.append(index + 1)
}
let parsedString: String? = (unparsedTitle as NSString).substring(from: spaceIndexes[1])
if parsedString != nil {
return parsedString!
}
}
return ""
}
/**
Returns the String representation of an optional or an empty String
- Parameter optional: Any Optional
- Returns: A String representation of the Object if not null, otherwise an empty String
*/
static func optionalDescriptionOrEmptyString(_ optional: Any?) -> String {
if let unwrapped = optional { return String(describing: unwrapped) }
return ""
}
/**
Sorts an array of strings containing term information, e.g. "W18"
*/
static func sortTerms(el1: String, el2: String) throws -> Bool {
guard el1.count > 2 && el2.count > 2 else {
throw UtilitiesError.sortTerms("Array contains < 3 elements")
}
guard let el1Year = Int(el1[el1.index(el1.endIndex, offsetBy: -2)...]) else {
throw UtilitiesError.sortTerms("Could not parse year from string: \(el1)")
}
guard let el2Year = Int(el2[el2.index(el2.endIndex, offsetBy: -2)...]) else {
throw UtilitiesError.sortTerms("Could not parse year from string: \(el2)")
}
let el1Term = String(el1[..<el1.index(el1.endIndex, offsetBy: -2)])
let el2Term = String(el2[..<el2.index(el2.endIndex, offsetBy: -2)])
if el1Year > el2Year { return false }
if el1Year < el2Year { return true }
let termRawValues = [
"W": 0,
"Sp": 1,
"Su": 2,
"F": 3,
"T": 4
]
if let el1RawValue = termRawValues[el1Term], let el2RawValue = termRawValues[el2Term] {
return el1RawValue < el2RawValue
}
throw UtilitiesError.sortTerms("Array contains invalid terms: \(el1Term), \(el2Term)")
}
}
| gpl-3.0 | bb113ce20cb3e242b9cf9a89a08baf1a | 31.645455 | 100 | 0.566973 | 4.275 | false | false | false | false |
yzyzsun/CurriculaTable | CurriculaTable/CurriculaTableItem.swift | 1 | 1072 | //
// CurriculaTableItem.swift
// CurriculaTable
//
// Created by Sun Yaozhu on 2016-09-10.
// Copyright © 2016 Sun Yaozhu. All rights reserved.
//
import Foundation
public struct CurriculaTableItem {
public let name: String
public let place: String
public let weekday: CurriculaTableWeekday
public let startPeriod: Int
public let endPeriod: Int
public let textColor: UIColor
public let bgColor: UIColor
public let identifier: String
public let tapHandler: (CurriculaTableItem) -> Void
public init(name: String, place: String, weekday: CurriculaTableWeekday, startPeriod: Int, endPeriod: Int, textColor: UIColor, bgColor: UIColor, identifier: String, tapHandler: @escaping (CurriculaTableItem) -> Void) {
self.name = name
self.place = place
self.weekday = weekday
self.startPeriod = startPeriod
self.endPeriod = endPeriod
self.textColor = textColor
self.bgColor = bgColor
self.identifier = identifier
self.tapHandler = tapHandler
}
}
| mit | 350e2dccd4ace6c991ef8228be08c888 | 29.6 | 222 | 0.686275 | 4.301205 | false | false | false | false |
pietrocaselani/Trakt-Swift | Trakt/Models/Enums/Extended.swift | 1 | 178 | public enum Extended: String {
case defaultMin = "min"
case full = "full"
case noSeasons = "noseasons"
case episodes = "episodes"
case fullEpisodes = "full,episodes"
}
| unlicense | ba75df4ecc44e47bbcce13692215a230 | 24.428571 | 37 | 0.691011 | 3.56 | false | false | false | false |
WillowChat/Squeak | Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift | 1 | 17482 | //
// DelegateProxyType.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import func Foundation.objc_getAssociatedObject
import func Foundation.objc_setAssociatedObject
#if !RX_NO_MODULE
import RxSwift
#endif
/**
`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with
views that can have only one delegate/datasource registered.
`Proxies` store information about observers, subscriptions and delegates
for specific views.
Type implementing `DelegateProxyType` should never be initialized directly.
To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method
should be used.
This is more or less how it works.
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+
Since RxCocoa needs to automagically create those Proxys and because views that have delegates can be hierarchical
UITableView : UIScrollView : UIView
.. and corresponding delegates are also hierarchical
UITableViewDelegate : UIScrollViewDelegate : NSObject
... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other
part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching).
RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) }
*/
public protocol DelegateProxyType : AnyObject {
associatedtype ParentObject: AnyObject
associatedtype Delegate: AnyObject
/// It is require that enumerate call `register` of the extended DelegateProxy subclasses here.
static func registerKnownImplementations()
/// Unique identifier for delegate
static var identifier: UnsafeRawPointer { get }
/// Returns designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// It's abstract method.
///
/// - parameter object: Object that has delegate property.
/// - returns: Value of delegate property.
static func currentDelegate(for object: ParentObject) -> Delegate?
/// Sets designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// It's abstract method.
///
/// - parameter toObject: Object that has delegate property.
/// - parameter delegate: Delegate value.
static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject)
/// Returns reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - returns: Value of reference if set or nil.
func forwardToDelegate() -> Delegate?
/// Sets reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
/// - parameter retainDelegate: Should `self` retain `forwardToDelegate`.
func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool)
}
// default implementations
extension DelegateProxyType {
/// Unique identifier for delegate
public static var identifier: UnsafeRawPointer {
let delegateIdentifier = ObjectIdentifier(Delegate.self)
let integerIdentifier = Int(bitPattern: delegateIdentifier)
return UnsafeRawPointer(bitPattern: integerIdentifier)!
}
}
extension DelegateProxyType {
/// Store DelegateProxy subclass to factory.
/// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory
/// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type.
/// Should call it from concrete DelegateProxy type, not generic.
public static func register<Parent>(make: @escaping (Parent) -> Self) {
self.factory.extend(make: make)
}
/// Creates new proxy for target object.
/// Should not call this function directory, use 'DelegateProxy.proxy(for:)'
public static func createProxy(for object: AnyObject) -> Self {
return castOrFatalError(factory.createProxy(for: object))
}
/// Returns existing proxy for object or installs new instance of delegate proxy.
///
/// - parameter object: Target object on which to install delegate proxy.
/// - returns: Installed instance of delegate proxy.
///
///
/// extension Reactive where Base: UISearchBar {
///
/// public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> {
/// return RxSearchBarDelegateProxy.proxy(for: base)
/// }
///
/// public var text: ControlProperty<String> {
/// let source: Observable<String> = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:)))
/// ...
/// }
/// }
public static func proxy(for object: ParentObject) -> Self {
MainScheduler.ensureExecutingOnScheduler()
let maybeProxy = self.assignedProxy(for: object)
// Type is ideally be `(Self & Delegate)`, but Swift 3.0 doesn't support it.
let proxy: Delegate
if let existingProxy = maybeProxy {
proxy = existingProxy
}
else {
proxy = castOrFatalError(self.createProxy(for: object))
self.assignProxy(proxy, toObject: object)
assert(self.assignedProxy(for: object) === proxy)
}
let currentDelegate = self.currentDelegate(for: object)
let delegateProxy: Self = castOrFatalError(proxy)
if currentDelegate !== delegateProxy {
delegateProxy.setForwardToDelegate(currentDelegate, retainDelegate: false)
assert(delegateProxy.forwardToDelegate() === currentDelegate)
self.setCurrentDelegate(proxy, to: object)
assert(self.currentDelegate(for: object) === proxy)
assert(delegateProxy.forwardToDelegate() === currentDelegate)
}
return delegateProxy
}
/// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate.
/// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations.
///
/// - parameter forwardDelegate: Delegate object to set.
/// - parameter retainDelegate: Retain `forwardDelegate` while it's being set.
/// - parameter onProxyForObject: Object that has `delegate` property.
/// - returns: Disposable object that can be used to clear forward delegate.
public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable {
weak var weakForwardDelegate: AnyObject? = forwardDelegate
let proxy = self.proxy(for: object)
assert(proxy.forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" +
"If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" +
" This is the source object value: \(object)\n" +
" This this the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" +
"Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n")
proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate)
return Disposables.create {
MainScheduler.ensureExecutingOnScheduler()
let delegate: AnyObject? = weakForwardDelegate
assert(delegate == nil || proxy.forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)")
proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate)
}
}
}
// fileprivate extensions
extension DelegateProxyType
{
fileprivate static var factory: DelegateProxyFactory {
return DelegateProxyFactory.sharedFactory(for: self)
}
fileprivate static func assignedProxy(for object: ParentObject) -> Delegate? {
let maybeDelegate = objc_getAssociatedObject(object, self.identifier)
return castOptionalOrFatalError(maybeDelegate.map { $0 as AnyObject })
}
fileprivate static func assignProxy(_ proxy: Delegate, toObject object: ParentObject) {
objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN)
}
}
/// Describes an object that has a delegate.
public protocol HasDelegate: AnyObject {
/// Delegate type
associatedtype Delegate: AnyObject
/// Delegate
var delegate: Delegate? { get set }
}
extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate {
public static func currentDelegate(for object: ParentObject) -> Delegate? {
return object.delegate
}
public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) {
object.delegate = delegate
}
}
/// Describes an object that has a data source.
public protocol HasDataSource: AnyObject {
/// Data source type
associatedtype DataSource: AnyObject
/// Data source
var dataSource: DataSource? { get set }
}
extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource {
public static func currentDelegate(for object: ParentObject) -> Delegate? {
return object.dataSource
}
public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) {
object.dataSource = delegate
}
}
#if os(iOS) || os(tvOS)
import UIKit
extension ObservableType {
func subscribeProxyDataSource<DelegateProxy: DelegateProxyType>(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event<E>) -> Void)
-> Disposable
where DelegateProxy.ParentObject: UIView {
let proxy = DelegateProxy.proxy(for: object)
let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object)
// this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75)
object.layoutIfNeeded()
let subscription = self.asObservable()
.observeOn(MainScheduler())
.catchError { error in
bindingError(error)
return Observable.empty()
}
// source can never end, otherwise it would release the subscriber, and deallocate the data source
.concat(Observable.never())
.takeUntil(object.rx.deallocated)
.subscribe { [weak object] (event: Event<E>) in
if let object = object {
assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))")
}
binding(proxy, event)
switch event {
case .error(let error):
bindingError(error)
unregisterDelegate.dispose()
case .completed:
unregisterDelegate.dispose()
default:
break
}
}
return Disposables.create { [weak object] in
subscription.dispose()
object?.layoutIfNeeded()
unregisterDelegate.dispose()
}
}
}
#endif
/**
To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other
part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching).
class RxScrollViewDelegateProxy: DelegateProxy {
public static func registerKnownImplementations() {
self.register { RxTableViewDelegateProxy(parentObject: $0) }
}
...
*/
private class DelegateProxyFactory {
private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:]
fileprivate static func sharedFactory<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory {
MainScheduler.ensureExecutingOnScheduler()
let identifier = DelegateProxy.identifier
if let factory = _sharedFactories[identifier] {
return factory
}
let factory = DelegateProxyFactory(for: proxyType)
_sharedFactories[identifier] = factory
DelegateProxy.registerKnownImplementations()
return factory
}
private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)]
private var _delegateProxyType: Any.Type
private var _identifier: UnsafeRawPointer
private init<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) {
_factories = [:]
_delegateProxyType = proxyType
_identifier = proxyType.identifier
}
fileprivate func extend<DelegateProxy: DelegateProxyType, ParentObject>(make: @escaping (ParentObject) -> DelegateProxy)
{
MainScheduler.ensureExecutingOnScheduler()
precondition(_identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier")
precondition((DelegateProxy.self as? DelegateProxy.Delegate) != nil, "DelegateProxy subclass should be as a Delegate")
guard _factories[ObjectIdentifier(ParentObject.self)] == nil else {
rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.")
}
_factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) }
}
fileprivate func createProxy(for object: AnyObject) -> AnyObject {
MainScheduler.ensureExecutingOnScheduler()
var maybeMirror: Mirror? = Mirror(reflecting: object)
while let mirror = maybeMirror {
if let factory = _factories[ObjectIdentifier(mirror.subjectType)] {
return factory(object)
}
maybeMirror = mirror.superclassMirror
}
rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.")
}
}
#endif
| isc | 867fc19bc7b12da6e5e715f0d1ab8245 | 43.255696 | 358 | 0.602254 | 6.009282 | false | false | false | false |
GordonLY/LYPopMenu | LYPopMenuDemo/LYPopMenuDemo/LYPopMenu/LYPopMenuStyle.swift | 1 | 1896 | //
// LYPopMenuStyle.swift
// LYPopMenuDemo
//
// Created by Gordon on 2017/8/31.
// Copyright © 2017年 Gordon. All rights reserved.
//
import UIKit
struct LYPopMenuStyle {
init() {
self.p_refreshStyle()
}
/// 屏幕遮罩背景色
var coverColor = UIColor.init(white: 0, alpha: 0.6)
/// 菜单的背景色
var menuBgColor = UIColor.white
/// 菜单的圆角
var menuCorner: CGFloat = 2
/// 菜单cell的width
var menuWidth: CGFloat = 120 {
didSet {
self.p_refreshStyle()
}
}
/// 菜单cell的height
var cellHeight: CGFloat = 40 {
didSet {
self.p_refreshStyle()
}
}
/// 菜单cell选中后的颜色
var cellHighlightColor = UIColor.init(red: 217.0/255, green: 217.0/255, blue: 217.0/255, alpha: 1)
/// 菜单小箭头的高度
var menuArrowHeight:CGFloat = 8
/// 菜单小箭头的宽度
var menuArrowWid:CGFloat = 12
/// 小图标的frame
var iconFrame = CGRect.zero
/// 小图标和文本之间的间距 (设置后,titleFrame无效)
var space: CGFloat = 0 {
didSet {
self.p_refreshStyle()
}
}
/// 文字的frame (设置后,space无效)
var titleFrame = CGRect.zero
/// 文字颜色
var titleColor = UIColor.black
/// 文字字体
var titleFont = UIFont.systemFont(ofSize: 14)
/// 分割线的左右的margin
var separateMargin: (left: CGFloat, right: CGFloat) = (0,0)
var separateColor = UIColor.init(red: 221.0/255, green: 221.0/255, blue: 221.0/255, alpha: 1)
private mutating func p_refreshStyle() {
iconFrame = CGRect.init(x: 0, y: 0, width: cellHeight, height: cellHeight)
titleFrame = CGRect.init(x: iconFrame.maxX + space, y: 0, width: menuWidth - iconFrame.maxX, height: cellHeight)
}
}
| mit | c858ea3c6fcda1fad12b177fce0fa1b0 | 24.477612 | 120 | 0.59051 | 3.505133 | false | false | false | false |
sakishum/mac2imgur | mac2imgur/LaunchServicesHelper.swift | 3 | 2893 | /* This file is part of mac2imgur.
*
* mac2imgur 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.
* mac2imgur 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 mac2imgur. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
// Refined version of http://stackoverflow.com/a/27442962
class LaunchServicesHelper {
let applicationURL = NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath)
var applicationIsInStartUpItems: Bool {
return itemReferencesInLoginItems.existingItem != nil
}
var itemReferencesInLoginItems: (existingItem: LSSharedFileListItem?, lastItem: LSSharedFileListItem?) {
let itemURL = UnsafeMutablePointer<Unmanaged<CFURL>?>.alloc(1)
let loginItemsList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue()
// Can't cast directly from CFArray to Swift Array, so the CFArray needs to be bridged to a NSArray first
let loginItemsListSnapshot: NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue()
if let loginItems = loginItemsListSnapshot as? [LSSharedFileListItem] {
for loginItem in loginItems {
if LSSharedFileListItemResolve(loginItem, 0, itemURL, nil) == noErr {
if let URL = itemURL.memory?.takeRetainedValue() {
// Check whether the item is for this application
if URL == applicationURL {
return (loginItem, loginItems.last)
}
}
}
}
// The application was not found in the startup list
return (nil, loginItems.last ?? kLSSharedFileListItemBeforeFirst.takeRetainedValue())
}
return (nil, nil)
}
func toggleLaunchAtStartup() {
let itemReferences = itemReferencesInLoginItems
let loginItemsList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue()
if let existingItem = itemReferences.existingItem {
// Remove application from login items
LSSharedFileListItemRemove(loginItemsList, existingItem)
} else {
// Add application to login items
LSSharedFileListInsertItemURL(loginItemsList, itemReferences.lastItem, nil, nil, applicationURL, nil, nil)
}
}
} | gpl-3.0 | 46fcd23243355339674adfc520d0d7f8 | 46.442623 | 137 | 0.684411 | 5.156863 | false | false | false | false |
szk-atmosphere/URLEmbeddedView | URLEmbeddedView/Core/Entity/OpenGraph.Data.swift | 1 | 5798 | //
// OpenGraph.Data.swift
// URLEmbeddedView
//
// Created by marty-suzuki on 2018/07/14.
// Copyright © 2018年 marty-suzuki. All rights reserved.
//
import Foundation
extension OpenGraph {
/// OGP object for Swift
public struct Data {
public private(set) var imageUrl: URL?
public private(set) var pageDescription: String?
public private(set) var pageTitle: String?
public private(set) var pageType: String?
public private(set) var siteName: String?
public private(set) var sourceUrl: URL?
public private(set) var url: URL?
}
}
extension OpenGraph.Data {
var isEmpty: Bool {
if let value = imageUrl?.absoluteString, !value.isEmpty {
return false
}
if let value = pageDescription, !value.isEmpty {
return false
}
if let value = pageTitle, !value.isEmpty {
return false
}
if let value = pageType, !value.isEmpty {
return false
}
if let value = siteName, !value.isEmpty {
return false
}
if let value = url?.absoluteString, !value.isEmpty {
return false
}
return true
}
init(ogData: OGData) {
imageUrl = URL(string: ogData.imageUrl)
pageDescription = ogData.pageDescription.isEmpty ? nil : ogData.pageDescription
pageTitle = ogData.pageTitle.isEmpty ? nil : ogData.pageTitle
pageType = ogData.pageType.isEmpty ? nil : ogData.pageType
siteName = ogData.siteName.isEmpty ? nil : ogData.siteName
sourceUrl = URL(string: ogData.sourceUrl)
url = URL(string: ogData.url)
}
init(youtube: OpenGraph.Youtube, sourceUrl: String) {
self.pageTitle = youtube.title
self.pageType = youtube.type
self.siteName = youtube.providerName
self.imageUrl = URL(string: youtube.thumbnailUrl)
self.pageDescription = youtube.authorName
let url = URL(string: sourceUrl)
self.sourceUrl = url
self.url = url
}
static func empty() -> OpenGraph.Data {
return .init(imageUrl: nil,
pageDescription: nil,
pageTitle: nil,
pageType: nil,
siteName: nil,
sourceUrl: nil,
url: nil)
}
}
extension OpenGraph.Data {
private enum PropertyName {
case description
case image
case siteName
case title
case type
case url
init?(_ meta: OpenGraph.HTML.Metadata) {
let property = meta.property
let content = meta.content
if property.contains("og:description") {
self = .description
} else if property.contains("og:image") && content.contains("http") {
self = .image
} else if property.contains("og:site_name") {
self = .siteName
} else if property.contains("og:title") {
self = .title
} else if property.contains("og:type") {
self = .type
} else if property.contains("og:url") {
self = .url
} else {
return nil
}
}
}
init(sourceUrl: String) {
self.imageUrl = nil
self.pageDescription = nil
self.pageTitle = nil
self.pageType = nil
self.siteName = nil
self.sourceUrl = URL(string: sourceUrl)
self.url = nil
}
init(html: OpenGraph.HTML, sourceUrl: String) {
let data = html.metaList.reduce(into: OpenGraph.Data(sourceUrl: sourceUrl)) { result, meta in
guard let propertyName = PropertyName(meta) else {
return
}
switch propertyName {
case .siteName:
result.siteName = meta.content
case .type:
result.pageType = meta.content
case .title:
result.pageTitle = (try? meta.unescapedContent()) ?? ""
case .image:
result.imageUrl = URL(string: meta.content)
case .url:
result.url = URL(string: meta.content)
case .description :
result.pageDescription = ((try? meta.unescapedContent()) ?? "")
.replacingOccurrences(of: "\n", with: " ")
}
}
self.imageUrl = data.imageUrl
self.pageDescription = data.pageDescription
self.pageTitle = data.pageTitle
self.pageType = data.pageType
self.siteName = data.siteName
self.sourceUrl = data.sourceUrl
self.url = data.url
}
}
extension OpenGraph.Data: _ObjectiveCBridgeable {
public typealias _ObjectiveCType = OpenGraphData
private init(source: OpenGraphData) {
self.imageUrl = source.imageUrl
self.pageDescription = source.pageDescription
self.pageTitle = source.pageTitle
self.pageType = source.pageType
self.siteName = source.siteName
self.sourceUrl = source.sourceUrl
self.url = source.url
}
public func _bridgeToObjectiveC() -> OpenGraphData {
return .init(source: self)
}
public static func _forceBridgeFromObjectiveC(_ source: OpenGraphData, result: inout OpenGraph.Data?) {
result = .init(source: source)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: OpenGraphData, result: inout OpenGraph.Data?) -> Bool {
_forceBridgeFromObjectiveC(source, result: &result)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: OpenGraphData?) -> OpenGraph.Data {
return .empty()
}
}
| mit | 1684d71668ae0d44a40f7e8a4dfe9270 | 29.989305 | 123 | 0.574461 | 4.734477 | false | false | false | false |
cikelengfeng/Jude | Jude/Antlr4/atn/ArrayPredictionContext.swift | 2 | 3806 | /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
public class ArrayPredictionContext: PredictionContext {
/// Parent can be null only if full ctx mode and we make an array
/// from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and
/// returnState == {@link #EMPTY_RETURN_STATE}.
public final var parents: [PredictionContext?]
/// Sorted for merge, no duplicates; if present,
/// {@link #EMPTY_RETURN_STATE} is always last.
public final let returnStates: [Int]
public convenience init(_ a: SingletonPredictionContext) {
// if a.parent == nil {
// // print("parent is nil")
// }
//self.init(new, PredictionContext[] {a.parent}, new, int[] {a.returnState});
let parents = [a.parent]
self.init(parents, [a.returnState])
}
public init(_ parents: [PredictionContext?], _ returnStates: [Int]) {
self.parents = parents
self.returnStates = returnStates
super.init(PredictionContext.calculateHashCode(parents, returnStates))
}
override
final public func isEmpty() -> Bool {
// since EMPTY_RETURN_STATE can only appear in the last position, we
// don't need to verify that size==1
return returnStates[0] == PredictionContext.EMPTY_RETURN_STATE
}
override
final public func size() -> Int {
return returnStates.count
}
override
final public func getParent(_ index: Int) -> PredictionContext? {
return parents[index]
}
override
final public func getReturnState(_ index: Int) -> Int {
return returnStates[index]
}
// @Override
// public int findReturnState(int returnState) {
// return Arrays.binarySearch(returnStates, returnState);
// }
override
public var description: String {
if isEmpty() {
return "[]"
}
let buf: StringBuilder = StringBuilder()
buf.append("[")
let length = returnStates.count
for i in 0..<length {
if i > 0 {
buf.append(", ")
}
if returnStates[i] == PredictionContext.EMPTY_RETURN_STATE {
buf.append("$")
continue
}
buf.append(returnStates[i])
if parents[i] != nil {
buf.append(" ")
buf.append(parents[i].debugDescription)
} else {
buf.append("null")
}
}
buf.append("]")
return buf.toString()
}
internal final func combineCommonParents() {
let length = parents.count
var uniqueParents: Dictionary<PredictionContext, PredictionContext> =
Dictionary<PredictionContext, PredictionContext>()
for p in 0..<length {
if let parent: PredictionContext = parents[p] {
// if !uniqueParents.keys.contains(parent) {
if uniqueParents[parent] == nil {
uniqueParents[parent] = parent // don't replace
}
}
}
for p in 0..<length {
if let parent: PredictionContext = parents[p] {
parents[p] = uniqueParents[parent]
}
}
}
}
public func ==(lhs: ArrayPredictionContext, rhs: ArrayPredictionContext) -> Bool {
if lhs === rhs {
return true
}
if lhs.hashValue != rhs.hashValue {
return false
}
// return lhs.returnStates == rhs.returnStates && lhs.parents == rhs.parents
return ArrayEquals(lhs.returnStates, rhs.returnStates) && ArrayEquals(lhs.parents, rhs.parents)
}
| mit | 3443aa709fa3a3c677d66d37b9244024 | 29.448 | 99 | 0.58145 | 4.585542 | false | false | false | false |
shunabcd/FirebaseSocialLoginSample-swift | FirebaseSocialLoginSample/Controller/AccountHomeViewController.swift | 1 | 5010 | //
// AccountHomeViewController.swift
// FirebaseSocialLoginSample
//
// Created by S-SAKU on 2016/11/26.
// Copyright © 2016年 S-SAKU. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
class AccountHomeViewController: SocialLoginService {
@IBOutlet weak var tableView: UITableView!
let SECTION_IDX_PROFILE = 0
let SECTION_IDX_PROVIDERS = 1
var arySection:[(title:String,rcnt:Int)] = [("",1),("Linked Providers",0)]
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Event
@IBAction func btnDispNameEdit_Tap(_ sender: Any) {
showAlertInput(title:"Edit AppDispName",msg: "Set App Display Name") { (userPressedOK, input) in
guard let userInput = input else{
return
}
if userInput == ""{
self.showAlertMsgOk(msg:"App Display Name can't be empty")
}else{
self.showAlertWithSpin(){
let changeRequest = FIRAuth.auth()?.currentUser?.profileChangeRequest()
changeRequest?.displayName = userInput
changeRequest?.commitChanges(){ (error) in
self.hideAlertWithSpin(){
if let err = error {
self.showAlertMsgOk(title: "Error",msg: err.localizedDescription)
}
self.tableView.reloadData()
}
}
}
}
}
}
@IBAction func btnLogout_Tap(_ sender: Any) {
logout(){
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SocialLogin") {
self.present(viewController, animated: true, completion: nil)
}
}
}
}
extension AccountHomeViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return arySection.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return arySection[section].title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case SECTION_IDX_PROFILE:
return arySection[section].rcnt
case SECTION_IDX_PROVIDERS:
if let user = FIRAuth.auth()?.currentUser {
return user.providerData.count
}
return 0
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell?
switch (indexPath as NSIndexPath).section {
case SECTION_IDX_PROFILE:
cell = tableView.dequeueReusableCell(withIdentifier: "Profile")
let user = FIRAuth.auth()?.currentUser
let txvEmail = cell?.viewWithTag(1) as? UITextView
let lblDispNm = cell?.viewWithTag(2) as? UILabel
let txvUserID = cell?.viewWithTag(3) as? UITextView
let imvAvatar = cell?.viewWithTag(4) as? UIImageView
txvEmail?.text = user?.email
lblDispNm?.text = user?.displayName
txvUserID?.text = user?.uid
let photoURL = user?.photoURL
let lastPhotoURL: URL? = photoURL
if let photoURL = photoURL {
DispatchQueue.global(qos: .default).async {
let data = try? Data.init(contentsOf: photoURL)
if let data = data {
let image = UIImage.init(data: data)
DispatchQueue.main.async(execute: {
if photoURL == lastPhotoURL {
imvAvatar?.image = image
}
})
}
}
} else {
imvAvatar?.image = UIImage.init(named: "avatar")
}
case SECTION_IDX_PROVIDERS:
cell = tableView.dequeueReusableCell(withIdentifier: "Provider")
let userInfo = FIRAuth.auth()?.currentUser?.providerData[(indexPath as NSIndexPath).row]
cell?.textLabel?.text = userInfo?.providerID
cell?.detailTextLabel?.text = userInfo?.uid
default:
fatalError("Unknown section in UITableView")
}
return cell!
}
}
extension AccountHomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath as NSIndexPath).section == SECTION_IDX_PROFILE {
return 270
}
return 45
}
}
| mit | dee77b2b173001ea28bfdfdbec0061c4 | 32.15894 | 111 | 0.565009 | 5.259454 | false | false | false | false |
DaVinAhn/EPubParser | EPubParser/EPubHelper.swift | 1 | 13140 | //
// EPubHelper.swift
// EPubParser
//
// Created by Davin Ahn on 2017. 1. 8..
// Copyright © 2017년 Davin Ahn. All rights reserved.
//
import Foundation
import minizip
public enum UnzipError: Error {
case notFile(url: URL)
case notDirectory(path: String)
case alreadyExistsDirectory(path: String)
case fileNotFound(path: String)
case fileNotSupport(path: String)
case openFail(path: String)
case unzipFail(path: String)
case crcError(path: String)
case encodingError(path: String)
case invalidPackaging(path: String)
}
fileprivate struct UnzipOptionKey: RawRepresentable, Hashable {
fileprivate var rawValue: String
fileprivate var hashValue: Int {
return rawValue.hash
}
fileprivate static let toPath = UnzipOptionKey(rawValue: "toPath")
fileprivate static let overwrite = UnzipOptionKey(rawValue: "overwrite")
fileprivate static let checkCrc = UnzipOptionKey(rawValue: "checkCrc")
}
internal extension String {
private var nsString: NSString {
return (self as NSString)
}
var lastPathComponent: String {
return nsString.lastPathComponent
}
var pathExtension: String {
return nsString.pathExtension
}
var deletingLastPathComponent: String {
return nsString.deletingLastPathComponent
}
var deletingPathExtension: String {
return nsString.deletingPathExtension
}
var pathComponents: [String] {
return nsString.pathComponents
}
func appendingPathComponent(_ str: String) -> String {
return nsString.appendingPathComponent(str)
}
func appendingPathExtension(_ str: String) -> String? {
return nsString.appendingPathExtension(str)
}
}
fileprivate extension Date {
static func dateFrom(tmuDate: tm_unz_s) -> Date {
var dateComponents = DateComponents()
dateComponents.second = Int(tmuDate.tm_sec)
dateComponents.minute = Int(tmuDate.tm_min)
dateComponents.hour = Int(tmuDate.tm_hour)
dateComponents.day = Int(tmuDate.tm_mday)
dateComponents.month = Int(tmuDate.tm_mon) + 1
dateComponents.year = Int(tmuDate.tm_year)
let calendar = Calendar.current
return calendar.date(from: dateComponents) ?? Date()
}
}
internal class EPubHelper {
fileprivate static var supportedZipExtensions = ["epub", "zip"]
fileprivate static var unzipBufferSize: UInt32 = 4096
fileprivate static var zipHeaderSize = 58
internal class func validateZipAt(_ path: String) throws {
try validateZipAt(URL(fileURLWithPath: path))
}
internal class func validateZipAt(_ url: URL) throws {
if !url.isFileURL {
throw UnzipError.notFile(url: url)
}
let fileManager = FileManager.default
let path = url.path
if !fileManager.fileExists(atPath: path) {
throw UnzipError.fileNotFound(path: path)
}
if !supportedZipExtensions.contains(path.pathExtension.lowercased()) {
throw UnzipError.fileNotSupport(path: path)
}
guard let data = try? Data(contentsOf: url), data.count >= zipHeaderSize else {
throw UnzipError.openFail(path: path)
}
let bytes = [UInt8](data)
let fileSignature = String(bytes: bytes[0..<2], encoding: String.Encoding.ascii)
let fileNameSize = UInt32(littleEndian: Data(bytes: bytes[26..<28]).withUnsafeBytes { $0.pointee })
let extraFieldSize = UInt32(littleEndian: Data(bytes: bytes[28..<30]).withUnsafeBytes { $0.pointee })
let fileName = String(bytes: bytes[30..<38], encoding: String.Encoding.ascii)
let mimetype = String(bytes: bytes[38..<zipHeaderSize], encoding: String.Encoding.ascii)
if fileSignature != "PK"
|| fileNameSize != 8
|| extraFieldSize != 0
|| fileName != "mimetype"
|| mimetype != "application/epub+zip" {
throw UnzipError.invalidPackaging(path: path)
}
}
internal class func entriesOfZipAt(_ url: URL, password: String?) throws -> [String] {
if !url.isFileURL {
throw UnzipError.notFile(url: url)
}
return try entriesOfZipAt(url.path, password: password)
}
internal class func entriesOfZipAt(_ path: String, password: String?) throws -> [String] {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
throw UnzipError.fileNotFound(path: path)
}
if !supportedZipExtensions.contains(path.pathExtension.lowercased()) {
throw UnzipError.fileNotSupport(path: path)
}
return try unzipAt(path, password: password, options: [
UnzipOptionKey.checkCrc: false
])
}
internal class func dataOf(_ entryPath: String, atZipPath zipPath: String, password: String?) throws -> Data {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: zipPath) {
throw UnzipError.fileNotFound(path: zipPath)
}
if !supportedZipExtensions.contains(zipPath.pathExtension.lowercased()) {
throw UnzipError.fileNotSupport(path: zipPath)
}
guard let zip = unzOpen64(zipPath) else {
throw UnzipError.openFail(path: zipPath)
}
defer { unzClose(zip) }
if unzGoToFirstFile(zip) != UNZ_OK {
throw UnzipError.openFail(path: zipPath)
}
guard let path = entryPath.cString(using: String.Encoding.ascii) else {
throw UnzipError.encodingError(path: entryPath)
}
var ret = unzLocateFile(zip, path) { (_, fileName1, fileName2) -> Int32 in
return strcasecmp(fileName1, fileName2)
}
if ret != UNZ_OK {
throw UnzipError.fileNotFound(path: entryPath)
}
if let password = password?.cString(using: String.Encoding.ascii) {
ret = unzOpenCurrentFilePassword(zip, password)
} else {
ret = unzOpenCurrentFile(zip)
}
if ret != UNZ_OK {
throw UnzipError.unzipFail(path: entryPath)
}
let data = NSMutableData()
var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(unzipBufferSize))
repeat {
let readBytes = Int(unzReadCurrentFile(zip, &buffer, unzipBufferSize))
if readBytes > 0 {
data.append(buffer, length: readBytes)
} else {
break
}
} while true
unzCloseCurrentFile(zip)
return data as Data
}
internal class func unzipAt(_ url: URL, to: URL, password: String?, overwrite: Bool = true) throws -> [String] {
if !url.isFileURL {
throw UnzipError.notFile(url: url)
} else if !to.isFileURL {
throw UnzipError.notFile(url: to)
}
return try unzipAt(url.path, toPath: to.path, password: password, overwrite: overwrite)
}
internal class func unzipAt(_ path: String, toPath: String, password: String?, overwrite: Bool = true) throws -> [String] {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
throw UnzipError.fileNotFound(path: path)
}
if !supportedZipExtensions.contains(path.pathExtension.lowercased()) {
throw UnzipError.fileNotSupport(path: path)
}
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: toPath, isDirectory: &isDirectory) {
if !isDirectory.boolValue {
throw UnzipError.notDirectory(path: toPath)
} else if overwrite {
try fileManager.removeItem(atPath: toPath)
} else {
throw UnzipError.alreadyExistsDirectory(path: toPath)
}
} else {
try fileManager.createDirectory(atPath: toPath, withIntermediateDirectories: true, attributes: nil)
}
return try unzipAt(path, password: password, options: [
UnzipOptionKey.toPath: toPath,
UnzipOptionKey.overwrite: overwrite
])
}
fileprivate class func unzipAt(_ path: String, password: String?, options: [UnzipOptionKey: Any]) throws -> [String] {
guard let zip = unzOpen64(path) else {
throw UnzipError.openFail(path: path)
}
defer { unzClose(zip) }
if unzGoToFirstFile(zip) != UNZ_OK {
throw UnzipError.openFail(path: path)
}
let fileManager = FileManager.default
let toPath = options[.toPath] as? String ?? ""
let overwrite = options[.overwrite] as? Bool ?? true
let checkCrc = options[.checkCrc] as? Bool ?? true
let readOnly = toPath.isEmpty
var ret: Int32 = 0
var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(unzipBufferSize))
var entries = [String]()
repeat {
if let password = password?.cString(using: String.Encoding.ascii) {
ret = unzOpenCurrentFilePassword(zip, password)
} else {
ret = unzOpenCurrentFile(zip)
}
if ret != UNZ_OK {
throw UnzipError.unzipFail(path: path)
}
var fileInfo = unz_file_info64()
memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size)
ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0)
if ret != UNZ_OK {
unzCloseCurrentFile(zip)
throw UnzipError.unzipFail(path: path)
}
let fileNameSize = Int(fileInfo.size_filename) + 1
let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize)
unzGetCurrentFileInfo64(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0)
fileName[Int(fileInfo.size_filename)] = 0
var entryPath = String(cString: fileName)
if entryPath.characters.isEmpty {
unzCloseCurrentFile(zip)
throw UnzipError.unzipFail(path: path)
}
var isDirectory = false
let fileInfoSize = Int(fileInfo.size_filename - 1)
if (fileName[fileInfoSize] == "/".cString(using: String.Encoding.utf8)?.first
|| fileName[fileInfoSize] == "\\".cString(using: String.Encoding.utf8)?.first) {
isDirectory = true
}
free(fileName)
if entryPath.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\")) != nil {
entryPath = entryPath.replacingOccurrences(of: "\\", with: "/")
}
let fullPath = toPath.appendingPathComponent(entryPath)
entries.append(entryPath)
if readOnly {
let crc_ret = unzCloseCurrentFile(zip)
if checkCrc && crc_ret == UNZ_CRCERROR {
throw UnzipError.crcError(path: path)
}
ret = unzGoToNextFile(zip)
continue
}
do {
if isDirectory {
try fileManager.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: nil)
} else {
try fileManager.createDirectory(atPath: fullPath.deletingLastPathComponent, withIntermediateDirectories: true, attributes: nil)
}
} catch {}
if fileManager.fileExists(atPath: fullPath) && !isDirectory && !overwrite {
unzCloseCurrentFile(zip)
ret = unzGoToNextFile(zip)
}
let file = fopen(fullPath, "wb")
while file != nil {
let readBytes = unzReadCurrentFile(zip, &buffer, unzipBufferSize)
if readBytes > 0 {
fwrite(buffer, Int(readBytes), 1, file)
} else {
break
}
}
if file != nil {
fclose(file)
if fileInfo.dosDate != 0 {
let originDate = Date.dateFrom(tmuDate: fileInfo.tmu_date)
do {
let attr = [FileAttributeKey.modificationDate: originDate]
try fileManager.setAttributes(attr, ofItemAtPath: fullPath)
} catch {}
}
}
let crc_ret = unzCloseCurrentFile(zip)
if checkCrc && crc_ret == UNZ_CRCERROR {
throw UnzipError.crcError(path: path)
}
ret = unzGoToNextFile(zip)
} while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE)
return entries
}
}
| apache-2.0 | d577d161e33c781d45e874102445e9c6 | 36.005634 | 147 | 0.580955 | 4.683422 | false | false | false | false |
caxco93/peliculas | DemoWS/Clases generales/CDMImageDownloaded/CDMImageDownloaded.swift | 1 | 4844 | //
// CDMImageDownloaded.swift
// DemoWS
//
// Created by Benjamin Eyzaguirre on 28/09/16.
// Copyright © 2016 Core Data Media. All rights reserved.
//
import UIKit
class CDMImageDownloaded: NSObject {
static let CDMImageDownloadedDirectorioDescarga = "Caches"
class func guardar(imagen aImagen : UIImage?, conNombre nombre : String?, enDirectorio directorio : String?) -> Bool {
if aImagen == nil || nombre == nil {
return false
}
let documentsPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString
let cachesPath = documentsPath.appendingPathComponent(directorio != nil ? directorio! : self.CDMImageDownloadedDirectorioDescarga) as NSString
let filePath = cachesPath.appendingPathComponent(nombre!)
let data = nombre?.hasSuffix("jpg") == true ? UIImageJPEGRepresentation(aImagen!, 1.0) : UIImagePNGRepresentation(aImagen!)
do{
try data?.write(to: URL.init(fileURLWithPath: filePath), options: Data.WritingOptions.atomic)
print("OSPImageDownloaded / Se guardó la imagen \(nombre!)")
return true
}catch{
print("OSPImageDownloaded / NO se guardó la imagen \(nombre!)")
return false
}
}
class func obtenerImagen(conNombre nombre : String?, enDirectorio directorio : String?) -> UIImage? {
if nombre == nil {
return nil
}
var imagen : UIImage?
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString
let cachesPath = documentsPath.appendingPathComponent(directorio != nil ? directorio! : self.CDMImageDownloadedDirectorioDescarga) as NSString
let filePath = cachesPath.appendingPathComponent(nombre!)
if fileManager.fileExists(atPath: filePath){
imagen = UIImage(contentsOfFile: filePath)
}
return imagen
}
class func descargarImagen(enURL url : String?, conNombre nombre : String?) -> UIImage?{
if url == nil || nombre == nil {
return nil
}
let urlDescarga = URL.init(string: url!)
if urlDescarga == nil {
return nil
}
do{
let dataImagenDescarga = try Data.init(contentsOf: urlDescarga!)
let imgDescargada = UIImage(data: dataImagenDescarga)
return self.guardar(imagen: imgDescargada, conNombre: nombre, enDirectorio: nil) == true ? self.obtenerImagen(conNombre: nombre, enDirectorio: nil) : nil
}catch{
return nil
}
}
class func asignarConAnimacion(laImagen nuevaImagen : UIImage?, enImageView imageView : UIImageView, conTransicion transicion : String?) {
imageView.image = nuevaImagen
let transition = CATransition.init()
transition.duration = 0.35
transition.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = transicion != nil ? transicion! : kCATransitionFade
imageView.layer.add(transition, forKey: nil)
}
class func descargarImagen(enURL url : String?, paraImageView imageViewFoto : UIImageView, conPlaceHolder imgPlaceHolder : UIImage?, conCompletion completion : @escaping(_ descargaCorrecta : Bool, _ nombreArchivo : String?, _ imagen : UIImage?) -> Void) {
imageViewFoto.image = imgPlaceHolder
var nombre : String? = url == nil ? nil : NSString(string: url!).lastPathComponent
nombre = nombre?.hasSuffix("jpg") == true ? nombre?.replacingOccurrences(of: ".jpg", with: "@2x.jpg") : nombre?.replacingOccurrences(of: ".png", with: "@2x.png")
DispatchQueue.global(qos: .default).async {
let imagenGuardada = self.obtenerImagen(conNombre: nombre, enDirectorio: nil)
if imagenGuardada == nil {
let imagenDescargada = self.descargarImagen(enURL: url, conNombre: nombre)
DispatchQueue.main.async {
completion( imagenDescargada != nil ? true : false, url, imagenDescargada != nil ? imagenDescargada : imgPlaceHolder)
}
}else{
DispatchQueue.main.async {
completion( true, url, imagenGuardada)
}
}
}
}
}
| mit | 88a50e306e1f38640c0e794b1aa76ac5 | 35.398496 | 259 | 0.5912 | 4.836164 | false | false | false | false |
khizkhiz/swift | test/DebugInfo/patternmatching.swift | 2 | 3067 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o %t.ll
// RUN: FileCheck %s < %t.ll
// RUN: FileCheck --check-prefix=CHECK-SCOPES %s < %t.ll
// RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -primary-file %s -o - | FileCheck %s --check-prefix=SIL-CHECK
func markUsed<T>(t: T) {}
func classifyPoint2(p: (Double, Double)) {
func return_same (input : Double) -> Double
{
return input; // return_same gets called in both where statements
}
switch p {
case (let x, let y) where
// CHECK: call double {{.*}}return_same{{.*}}, !dbg ![[LOC1:.*]]
// CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC2:.*]]
// CHECK: call{{.*}}markUsed{{.*}}, !dbg ![[LOC3:.*]]
// CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+2]],
// CHECK: ![[LOC2]] = !DILocation(line: [[@LINE+1]],
return_same(x) == return_same(y):
// CHECK: ![[LOC3]] = !DILocation(line: [[@LINE+1]],
markUsed(x)
// SIL-CHECK: dealloc_stack{{.*}}line:[[@LINE-1]]:17:cleanup
// Verify that the branch has a location >= the cleanup.
// SIL-CHECK-NEXT: br{{.*}}line:[[@LINE-3]]:17:cleanup
// CHECK-SCOPES: call {{.*}}markUsed
// CHECK-SCOPES: call void @llvm.dbg.value({{.*}}metadata ![[X1:[0-9]+]]
// CHECK-SCOPES-SAME: !dbg ![[X1LOC:[0-9]+]]
// CHECK-SCOPES: call void @llvm.dbg.value
// CHECK-SCOPES: call void @llvm.dbg.value({{.*}}metadata ![[X2:[0-9]+]]
// CHECK-SCOPES-SAME: !dbg ![[X2LOC:[0-9]+]]
// CHECK-SCOPES: call void @llvm.dbg.value
// CHECK-SCOPES: call void @llvm.dbg.value({{.*}}metadata ![[X3:[0-9]+]]
// CHECK-SCOPES-SAME: !dbg ![[X3LOC:[0-9]+]]
// CHECK-SCOPES: !DILocalVariable(name: "x",
case (let x, let y) where x == -y:
// Verify that all variables end up in separate appropriate scopes.
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE1:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-3]]
// CHECK-SCOPES: ![[X1LOC]] = !DILocation(line: [[@LINE-4]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE1]])
// FIXME: ![[SCOPE1]] = distinct !DILexicalBlock({{.*}}line: [[@LINE-6]]
markUsed(x)
case (let x, let y) where x >= -10 && x < 10 && y >= -10 && y < 10:
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE2:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-2]]
// CHECK-SCOPES: ![[X2LOC]] = !DILocation(line: [[@LINE-3]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE2]])
markUsed(x)
case (let x, let y):
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE3:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-2]]
// CHECK-SCOPES: ![[X3LOC]] = !DILocation(line: [[@LINE-3]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE3]])
markUsed(x)
}
// CHECK: !DILocation(line: [[@LINE+1]],
}
| apache-2.0 | 32b7e0294f114a74a3db4c63a09c88bf | 50.983051 | 120 | 0.515487 | 3.248941 | false | false | false | false |
ZB0106/MCSXY | MCSXY/MCSXY/Bussniess/Live/VIewModels/MCLivePreDataViewModel.swift | 1 | 1468 | //
// MCLivePreDataViewModel.swift
// MCSXY
//
// Created by 瞄财网 on 2017/7/17.
// Copyright © 2017年 瞄财网. All rights reserved.
//
import Foundation
import SwiftyJSON
class MCLivePreDataViewModel: ZB_DataTableViewModel {
override func ZB_loadData(dataHandeler: ((Any) -> Void)?, failureHandeler: handelerFailureBlock?) {
super.ZB_loadData(dataHandeler: dataHandeler, failureHandeler: failureHandeler)
MCRequestTool .ZB_request(requestModelBlock: { () -> ZB_NetWorkModel in
return MCLivePreRequestModel.init()
}, requestHandel: { (json) in
if let dataHandeler = dataHandeler {
//对json数据进行处理
if let json = json as? JSON {
let array = json["data"]["page"].arrayValue
var arrayM :Array<JSON> = []
for json in array{
var jsM = json
jsM[cellHeight] = 110.0
arrayM .append(jsM)
}
let jsonArray :JSON = [[headerHeight:0.01, footerHeight:0.01, cellDataArray:arrayM]]
dataHandeler(jsonArray.arrayValue)
}
}
}) { (error) in
if let failureHandeler = failureHandeler {
failureHandeler(error)
}
}
}
}
| mit | ec9880866605f7f690119f90d54a756e | 30.282609 | 104 | 0.512161 | 4.244838 | false | false | false | false |
jtekenos/ios_schedule | detailsViewController.swift | 1 | 2197 | //
// detailsViewController.swift
// ios_schedule
//
// Created by Denis Turitsa on 2015-11-29.
// Copyright © 2015 Jess. All rights reserved.
//
import UIKit
import Parse
class detailsViewController: UIViewController {
var id: String = ""
var pulledEvent: PFObject!
@IBAction func deleteButton(sender: AnyObject) {
pulledEvent.deleteInBackground()
self.performSegueWithIdentifier("detailsToSchedule", sender: self)
}
@IBOutlet weak var deleteButOutlet: UIButton!
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var setLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
userSettings()
getEvent()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getEvent(){
var query = PFQuery(className:"Schedule")
query.whereKey("objectId", equalTo: id)
do{
pulledEvent = try query.findObjects().first as PFObject!
titleLabel.text = pulledEvent["eventName"] as! String
setLabel.text = "Set: " + (pulledEvent["classSet"] as! String)
detailsLabel.text = pulledEvent["eventDescription"] as! String
let date = pulledEvent["date"] as! NSDate
let f = NSDateFormatter()
f.dateFormat = "HH:mm EEEE MMMM dd yyyy"
dateLabel.text = f.stringFromDate(date)
} catch{}
}
func userSettings(){
var userquery = PFUser.query()
userquery!.whereKey("username", equalTo:PFUser.currentUser()!.username!)
do{
var user = try userquery!.findObjects().first as! PFUser
let userRole = user["role"] as! String
if(userRole == "admin"){
self.deleteButOutlet.hidden = false
} else{
self.deleteButOutlet.hidden = true
}
} catch{}
}
}
| mit | c2357407ba07f08fb722bed821c07a42 | 26.797468 | 80 | 0.579235 | 4.945946 | false | false | false | false |
EtneteraMobile/ETMultiColumnView | Source/ETMultiColumnView+ConfigurationCalculations.swift | 1 | 5079 | //
// ETMultiColumnView+ConfigurationCalculations.swift
// ETMultiColumnView
//
// Created by Jan Čislinský on 17/02/2017.
//
//
import UIKit
// MARK: - Configuration.columnsWithSizes
public extension ETMultiColumnView.Configuration {
struct ColumnWrapper {
let column: ETMultiColumnView.Configuration.Column
let size: CGSize
let edges: Column.Layout.Edges
let borders: [Column.Layout.Border]
let alignment: Column.Layout.VerticalAlignment
}
internal func columnsWithSizes(in width: CGFloat) throws -> [ColumnWrapper] {
// Is width valid
guard width > 0.0 else { throw ETMultiColumnView.Error.invalidWidth }
// Calculates fitContent columns width
let precalculatedColumns: [Column] = columns.map {
if case .fit(maxOutWidth: let maxWidth, borders: _, edges: let edges, verticalAlignment: _) = $0.layout {
var col = $0
col.calculatedInnerSize = col.viewProvider.boundingSize(widthConstraint: (min(width, maxWidth) - edges.insets.horizontal))
return col
} else {
return $0
}
}
// Calculates fixed+fit columns width sum
var relativeColumnsCount = 0
let reservedColumnsWidth = precalculatedColumns.reduce(CGFloat(0.0)) { a, x in
if case .fix(outWidth: let width, borders: _, edges: _, verticalAlignment: _) = x.layout {
return a + width
} else if case .fit(maxOutWidth: _, borders: _, edges: let e, verticalAlignment: _) = x.layout {
return a + (x.calculatedInnerSize == nil ? 0.0 : x.calculatedInnerSize!.width + e.insets.horizontal)
} else {
relativeColumnsCount += 1
return a
}
}
let remainingWidth = width - reservedColumnsWidth
// Is width sufficient
guard remainingWidth >= 0.0 else {
let description = "Sum width of fixed and fit colums is greater than available width (reservedColumnsWidth=\(reservedColumnsWidth), columnWidth=\(width))."
throw ETMultiColumnView.Error.insufficientWidth(description: description)
}
let relativeColumnWidth = (remainingWidth > 0 ? floor(remainingWidth / CGFloat(relativeColumnsCount)) : 0.0)
// Calculates columns frame
let result:[ColumnWrapper] = try precalculatedColumns.map { col in
let edges: Column.Layout.Edges
let outWidth: CGFloat
let borders: [Column.Layout.Border]
let alignment: Column.Layout.VerticalAlignment
switch col.layout {
case let .rel(borders: b, edges: e, verticalAlignment: a):
borders = b
outWidth = relativeColumnWidth
edges = e
alignment = a
case let .fix(outWidth: w, borders: b, edges: e, verticalAlignment: a):
borders = b
outWidth = w
edges = e
alignment = a
case let .fit(maxOutWidth: _, borders: b, edges: e, verticalAlignment: a):
borders = b
outWidth = (col.calculatedInnerSize == nil ? 0.0 : col.calculatedInnerSize!.width + e.insets.horizontal)
edges = e
alignment = a
}
let verticalEdges = edges.insets.vertical
let horizontalEdges = edges.insets.horizontal
let inWidth = outWidth - horizontalEdges
if inWidth <= 0 {
// Relative column can have width = 0
if case .rel = col.layout {
// Hides column
return ColumnWrapper(column: col, size: .zero, edges: .zero, borders: [], alignment: alignment)
} else {
let description = "InWidth is negative or 0, horizontal edges are longer than cell width (horizontalEdges=\(horizontalEdges), columnWidth=\(outWidth))."
throw ETMultiColumnView.Error.insufficientWidth(description: description)
}
}
let size: CGSize
if let calculated = col.calculatedInnerSize {
size = calculated
} else {
let boundingSize = col.viewProvider.boundingSize(widthConstraint: inWidth)
size = CGSize(width: max(inWidth, boundingSize.width), height: boundingSize.height)
}
let height = size.height
guard size.width <= inWidth else {
let description = "Width of custom view is loonger than given width of cell content view (provider.viewSize().width=\(size.width), inWidth=\(inWidth))."
throw ETMultiColumnView.Error.insufficientWidth(description: description)
}
return ColumnWrapper(column: col, size: CGSize(width: ceil(outWidth), height: ceil(height + verticalEdges)), edges: edges, borders: borders, alignment: alignment)
}
return result
}
}
| mit | a912e40922ca7752eb9972deb072cf50 | 40.958678 | 174 | 0.592279 | 4.933916 | false | false | false | false |
PrestonV/ios-cannonball | Cannonball/NativeAdCell.swift | 1 | 2246 | //
// Copyright (C) 2014 Twitter, Inc. and other 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 UIKit
import MoPub
class NativeAdCell: UITableViewCell, MPNativeAdRendering {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var mainTextLabel: UILabel!
@IBOutlet weak var callToActionButton: UIButton!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var containerView: UIView!
func layoutAdAssets(adObject: MPNativeAd!) {
// Load ad assets.
adObject.loadTitleIntoLabel(self.titleLabel)
adObject.loadTextIntoLabel(self.mainTextLabel)
adObject.loadCallToActionTextIntoLabel(self.callToActionButton.titleLabel)
adObject.loadImageIntoImageView(self.mainImageView)
adObject.loadIconIntoImageView(self.iconImageView)
// Decorate the call to action button.
callToActionButton.layer.masksToBounds = false
callToActionButton.layer.borderColor = callToActionButton.titleLabel?.textColor.CGColor
callToActionButton.layer.borderWidth = 2
callToActionButton.layer.cornerRadius = 6
// Decorate the ad container.
containerView.layer.cornerRadius = 6
// Add the background color to the main view.
self.backgroundColor = UIColor(red: 55/255, green: 31/255, blue: 31/255, alpha: 1.0)
}
class func sizeWithMaximumWidth(maximumWidth: CGFloat) -> CGSize {
return CGSizeMake(maximumWidth, maximumWidth)
}
// Return the nib used for the native ad.
class func nibForAd() -> UINib! {
return UINib(nibName: "NativeAdCell", bundle: nil)
}
}
| apache-2.0 | 6790dbf9a8f53f3e1cc15b00772f9ddd | 33.030303 | 95 | 0.71683 | 4.583673 | false | false | false | false |
Yalantis/EatFit | Demo/DemoProject/ViewController/ViewController.swift | 1 | 2462 | //
// ViewController.swift
// EatFit Demo Project
//
// Created by aleksey on 08.05.15.
// Copyright (c) 2015 Aleksey Chernish. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let eatFitController = EatFitViewController()
let objects: [ChartObject] = {
var objects: [ChartObject] = []
let filePath = Bundle.main.path(forResource: "Objects", ofType: "plist")
let contents = NSArray(contentsOfFile: filePath!)! as Array
for dictionary in contents {
let color = UIColor(hexString: dictionary["color"] as! String)
let percentage = dictionary["percentage"] as! Int
let title = dictionary["title"] as! String
let description = dictionary["description"] as! String
let logoName = dictionary["logoName"] as! String
let logoImage = UIImage(named: logoName)!
let object = ChartObject(color: color, percentage: percentage, title: title, description: description, logoImage: logoImage)
objects.append(object)
}
return objects
}()
override func viewDidLoad() {
super.viewDidLoad()
eatFitController.dataSource = self
eatFitController.view.frame = view.frame
addChild(eatFitController)
view.yal_addSubview(eatFitController.view, options: .overlay)
}
}
extension ViewController: EatFitViewControllerDataSource {
func numberOfPagesForPagingViewController(_ controller: EatFitViewController) -> Int {
return objects.count
}
func chartColorForPage(_ index: Int, forPagingViewController: EatFitViewController) -> UIColor {
return objects[index].color
}
func percentageForPage(_ index: Int, forPagingViewController: EatFitViewController) -> Int {
return objects[index].percentage
}
func titleForPage(_ index: Int, forPagingViewController: EatFitViewController) -> String {
return objects[index].title
}
func descriptionForPage(_ index: Int, forPagingViewController: EatFitViewController) -> String {
return objects[index].description
}
func logoForPage(_ index: Int, forPagingViewController: EatFitViewController) -> UIImage {
return objects[index].logoImage
}
func chartThicknessForPagingViewController(_ controller: EatFitViewController) -> CGFloat {
return 15
}
}
| mit | 40d9ddd72065af2121c0b122959e93b8 | 31.826667 | 136 | 0.663688 | 4.884921 | false | false | false | false |
davepatterson/SwiftValidator | SwiftValidator/Rules/FullNameRule.swift | 2 | 1428 | //
// FullNameValidation.swift
//
// Created by Jeff Potter on 11/19/14.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
/**
`FullNameRule` is a subclass of Rule that defines how a full name is validated.
*/
public class FullNameRule : Rule {
/// Error message to be displayed if validation fails.
private var message : String
/**
Initializes a `FullNameRule` object that is used to verify that text in text field is a full name.
- parameter message: String of error message.
- returns: An initialized `FullNameRule` object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(message : String = "Please provide a first & last name"){
self.message = message
}
/**
Used to validate a text field.
- parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
let nameArray: [String] = value.characters.split { $0 == " " }.map { String($0) }
return nameArray.count >= 2
}
/**
Used to display error message of a text field that has failed validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
} | mit | 9bc0862e4a872aaf98511621a5c0fa96 | 30.065217 | 149 | 0.646359 | 4.407407 | false | false | false | false |
wilzh40/ShirPrize-Me | SwiftSkeleton/ImageSaver.swift | 1 | 1729 | //
// ImageSaver.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 8/16/14.
// Copyright (c) 2014 Wilson Zhao. All rights reserved.
//
import Foundation
import UIKit
class ImageSaver {
var documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as NSString
func getImageFromUrl(urlString:NSString) -> UIImage {
var result:UIImage
var err:NSError?
var url:NSURL = NSURL.URLWithString(urlString)
var data:NSData = NSData.dataWithContentsOfURL(url, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
if err != nil {
println(err)
}
return UIImage(data: data)
}
func saveImage(image:UIImage,fileName:NSString,type:NSString,directory:NSString) {
var err:NSError?
if type.lowercaseString == "png" {
UIImagePNGRepresentation(image).writeToFile(directory.stringByAppendingPathComponent("\(fileName).png"), options:NSDataWritingOptions.DataWritingAtomic, error: &err)
}
else if type.lowercaseString == "jpg" || type.lowercaseString == "jpeg" {
UIImageJPEGRepresentation(image,1.0).writeToFile(directory.stringByAppendingPathComponent("\(fileName).jpg"), options:NSDataWritingOptions.DataWritingAtomic, error: &err)
} else {
println("Image Save Failed \(type)")
}
}
func loadImage(fileName:NSString,type:String,directory:NSString) -> UIImage {
var result:UIImage = NSData.dataWithContentsOfMappedFile("\(directory)/\(fileName).\(type)") as UIImage
return result
}
} | mit | dd51b70a8e426da2f02345132d56dcf4 | 37.444444 | 180 | 0.679005 | 4.968391 | false | false | false | false |
darkerk/v2ex | V2EX/ViewModel/TimelineViewModel.swift | 1 | 2933 | //
// TimelineViewModel.swift
// V2EX
//
// Created by darker on 2017/3/14.
// Copyright © 2017年 darker. All rights reserved.
//
import RxSwift
import Moya
class TimelineViewModel {
let sections = Variable<[TimelineSection]>([])
let joinTime = Variable<String>("")
let loadingActivityIndicator = ActivityIndicator()
var isFollowed: Bool = false
var isBlockd: Bool = false
private var tValue: String = ""
private var idValue: String = ""
private let disposeBag = DisposeBag()
func fetcTimeline(href: String) {
API.provider.request(API.timeline(userHref: href)).observeOn(MainScheduler.instance)
.trackActivity(loadingActivityIndicator).subscribe(onNext: { response in
if let data = HTMLParser.shared.timeline(html: response.data) {
self.isFollowed = data.isFollowed
self.isBlockd = data.isBlockd
self.tValue = data.tValue
self.idValue = data.idValue
self.joinTime.value = data.joinTime
var topicItems = data.topics.map({SectionTimelineItem.topicItem(topic: $0)})
if !data.topicPrivacy.isEmpty {
topicItems = [SectionTimelineItem.topicItem(topic: Topic())]
}
let replyItems = data.replys.map({SectionTimelineItem.replyItem(reply: $0)})
self.sections.value = [.topic(title: "创建的主题", privacy: data.topicPrivacy, moreHref: data.moreTopicHref, items: topicItems),
.reply(title: "最近的回复", moreHref: data.moreRepliesHref, items: replyItems)]
}
}, onError: { error in
print(error)
}).disposed(by: disposeBag)
}
func sendFollow(completion: ((Bool) -> Void)? = nil) {
let isCancel = isFollowed
API.provider.request(.once).flatMap { response -> Observable<Response> in
if let once = HTMLParser.shared.once(html: response.data) {
return API.provider.request(.follow(id: self.idValue, once: once, isCancel: isCancel))
}else {
return Observable.error(NetError.message(text: "获取once失败"))
}
}.share(replay: 1).subscribe(onNext: { response in
self.isFollowed = !isCancel
completion?(true)
}, onError: {error in
completion?(false)
}).disposed(by: disposeBag)
}
func sendBlock(completion: ((Bool) -> Void)? = nil) {
let isCancel = isBlockd
API.provider.request(.block(id: idValue, token: tValue, isCancel: isCancel))
.subscribe(onNext: { response in
self.isBlockd = !isCancel
completion?(true)
}, onError: {error in
completion?(false)
}).disposed(by: disposeBag)
}
}
| mit | c6f91f7031d1369671446392e36af082 | 38.216216 | 139 | 0.582702 | 4.464615 | false | false | false | false |
daniel-c/iSimulatorExplorer | TestTrustedCertificate/TestTrustedCertificate/TestWebViewController.swift | 1 | 1382 | //
// ViewController.swift
// TestTrustedCertificate
//
// Created by Daniel Cerutti on 11/10/14.
// Copyright (c) 2014-2016 Daniel Cerutti. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
import UIKit
class TestWebViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
webView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func openUrlButton(sender: AnyObject) {
if let text = urlTextField.text {
urlTextField.resignFirstResponder()
if let url = URL(string: text){
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
let text = "<html><header></header><body><h2 style=\"color:red\">\(error.localizedDescription)</h2</body></html>"
webView.loadHTMLString (text, baseURL:URL(string:"localhost"))
}
}
| mit | c8bb1d18d99e54d7d394fb542cc7209f | 29.711111 | 121 | 0.657019 | 4.749141 | false | false | false | false |
tensorflow/examples | lite/examples/pose_estimation/ios/PoseEstimation/ML/Extensions/CGSize+TFLite.swift | 1 | 1855 | // Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import Accelerate
import Foundation
extension CGSize {
/// Returns `CGAffineTransform` to resize `self` to fit in destination size, keeping aspect ratio
/// of `self`. `self` image is resized to be inscribe to destination size and located in center of
/// destination.
///
/// - Parameter toFitIn: destination size to be filled.
/// - Returns: `CGAffineTransform` to transform `self` image to `dest` image.
func transformKeepAspect(toFitIn dest: CGSize) -> CGAffineTransform {
let sourceRatio = self.height / self.width
let destRatio = dest.height / dest.width
// Calculates ratio `self` to `dest`.
var ratio: CGFloat
var x: CGFloat = 0
var y: CGFloat = 0
if sourceRatio > destRatio {
// Source size is taller than destination. Resized to fit in destination height, and find
// horizontal starting point to be centered.
ratio = dest.height / self.height
x = (dest.width - self.width * ratio) / 2
} else {
ratio = dest.width / self.width
y = (dest.height - self.height * ratio) / 2
}
return CGAffineTransform(a: ratio, b: 0, c: 0, d: ratio, tx: x, ty: y)
}
}
| apache-2.0 | 2c77ed4a15d4a12183452347999398f8 | 40.222222 | 100 | 0.663612 | 4.264368 | false | false | false | false |
yuhaifei123/WeiBo_Swift | WeiBo_Swift/WeiBo_Swift/class/Home(主页)/view/StatusFooterTopView.swift | 1 | 3962 | //
// StatusFooterTopView.swift
// WeiBo_Swift
//
// Created by 虞海飞 on 2017/1/9.
// Copyright © 2017年 虞海飞. All rights reserved.
//
import UIKit
class StatusFooterTopView: UIView {
var status : Status? {
didSet{
nameLabel.text = status?.user?.name;
timeLabel.text = status?.created_at;
sourceLabel.text = "来自: 小霸王学习机";
//头像 iconView
if let iconurl = status?.user?.profile_image_url{
let url = URL(string: iconurl);
iconView.sd_setImage(with: url as URL!);
}
// 设置认证图标
verifiedView.image = status?.user?.verifiedImage
}
}
/// 添加 view
private func setupUI(){
addSubview(iconView);
addSubview(verifiedView);
addSubview(nameLabel);
addSubview(vipView);
addSubview(timeLabel);
addSubview(sourceLabel);
//头像
iconView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 50, height: 50))
make.top.left.equalTo(10);
}
//图标
verifiedView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 14, height: 14));
make.bottom.equalTo(iconView.snp.bottom).offset(5);
make.right.equalTo(iconView.snp.right).offset(5);
}
// 昵称
nameLabel.snp.makeConstraints { (make) in
make.top.equalTo(iconView.snp.top);
make.left.equalTo(iconView.snp.right).offset(10);
}
// vip图标
vipView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 14, height: 14));
make.top.equalTo(nameLabel.snp.top);
make.left.equalTo(nameLabel.snp.right).offset(10);
}
//时间
timeLabel.snp.makeConstraints { (make) in
make.top.equalTo(nameLabel.snp.bottom).offset(10);
make.left.equalTo(iconView.snp.right).offset(10);
}
//来源
sourceLabel.snp.makeConstraints { (make) in
make.top.equalTo(timeLabel.snp.top);
make.left.equalTo(timeLabel.snp.right).offset(10);
}
}
/// 头像
private lazy var iconView : UIImageView = {
let imageViw = UIImageView(image: UIImage(named: "avatar_default_big"));
return imageViw;
}();
/// 图标
private lazy var verifiedView : UIImageView = {
let imageView = UIImageView(image: UIImage(named: "avatar_enterprise_vip"));
return imageView;
}();
/// 昵称
private lazy var nameLabel : UILabel = {
let label = UILabel();
label.textColor = UIColor.darkGray;
//字体的大小
label.font = UIFont.systemFont(ofSize: 14);
return label;
}();
/// 会员图标
private lazy var vipView : UIImageView = {
let imageView = UIImageView(image: UIImage(named: "common_icon_membership"));
return imageView;
}();
///时间
private lazy var timeLabel : UILabel = {
let label = UILabel();
label.textColor = UIColor.darkGray;
//字体的大小
label.font = UIFont.systemFont(ofSize: 14);
return label;
}();
///来源
private lazy var sourceLabel : UILabel = {
let label = UILabel();
label.textColor = UIColor.darkGray;
//字体的大小
label.font = UIFont.systemFont(ofSize: 14);
return label;
}();
override init(frame: CGRect) {
super.init(frame: frame);
setupUI();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | a135fd6c38a850f80a378ce910bf4d40 | 26.156028 | 85 | 0.534343 | 4.488863 | false | false | false | false |
CanyFrog/HCComponent | HCSource/String+Extension.swift | 1 | 1220 | //
// String+Extension.swift
// HCComponents
//
// Created by Magee Huang on 5/26/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
import Foundation
extension String {
public static func convertFromBytes(_ bytes: Int) -> String {
switch Double(bytes) {
case 0.1 * 1024 * 1024 ..< Double(Int.max):
return String(format: "%0.2fM", Double(bytes)/1024/1024)
case 1024 ..< 1024*1024:
return String(format: "%0.2fK", Double(bytes)/1024)
default:
return "\(bytes)dB"
}
}
public static func convertFromSeconds(_ seconds: TimeInterval) -> String {
let s = Int(seconds)
let min = Int(s / 60 % 60)
let sec = Int(s % 60)
return String(format: "%02d:%02d", min,sec)
}
public static var UUID: String {
let uuid = CFUUIDCreate(kCFAllocatorNull)
let str = CFUUIDCreateString(kCFAllocatorNull, uuid)
return str! as String
}
public static func systemSettingPath(_ path: String) -> String {
if #available(iOS 10.0, *) {
return "App-Prefs:root="+path
}
else {
return "prefs:root="+path
}
}
}
| mit | 95ed02b69454d6e5fb6d2329b3ee7d8c | 27.348837 | 78 | 0.567678 | 3.894569 | false | false | false | false |
LetItPlay/iOSClient | blockchainapp/SearchPresenter.swift | 1 | 5452 | //
// SearchPresenter.swift
// blockchainapp
//
// Created by Aleksey Tyurnin on 13/12/2017.
// Copyright © 2017 Ivan Gorbulin. All rights reserved.
//
import Foundation
import RealmSwift
enum SearchScreenState {
case search, recommendations
}
protocol SearchPresenterDelegate: class {
func updateSearch()
func update(tracks: [Int], channels: [Int])
}
class SearchPresenter {
var tracks: [Track] = []
var channels: [Station] = []
weak var delegate: SearchPresenterDelegate?
let realm: Realm? = try? Realm()
var currentPlayingIndex: Int = -1
var playlists: [(image: UIImage?, title: String, descr: String)] = []
var currentSearchString: String = ""
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(subscriptionChanged(notification:)),
name: SubscribeManager.NotificationName.added.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(subscriptionChanged(notification:)),
name: SubscribeManager.NotificationName.deleted.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(trackPlayed(notification:)),
name: AudioController.AudioStateNotification.playing.notification(),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(trackPaused(notification:)),
name: AudioController.AudioStateNotification.paused.notification(),
object: nil)
playlists.append((image: UIImage.init(named: "news"), title: "Fresh news in 30 minutes".localized, descr: "A compilation of fresh news in one 30-minute playlist".localized))
// playlists.append((image: nil, title: "IT", descr: "Новост\nНовости"))
// playlists.append((image: nil, title: "Спорт", descr: "Новост\nНовости"))
NotificationCenter.default.addObserver(self,
selector: #selector(settingsChanged(notification:)),
name: SettingsNotfification.changed.notification(),
object: nil) }
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func settingsChanged(notification: Notification) {
self.currentPlayingIndex = -1
self.searchChanged(string: currentSearchString)
}
func trackSelected(index: Int) {
let contr = AudioController.main
contr.loadPlaylist(playlist: ("Searching".localized, self.tracks.map({$0.audioTrack()})), playId: self.tracks[index].audiotrackId())
}
func channelSubPressed(index: Int) {
SubscribeManager.shared.addOrDelete(station: self.channels[index].id)
}
func searchChanged(string: String) {
self.currentSearchString = string
if string.count == 0 {
self.tracks = []
self.channels = []
} else {
self.tracks = self.realm?.objects(Track.self).filter("name contains[cd] '\(string.lowercased())' OR tagString contains[cd] '\(string.lowercased())'").filter({$0.lang == UserSettings.language.rawValue}).map({$0}) ?? []
self.channels = self.realm?.objects(Station.self).filter("name contains[cd] '\(string.lowercased())' OR tagString contains[cd] '\(string.lowercased())'").filter({$0.lang == UserSettings.language.rawValue}).map({$0}) ?? []
}
self.delegate?.updateSearch()
}
func formatPlaylists(index: Int) {
let tags = ["новости", "IT", "спорт"]
if let channels = self.realm?.objects(Station.self).filter("tagString CONTAINS '\(tags[index])'").map({$0.id}){
var trackSelection = [Track]()
for id in channels {
if let tracks = self.realm?.objects(Track.self).filter("station = \(id)"){
trackSelection.append(contentsOf: tracks)
}
}
var maxlength: Int64 = 0
trackSelection = trackSelection.sorted(by: {$0.publishedAt > $1.publishedAt})
var res = [Track]()
for track in trackSelection {
if let length = track.audiofile?.lengthSeconds, length < Int64(7*60), track.audiofile?.file != "" || track.audiofile?.file != nil, track.lang == UserSettings.language.rawValue {
if maxlength + length < Int64(60*33) {
res.append(track)
maxlength += length
} else {
break
}
}
}
if res.count > 0 {
let contr = AudioController.main
contr.loadPlaylist(playlist: ("Playlist".localized + " \"\(tags[index])\"", res.map({$0.audioTrack()})), playId: res[0].audiotrackId())
contr.showPlaylist()
}
print("res = \(res.map({$0.name}))")
}
}
@objc func subscriptionChanged(notification: Notification) {
if let id = notification.userInfo?["id"] as? Int,
let index = self.channels.index(where: {$0.id == id}) {
self.delegate?.update(tracks: [], channels: [index])
}
}
@objc func trackPlayed(notification: Notification) {
if let id = notification.userInfo?["ItemID"] as? String,
let index = self.tracks.index(where: {$0.audiotrackId() == id}) {
var reload = [Int]()
if currentPlayingIndex != -1 {
reload.append(self.currentPlayingIndex)
}
self.currentPlayingIndex = index
reload.append(index)
self.delegate?.update(tracks: reload, channels: [])
}
}
@objc func trackPaused(notification: Notification) {
if let id = notification.userInfo?["ItemID"] as? String,
let _ = self.tracks.index(where: {$0.audiotrackId() == id}) {
let reload = [self.currentPlayingIndex]
self.currentPlayingIndex = -1
self.delegate?.update(tracks: reload, channels: [])
}
}
}
| mit | e1c2ba1e503af6b607eab01d47d950a8 | 34.81457 | 224 | 0.674556 | 3.622237 | false | false | false | false |
4np/UitzendingGemist | UitzendingGemist/TipCollectionViewCell.swift | 1 | 2165 | //
// TipCollectionViewCell.swift
// UitzendingGemist
//
// Created by Jeroen Wesbeek on 15/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import UIKit
import NPOKit
import CocoaLumberjack
class TipCollectionViewCell: UICollectionViewCell {
@IBOutlet weak fileprivate var imageView: UIImageView!
@IBOutlet weak fileprivate var nameLabel: UILabel!
@IBOutlet weak fileprivate var dateLabel: UILabel!
// MARK: Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
self.nameLabel.text = nil
self.dateLabel.text = nil
}
// MARK: Focus engine
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
self.imageView.adjustsImageWhenAncestorFocused = self.isFocused
}
// MARK: Configuration
internal func configure(withTip tip: NPOTip) {
self.fetchImage(forTip: tip)
self.nameLabel.text = tip.getDisplayName()
self.dateLabel.text = tip.publishedDisplayValue
}
// MARK: Networking
internal func fetchImage(forTip tip: NPOTip) {
// Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000
// causing the images to look compressed so hardcode the dimensions for now...
// TODO: check if this is solved in later releases...
//let size = self.imageView.frame.size
let size = CGSize(width: 548, height: 320)
_ = tip.getImage(ofSize: size) { [weak self] image, error, _ in
guard let image = image else {
DDLogError("Could not fetch image for tip (\(String(describing: error)))")
return
}
// add a gradient to improve readability
if let gradientImage = image.imageWithGradient() {
self?.imageView.image = gradientImage
} else {
self?.imageView.image = image
}
}
}
}
| apache-2.0 | 23a199e46292be449d10f9284199e77d | 29.914286 | 115 | 0.628466 | 4.974713 | false | false | false | false |
mobilabsolutions/jenkins-ios | JenkinsiOS/Service/VersionNumberBuilder.swift | 1 | 938 | //
// VersionNumberBuilder.swift
// JenkinsiOS
//
// Created by Robert on 26.11.18.
// Copyright © 2018 MobiLab Solutions. All rights reserved.
//
import Foundation
class VersionNumberBuilder {
private static let versionKey = "CFBundleShortVersionString"
private static let buildNumberKey = "CFBundleVersion"
var fullVersionNumberDescription: String? {
guard let versionNumber = self.versionNumber
else { return nil }
var versionString = "Version \(versionNumber)"
if let buildNumber = self.buildNumber {
versionString += " (\(buildNumber))"
}
return versionString
}
var versionNumber: String? {
return Bundle.main.object(forInfoDictionaryKey: VersionNumberBuilder.versionKey) as? String
}
var buildNumber: String? {
return Bundle.main.object(forInfoDictionaryKey: VersionNumberBuilder.buildNumberKey) as? String
}
}
| mit | e58aaaab5b61602fea2e9f159bf6541b | 25.771429 | 103 | 0.689434 | 4.880208 | false | false | false | false |
Vanlol/MyYDW | Pods/ReactiveSwift/Sources/Flatten.swift | 5 | 33308 | //
// Flatten.swift
// ReactiveSwift
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how a stream of inner streams should be flattened into a stream of values.
public struct FlattenStrategy {
fileprivate enum Kind {
case concurrent(limit: UInt)
case latest
case race
}
fileprivate let kind: Kind
private init(kind: Kind) {
self.kind = kind
}
/// The stream of streams is merged, so that any value sent by any of the inner
/// streams is forwarded immediately to the flattened stream of values.
///
/// The flattened stream of values completes only when the stream of streams, and all
/// the inner streams it sent, have completed.
///
/// Any interruption of inner streams is treated as completion, and does not interrupt
/// the flattened stream of values.
///
/// Any failure from the inner streams is propagated immediately to the flattened
/// stream of values.
public static let merge = FlattenStrategy(kind: .concurrent(limit: .max))
/// The stream of streams is concatenated, so that only values from one inner stream
/// are forwarded at a time, in the order the inner streams are received.
///
/// In other words, if an inner stream is received when a previous inner stream has
/// yet terminated, the received stream would be enqueued.
///
/// The flattened stream of values completes only when the stream of streams, and all
/// the inner streams it sent, have completed.
///
/// Any interruption of inner streams is treated as completion, and does not interrupt
/// the flattened stream of values.
///
/// Any failure from the inner streams is propagated immediately to the flattened
/// stream of values.
public static let concat = FlattenStrategy(kind: .concurrent(limit: 1))
/// The stream of streams is merged with the given concurrency cap, so that any value
/// sent by any of the inner streams on the fly is forwarded immediately to the
/// flattened stream of values.
///
/// In other words, if an inner stream is received when a previous inner stream has
/// yet terminated, the received stream would be enqueued.
///
/// The flattened stream of values completes only when the stream of streams, and all
/// the inner streams it sent, have completed.
///
/// Any interruption of inner streams is treated as completion, and does not interrupt
/// the flattened stream of values.
///
/// Any failure from the inner streams is propagated immediately to the flattened
/// stream of values.
///
/// - precondition: `limit > 0`.
public static func concurrent(limit: UInt) -> FlattenStrategy {
return FlattenStrategy(kind: .concurrent(limit: limit))
}
/// Forward only values from the latest inner stream sent by the stream of streams.
/// The active inner stream is disposed of as a new inner stream is received.
///
/// The flattened stream of values completes only when the stream of streams, and all
/// the inner streams it sent, have completed.
///
/// Any interruption of inner streams is treated as completion, and does not interrupt
/// the flattened stream of values.
///
/// Any failure from the inner streams is propagated immediately to the flattened
/// stream of values.
public static let latest = FlattenStrategy(kind: .latest)
/// Forward only events from the first inner stream that sends an event. Any other
/// in-flight inner streams is disposed of when the winning inner stream is
/// determined.
///
/// The flattened stream of values completes only when the stream of streams, and the
/// winning inner stream, have completed.
///
/// Any interruption of inner streams is propagated immediately to the flattened
/// stream of values.
///
/// Any failure from the inner streams is propagated immediately to the flattened
/// stream of values.
public static let race = FlattenStrategy(kind: .race)
}
extension Signal where Value: SignalProducerConvertible, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy.kind {
case .concurrent(let limit):
return self.concurrent(limit: limit)
case .latest:
return self.switchToLatest()
case .race:
return self.race()
}
}
}
extension Signal where Value: SignalProducerConvertible, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` or an active inner producer fails, the returned
/// signal will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteError(Value.Error.self)
.flatten(strategy)
}
}
extension Signal where Value: SignalProducerConvertible, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy.kind {
case .concurrent(let limit):
return self.concurrent(limit: limit)
case .latest:
return self.switchToLatest()
case .race:
return self.race()
}
}
}
extension Signal where Value: SignalProducerConvertible, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer.promoteError(Error.self) }
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy.kind {
case .concurrent(let limit):
return self.concurrent(limit: limit)
case .latest:
return self.switchToLatest()
case .race:
return self.race()
}
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - note: If an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteError(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single
/// producer of values), according to the semantics of the given strategy.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy.kind {
case .concurrent(let limit):
return self.concurrent(limit: limit)
case .latest:
return self.switchToLatest()
case .race:
return self.race()
}
}
}
extension SignalProducer where Value: SignalProducerConvertible, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// - note: If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// - warning: `interrupted` events on inner producers will be treated like
/// `completed` events on inner producers.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.producer.promoteError(Error.self) }
}
}
extension Signal where Value: Sequence {
/// Flattens the `sequence` value sent by `signal`.
public func flatten() -> Signal<Value.Iterator.Element, Error> {
return self.flatMap(.merge, SignalProducer.init)
}
}
extension SignalProducer where Value: Sequence {
/// Flattens the `sequence` value sent by `signal`.
public func flatten() -> SignalProducer<Value.Iterator.Element, Error> {
return self.flatMap(.merge, SignalProducer<Value.Iterator.Element, NoError>.init)
}
}
extension Signal where Value: SignalProducerConvertible, Error == Value.Error {
fileprivate func concurrent(limit: UInt) -> Signal<Value.Value, Error> {
precondition(limit > 0, "The concurrent limit must be greater than zero.")
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcurrent(relayObserver, limit, relayDisposable)
return disposable
}
}
fileprivate func observeConcurrent(_ observer: Signal<Value.Value, Error>.Observer, _ limit: UInt, _ disposable: CompositeDisposable) -> Disposable? {
let state = Atomic(ConcurrentFlattenState<Value.Value, Error>(limit: limit))
func startNextIfNeeded() {
while let producer = state.modify({ $0.dequeue() }) {
let producerState = UnsafeAtomicState<ProducerState>(.starting)
let deinitializer = ScopedDisposable(AnyDisposable(producerState.deinitialize))
producer.startWithSignal { signal, inner in
let handle = disposable.add(inner)
signal.observe { event in
switch event {
case .completed, .interrupted:
handle?.dispose()
let shouldComplete: Bool = state.modify { state in
state.activeCount -= 1
return state.shouldComplete
}
withExtendedLifetime(deinitializer) {
if shouldComplete {
observer.sendCompleted()
} else if producerState.is(.started) {
startNextIfNeeded()
}
}
case .value, .failed:
observer.action(event)
}
}
}
withExtendedLifetime(deinitializer) {
producerState.setStarted()
}
}
}
return observe { event in
switch event {
case let .value(value):
state.modify { $0.queue.append(value.producer) }
startNextIfNeeded()
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify { state in
state.isOuterCompleted = true
return state.shouldComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error {
fileprivate func concurrent(limit: UInt) -> SignalProducer<Value.Value, Error> {
precondition(limit > 0, "The concurrent limit must be greater than zero.")
return SignalProducer<Value.Value, Error> { relayObserver, lifetime in
self.startWithSignal { signal, signalDisposable in
let disposables = CompositeDisposable()
lifetime.observeEnded(signalDisposable.dispose)
lifetime.observeEnded(disposables.dispose)
_ = signal.observeConcurrent(relayObserver, limit, disposables)
}
}
}
}
extension SignalProducer {
/// `concat`s `next` onto `self`.
///
/// - parameters:
/// - next: A follow-up producer to concat `self` with.
///
/// - returns: A producer that will start `self` and then on completion of
/// `self` - will start `next`.
public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>([ self.producer, next ]).flatten(.concat)
}
/// `concat`s `value` onto `self`.
///
/// - parameters:
/// - value: A value to concat onto `self`.
///
/// - returns: A producer that, when started, will emit own values and on
/// completion will emit a `value`.
public func concat(value: Value) -> SignalProducer<Value, Error> {
return self.concat(SignalProducer(value: value))
}
/// `concat`s `self` onto initial `previous`.
///
/// - parameters:
/// - previous: A producer to start before `self`.
///
/// - returns: A signal producer that, when started, first emits values from
/// `previous` producer and then from `self`.
public func prefix(_ previous: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return previous.concat(self)
}
/// `concat`s `self` onto initial `value`.
///
/// - parameters:
/// - value: A first value to emit.
///
/// - returns: A producer that, when started, first emits `value`, then all
/// values emited by `self`.
public func prefix(value: Value) -> SignalProducer<Value, Error> {
return self.prefix(SignalProducer(value: value))
}
}
private final class ConcurrentFlattenState<Value, Error: Swift.Error> {
typealias Producer = ReactiveSwift.SignalProducer<Value, Error>
/// The limit of active producers.
let limit: UInt
/// The number of active producers.
var activeCount: UInt = 0
/// The producers waiting to be started.
var queue: [Producer] = []
/// Whether the outer producer has completed.
var isOuterCompleted = false
/// Whether the flattened signal should complete.
var shouldComplete: Bool {
return isOuterCompleted && activeCount == 0 && queue.isEmpty
}
init(limit: UInt) {
self.limit = limit
}
/// Dequeue the next producer if one should be started.
///
/// - returns: The `Producer` to start or `nil` if no producer should be
/// started.
func dequeue() -> Producer? {
if activeCount < limit, !queue.isEmpty {
activeCount += 1
return queue.removeFirst()
} else {
return nil
}
}
}
private enum ProducerState: Int32 {
case starting
case started
}
extension UnsafeAtomicState where State == ProducerState {
fileprivate func setStarted() {
precondition(tryTransition(from: .starting, to: .started), "The transition is not supposed to fail.")
}
}
extension Signal {
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
///
/// - parameters:
/// - signals: A sequence of signals to merge.
public static func merge<Seq: Sequence>(_ signals: Seq) -> Signal<Value, Error> where Seq.Iterator.Element == Signal<Value, Error>
{
return SignalProducer<Signal<Value, Error>, Error>(signals)
.flatten(.merge)
.startAndRetrieveSignal()
}
/// Merges the given signals into a single `Signal` that will emit all
/// values from each of them, and complete when all of them have completed.
///
/// - parameters:
/// - signals: A list of signals to merge.
public static func merge(_ signals: Signal<Value, Error>...) -> Signal<Value, Error> {
return Signal.merge(signals)
}
}
extension SignalProducer {
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
///
/// - parameters:
/// - producers: A sequence of producers to merge.
public static func merge<Seq: Sequence>(_ producers: Seq) -> SignalProducer<Value, Error> where Seq.Iterator.Element == SignalProducer<Value, Error>
{
return SignalProducer<Seq.Iterator.Element, NoError>(producers).flatten(.merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit
/// all values from each of them, and complete when all of them have
/// completed.
///
/// - parameters:
/// - producers: A sequence of producers to merge.
public static func merge(_ producers: SignalProducer<Value, Error>...) -> SignalProducer<Value, Error> {
return SignalProducer.merge(producers)
}
}
extension Signal where Value: SignalProducerConvertible, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// - warning: An error sent on `signal` or the latest inner signal will be
/// sent on the returned signal.
///
/// - note: The returned signal completes when `signal` and the latest inner
/// signal have both completed.
fileprivate func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
fileprivate func observeSwitchToLatest(_ observer: Signal<Value.Value, Error>.Observer, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .value(p):
p.producer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents
// the generated Interrupted event from doing any work.
$0.replacingInnerSignal = true
}
latestInnerDisposable.inner = innerDisposable
state.modify {
$0.replacingInnerSignal = false
$0.innerSignalComplete = false
}
innerSignal.observe { event in
switch event {
case .interrupted:
// If interruption occurred as a result of a new
// producer arriving, we don't want to notify our
// observer.
let shouldComplete: Bool = state.modify { state in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return !state.replacingInnerSignal && state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.innerSignalComplete = true
return $0.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.outerSignalComplete = true
return $0.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error {
/// - warning: An error sent on `signal` or the latest inner signal will be
/// sent on the returned signal.
///
/// - note: The returned signal completes when `signal` and the latest inner
/// signal have both completed.
///
/// - returns: A signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, lifetime in
let latestInnerDisposable = SerialDisposable()
lifetime.observeEnded(latestInnerDisposable.dispose)
self.startWithSignal { signal, signalDisposable in
lifetime.observeEnded(signalDisposable.dispose)
if let disposable = signal.observeSwitchToLatest(observer, latestInnerDisposable) {
lifetime.observeEnded(disposable.dispose)
}
}
}
}
}
private struct LatestState<Value, Error: Swift.Error> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension Signal where Value: SignalProducerConvertible, Error == Value.Error {
/// Returns a signal that forwards values from the "first input signal to send an event"
/// (winning signal) that is sent on `self`, ignoring values sent from other inner signals.
///
/// An error sent on `self` or the winning inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `self` and the winning inner signal have both completed.
fileprivate func race() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let relayDisposable = CompositeDisposable()
composite += relayDisposable
composite += self.observeRace(observer, relayDisposable)
return composite
}
}
fileprivate func observeRace(_ observer: Signal<Value.Value, Error>.Observer, _ relayDisposable: CompositeDisposable) -> Disposable? {
let state = Atomic(RaceState())
return self.observe { event in
switch event {
case let .value(innerProducer):
// Ignore consecutive `innerProducer`s if any `innerSignal` already sent an event.
guard !relayDisposable.isDisposed else {
return
}
innerProducer.producer.startWithSignal { innerSignal, innerDisposable in
state.modify {
$0.innerSignalComplete = false
}
let disposableHandle = relayDisposable.add(innerDisposable)
var isWinningSignal = false
innerSignal.observe { event in
if !isWinningSignal {
isWinningSignal = state.modify { state in
guard !state.isActivated else {
return false
}
state.isActivated = true
return true
}
// Ignore non-winning signals.
guard isWinningSignal else { return }
// The disposals would be run exactly once immediately after
// the winning signal flips `state.isActivated`.
disposableHandle?.dispose()
relayDisposable.dispose()
}
switch event {
case .completed:
let shouldComplete: Bool = state.modify { state in
state.innerSignalComplete = true
return state.outerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .value, .failed, .interrupted:
observer.action(event)
}
}
}
case let .failed(error):
observer.send(error: error)
case .completed:
let shouldComplete: Bool = state.modify { state in
state.outerSignalComplete = true
return state.innerSignalComplete
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error {
/// Returns a producer that forwards values from the "first input producer to send an event"
/// (winning producer) that is sent on `self`, ignoring values sent from other inner producers.
///
/// An error sent on `self` or the winning inner producer will be sent on the
/// returned producer.
///
/// The returned producer completes when `self` and the winning inner producer have both completed.
fileprivate func race() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, lifetime in
let relayDisposable = CompositeDisposable()
lifetime.observeEnded(relayDisposable.dispose)
self.startWithSignal { signal, signalDisposable in
lifetime.observeEnded(signalDisposable.dispose)
if let disposable = signal.observeRace(observer, relayDisposable) {
lifetime.observeEnded(disposable.dispose)
}
}
}
}
}
private struct RaceState {
var outerSignalComplete = false
var innerSignalComplete = true
var isActivated = false
}
extension Signal {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// - warning: If `signal` or any of the created producers fail, the
/// returned signal will forward that failure immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == Error {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// - warning: If `signal` fails, the returned signal will forward that
/// failure immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == NoError {
return map(transform).flatten(strategy)
}
}
extension Signal where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// - warning: If any of the created signals emit an error, the returned
/// signal will forward that error immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Inner.Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, NoError> where Inner.Error == NoError {
return map(transform).flatten(strategy)
}
}
extension SignalProducer {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// - warning: If `self` or any of the created producers fail, the returned
/// producer will forward that failure immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// - warning: If `self` fails, the returned producer will forward that
/// failure immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == NoError {
return map(transform).flatten(strategy)
}
}
extension SignalProducer where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// - warning: If any of the created producers fail, the returned producer
/// will forward that failure immediately.
///
/// - parameters:
/// - strategy: Strategy used when flattening signals.
/// - transform: A closure that takes a value emitted by `self` and
/// returns a signal producer with transformed value.
public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Inner.Error> {
return map(transform).flatten(strategy)
}
}
extension Signal {
/// Catches any failure that may occur on the input signal, mapping to a new
/// producer that starts in its place.
///
/// - parameters:
/// - transform: A closure that accepts emitted error and returns a signal
/// producer with a different type of error.
public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal<Value, F> { observer in
self.observeFlatMapError(transform, observer, SerialDisposable())
}
}
fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Signal<Value, F>.Observer, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
observer.send(value: value)
case let .failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.inner = disposable
signal.observe(observer)
}
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducer {
/// Catches any failure that may occur on the input producer, mapping to a
/// new producer that starts in its place.
///
/// - parameters:
/// - transform: A closure that accepts emitted error and returns a signal
/// producer with a different type of error.
public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer<Value, F> { observer, lifetime in
let serialDisposable = SerialDisposable()
lifetime.observeEnded(serialDisposable.dispose)
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
_ = signal.observeFlatMapError(transform, observer, serialDisposable)
}
}
}
}
| apache-2.0 | e948836cbb70d1ecb5171fec4d05af69 | 34.023134 | 193 | 0.69646 | 4.133408 | false | false | false | false |
Stitch7/Instapod | Instapod/Extensions/UIImage+createThumbnail.swift | 1 | 949 | //
// UIImage+createThumbnail.swift
// Instapod
//
// Created by Christopher Reitz on 03.09.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
extension UIImage {
func createThumbnail(size baseSize: CGFloat) -> Data? {
let length = UIScreen.main.scale * baseSize
let size = CGSize(width: length, height: length)
UIGraphicsBeginImageContext(size)
self.draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
let thumbnailImage = UIGraphicsGetImageFromCurrentImageContext()
var thumbnailData: Data?
if let png = UIImagePNGRepresentation(thumbnailImage!) {
thumbnailData = NSData(data: png) as Data
}
else if let jpeg = UIImageJPEGRepresentation(thumbnailImage!, 1.0) {
thumbnailData = NSData(data: jpeg) as Data
}
UIGraphicsEndImageContext()
return thumbnailData
}
}
| mit | 36fb047fa538f87ea7a255712c1a3fb6 | 29.580645 | 85 | 0.657173 | 4.492891 | false | false | false | false |
brentsimmons/Evergreen | iOS/MasterTimeline/MarkAsReadAlertController.swift | 1 | 2856 | //
// UndoAvailableAlertController.swift
// NetNewsWire
//
// Created by Phil Viso on 9/29/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import UIKit
protocol MarkAsReadAlertControllerSourceType {}
extension CGRect: MarkAsReadAlertControllerSourceType {}
extension UIView: MarkAsReadAlertControllerSourceType {}
extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {}
struct MarkAsReadAlertController {
static func confirm<T>(_ controller: UIViewController?,
coordinator: SceneCoordinator?,
confirmTitle: String,
sourceType: T,
cancelCompletion: (() -> Void)? = nil,
completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType {
guard let controller = controller, let coordinator = coordinator else {
completion()
return
}
if AppDefaults.shared.confirmMarkAllAsRead {
let alertController = MarkAsReadAlertController.alert(coordinator: coordinator, confirmTitle: confirmTitle, cancelCompletion: cancelCompletion, sourceType: sourceType) { _ in
completion()
}
controller.present(alertController, animated: true)
} else {
completion()
}
}
private static func alert<T>(coordinator: SceneCoordinator,
confirmTitle: String,
cancelCompletion: (() -> Void)?,
sourceType: T,
completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType {
let title = NSLocalizedString("Mark As Read", comment: "Mark As Read")
let message = NSLocalizedString("You can turn this confirmation off in Settings.",
comment: "You can turn this confirmation off in Settings.")
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let settingsTitle = NSLocalizedString("Open Settings", comment: "Open Settings")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in
cancelCompletion?()
}
let settingsAction = UIAlertAction(title: settingsTitle, style: .default) { _ in
coordinator.showSettings(scrollToArticlesSection: true)
}
let markAction = UIAlertAction(title: confirmTitle, style: .default, handler: completion)
alertController.addAction(markAction)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
if let barButtonItem = sourceType as? UIBarButtonItem {
alertController.popoverPresentationController?.barButtonItem = barButtonItem
}
if let rect = sourceType as? CGRect {
alertController.popoverPresentationController?.sourceRect = rect
}
if let view = sourceType as? UIView {
alertController.popoverPresentationController?.sourceView = view
}
return alertController
}
}
| mit | 4664ed1839f95513fb1623687bb729fb | 33.39759 | 177 | 0.740105 | 4.880342 | false | false | false | false |
idea4good/GuiLiteSamples | Hello3Dwave/BuildAppleWatch/Hello3D WatchKit Extension/InterfaceController.swift | 1 | 1498 | import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
fileprivate let viewWidth = 240
fileprivate var viewHeight = 320
fileprivate var colorBytes = 4
@IBOutlet weak var image: WKInterfaceImage!
fileprivate var guiLiteImage : GuiLiteImage?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
guiLiteImage = GuiLiteImage(width: viewWidth, height: viewHeight, colorBytes: colorBytes)
Thread.detachNewThreadSelector(#selector(starUI), toTarget: self, with: nil)
sleep(2)// Wait for GuiLite App ready
Timer.scheduledTimer(withTimeInterval: 0.04, repeats: true, block: {_ in self.updateNativeView()})
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func updateNativeView() {
let cgGuiLiteImage = guiLiteImage?.getUiImage()
if(cgGuiLiteImage == nil){
return
}
image.setImage(UIImage(cgImage: cgGuiLiteImage!))
}
@objc func starUI(){
startHello3Dwave(calloc(viewWidth * viewHeight, colorBytes), Int32(viewWidth), Int32(viewHeight), Int32(colorBytes), nil);
}
}
| apache-2.0 | 5ca332718f088f7b1593fa5d39a5bbc9 | 32.288889 | 130 | 0.671562 | 4.770701 | false | false | false | false |
Raiden9000/Sonarus | SearchViewController.swift | 1 | 14957 | //
// SearchViewController.swift
// Sonarus
//
// Created by Christopher Arciniega on 4/22/17.
// Copyright © 2017 HQZenithLabs. All rights reserved.
//
/**
TODO:
[ ] 5. Prefetch data, increase limit of result cells shown
BUGS:
[ ] 1. Typing too fast causes a missing letter on search results
*/
import Foundation
var searchController = UISearchController(searchResultsController: nil)
var searchText : String = ""
var songListPage : SPTListPage = SPTListPage.init()
var artistListPage : SPTListPage = SPTListPage.init()
var userRef:FIRDatabaseReference!
var scope = 0
var searchCount = 0
var session: SPTSession!
var arrayOfFollowing:[String] = []
///For timing search requests
var timer:Timer!
class SearchViewController : UITableViewController, UISearchControllerDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
searchController.searchBar.showsScopeBar = false
}
override func viewDidLoad() {
print("xxxxxxxxxxxxxxxxxxxxxxxxx SEARCH CONTROLLER view did load xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
super.viewDidLoad()
//self.setNeedsStatusBarAppearanceUpdate()
//get session variable
if let sessionObj:AnyObject = UserDefaults.standard.value(forKey: "SpotifySession") as AnyObject?{
let sessionDataObj = sessionObj as! Data
let firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSession
session = firstTimeSession
}
//Register cell class
self.tableView.register(SearchCell.self, forCellReuseIdentifier: "ResultCell")
self.tableView.register(UserCell.self, forCellReuseIdentifier: "UserCell")
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.keyboardAppearance = UIKeyboardAppearance.dark
searchController.searchBar.barTintColor = UIColor.black
tableView.backgroundView = UIImageView(image: UIImage(named: "wallpaper"))
tableView.separatorColor = UIColor.clear
searchController.searchBar.scopeButtonTitles = ["Songs", "Artists", "Users"]
searchController.searchBar.delegate = self
searchController.delegate = self
//let searchBarTextField = searchController.searchBar.value(forKey: "_searchField") as! UITextField
//searchBarTextField.delegate = self
tableView.dataSource = self
searchController.searchBar.autocorrectionType = UITextAutocorrectionType.no
searchController.hidesNavigationBarDuringPresentation = true
self.edgesForExtendedLayout = []
self.definesPresentationContext = true
tableView.tableFooterView = UIView()//removes empty cells
tableView.backgroundColor = UIColor.black
//Set searchbar position
searchController.searchBar.searchBarStyle = UISearchBarStyle.prominent
searchController.searchBar.sizeToFit()
searchController.searchBar.isTranslucent = false
tableView.tableHeaderView = searchController.searchBar
searchController.isActive = true //ADDED B/C KEYBOARD WAS NOT APPEARING.
searchController.extendedLayoutIncludesOpaqueBars = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
searchController.searchBar.becomeFirstResponder()
}
//POPULATE CELLS
//Does not currently retrieve next listpage, so only 20 results will show.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("cellForRowAt. searchText: " + searchController.searchBar.text!)
if scope == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as? SearchCell
print("Index: \(indexPath.row), Range: \(songListPage.items.count), SearchCount: \(searchCount)")
guard let partialTrack = songListPage.items[indexPath.row] as? SPTPartialTrack
else {
//throw SearchError.outOfRange
print("Search index out of range")
cell?.prepareForReuse()
return cell!
}
cell?.link = partialTrack.playableUri
cell?.trackID = partialTrack.identifier
cell?.topLabel.text = partialTrack.name
let artist = partialTrack.artists.first as! SPTPartialArtist
cell?.lowerLabel.text = artist.name
setAlbumArt(cell: cell!,smallArtUrl: partialTrack.album.smallestCover.imageURL, largeArtUrl: partialTrack.album.largestCover.imageURL)
//Info
cell?.artistName = artist.name
cell?.songName = partialTrack.name
return cell!
}
else if scope == 1{
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as? SearchCell
print("scope is 1")
cell?.prepareForReuse()
if (indexPath.row < artistListPage.range.length){
let partialArtist = artistListPage.items[indexPath.row] as! SPTPartialArtist
cell?.lowerLabel.isHidden = true
cell?.artView.isHidden = true
cell?.topLabel.isHidden = true
cell?.button.isHidden = true
cell?.singleLabel.isHidden = false
cell?.singleLabel.text = partialArtist.name
}
else{
print("out of range")
}
return cell!
}
else if scope == 2{
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as? UserCell
cell?.setUsername(userID: searchText, displayName: "")
cell?.setStatusTextToWhite()
getFollowing()
if arrayOfFollowing.contains(searchText){
cell?.disableFollowButton()
}
//Get recent status
userRef = FIRDatabase.database().reference().child("Userbase/\(searchText)/6Statuses/")
userRef.observeSingleEvent(of: .value, with: {(snapshot) in
var statuses = [String]()
for data in snapshot.children.allObjects as! [FIRDataSnapshot]{
if let dataDict = data.value as? [String:Any]{
let status = dataDict["1status"] as? String
statuses.append(status!)
}
}
if statuses.last! != nil{
cell?.setDisplayStatus(asStatus: statuses.last!)
}
})
//Get Firebase Profile Pic
userRef = FIRDatabase.database().reference().child("Userbase/\(searchText)/3Image/")
userRef.observeSingleEvent(of: .value, with: {(snapshot) in
let userImage = snapshot.value as! String
cell?.setProfilePic(imageURL: URL(string: userImage)!)
})
return cell!
}
let cell = UITableViewCell()
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(65)
}
//Takes care of when you select things
//We want it to flash off after user has pressed cell
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as! SearchCell
searchController.searchBar.resignFirstResponder()
if (searchController.searchBar.selectedScopeButtonIndex == 0)
{
NotificationCenter.default.post(name: Notification.Name(rawValue: "playSongFromMusicCell"), object: selectedCell)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//Number of cells/items
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numOfRowsInSection. Count: \(searchCount), searchText: " + searchController.searchBar.text!)
if searchText == ""{
//print("1: searchText empty")
return 0
}
else if searchCount > 20{
return 20
}
return searchCount
}//END NUMBEROFROWSINSECTION
//Sets a cell's album art provided a URL
func setAlbumArt(cell : SearchCell, smallArtUrl : URL, largeArtUrl : URL){
//Set proper labels to show
cell.lowerLabel.isHidden = false
cell.artView.isHidden = false
cell.topLabel.isHidden = false
cell.singleLabel.isHidden = true
//Set cover
var coverImageSmall : UIImage? = nil
var coverImageLarge : UIImage? = nil
DispatchQueue.global(qos: .userInitiated).async{
do{
let imageDataSmall = try Data(contentsOf: smallArtUrl)
coverImageSmall = UIImage(data: imageDataSmall)
let imageDataLarge = try Data(contentsOf: largeArtUrl)
coverImageLarge = UIImage(data: imageDataLarge)
}//End do
catch{
print(error.localizedDescription)
}
DispatchQueue.main.async{
if coverImageSmall != nil{
//print("setting cover")
cell.artView.image = coverImageSmall
cell.smallArt = coverImageSmall!
}
else{
print("no image for search cell")
}
if coverImageLarge != nil{
cell.largeArt = coverImageLarge!
}
else{
print("no image for search cell")
}
}//End dispatch main
}//End Dispatch Global
}
//Scope 0 = songs
//Scope 1 = artists
//Scope 2, users
@objc func sendSearchRequest(){
print("sendSearchRequest")
var type : SPTSearchQueryType = SPTSearchQueryType.queryTypeTrack
if (session.accessToken == nil)
{
print("nil session")
return
}
searchText = searchController.searchBar.text!
print("searchtext!: \(searchText)")
if scope == 2{
let ref = FIRDatabase.database().reference().child("Userbase/\(searchText)/")
ref.observeSingleEvent(of: .value, with:{(snapshot) in
if (snapshot.value as? NSDictionary) == nil{
print("User does not exist in firebase db.")
}
else{
searchCount = 1
userRef = ref
self.tableView.reloadData()
}
})
}
else{
if scope == 1{
type = SPTSearchQueryType.queryTypeArtist
}
SPTSearch.perform(withQuery: searchText, queryType: type, offset: 0, accessToken: session.accessToken, market: "US",
callback: {(error, results) in
var trackListPage : SPTListPage
if error == nil{
trackListPage = results as! SPTListPage
searchCount = Int(trackListPage.totalListLength)
if scope == 0{
songListPage = trackListPage
}
else{//forScope = 1
artistListPage = trackListPage
}
}
else {
print(error ?? "Error in search.")}
self.tableView.reloadData()
}as SPTRequestCallback!)//End callback, end SPTSearch.perform
}
}
func getFollowing(){
//Generate key
let refQ = FIRDatabase.database().reference().child("Userbase/\(session.canonicalUsername!)/5Following/")
refQ.observeSingleEvent(of: .value, with: {(snapshot) in
if let following = snapshot.value as? NSDictionary{
for name in following{
arrayOfFollowing.append(name.value as! String)
}
self.tableView.reloadData()
}
else{
print("User not following.")
}
})
}
}
extension SearchViewController : UISearchBarDelegate, UISearchResultsUpdating{//UITextFieldDelegate
func updateSearchResults(for searchController: UISearchController) {
print("updateSearchResults")
searchText = searchController.searchBar.text!
timer?.invalidate()//cancel previous timer
if searchText.characters.count > 3{
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SearchViewController.sendSearchRequest), userInfo: nil, repeats: false)
}
}
//To apply this method, searchBar delegate is made self in viewDidLoad
//Method allows this class to control what happens when the search scope is changed from song, to artist, or etc
//Method intends to change the scope1 even if search text remains the same for a different set of data(tracks/artists/etc)
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
print("scopeButtonIndexDidChange")
scope = selectedScope
if searchText.characters.count > 3{
sendSearchRequest()
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchCount = 0
tableView.reloadData()
}
/*
//Wait half a second before sending search request
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
timer?.invalidate()//cancel previous timer
let currentText = textField.text ?? ""
if (currentText as NSString).replacingCharacters(in: range, with: string).characters.count >= 3{
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SearchViewController.sendSearchRequest), userInfo: nil, repeats: false)
}
return true
}*/
}
| mit | ef8a5a16c29fea531de6b369987377d4 | 39.421622 | 165 | 0.588861 | 5.603597 | false | false | false | false |
wjc2118/TagView | TagView_Swift/TagView_Swift/TagView/ContentScrollView.swift | 1 | 3460 | //
// ContentScrollView.swift
// TagView_Swift
//
// Created by Mac-os on 16/12/26.
// Copyright © 2016年 risen. All rights reserved.
//
import UIKit
class ContentScrollView: UIScrollView {
// MARK: - internal
var contentType: TagView.ContentType = .tableView {
didSet {
if contentType != oldValue {
setupContentViewAt(index: 0)
}
}
}
var contentDirection: TitleScrollView.LayoutDirection = .horizontal {
didSet {
if contentDirection != oldValue {
// relayout()
}
}
}
var contentCount: Int = 0 {
didSet {
setupContentViewAt(index: 0)
}
}
var tableViewConfigure: ((Int, UITableView)->())?
var collectionViewConfigure: ((Int, UICollectionViewFlowLayout, UICollectionView)->())?
var customViewConfigure: ((Int, UIView)->())?
lazy var contentViews: [UIView?] = [UIView?](repeating: nil, count: self.contentCount)
func setupContentViewAt(index: Int) {
guard contentCount > 0, contentViews[index] == nil else { return }
let zeroFrame = CGRect.zero
switch contentType {
case .tableView:
let tableView = UITableView(frame: zeroFrame, style: .plain)
tableViewConfigure?(index, tableView)
addSubview(tableView)
contentViews[index] = tableView
case .collectionView:
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: zeroFrame, collectionViewLayout: layout)
collectionViewConfigure?(index, layout, collectionView)
addSubview(collectionView)
contentViews[index] = collectionView
case .customView:
let customView = UIView()
customViewConfigure?(index, customView)
addSubview(customView)
contentViews[index] = customView
}
}
// MARK: - override
override init(frame: CGRect) {
super.init(frame: frame)
bounces = false
isPagingEnabled = true
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
relayout()
}
// MARK: - private
private func relayout() {
guard !contentViews.isEmpty else { return }
switch contentDirection {
case .horizontal:
contentSize = CGSize(width: frame.width * CGFloat(contentCount), height: 0)
for (idx, view) in contentViews.enumerated() {
guard let view = view else { continue }
view.frame = CGRect(x: CGFloat(idx) * frame.width, y: 0, width: frame.width, height: frame.height)
}
case .vertical:
contentSize = CGSize(width: 0, height: frame.height * CGFloat(contentCount))
for (idx, view) in contentViews.enumerated() {
guard let view = view else { continue }
view.frame = CGRect(x: 0, y: CGFloat(idx) * frame.height, width: frame.width, height: frame.height)
}
}
}
}
| mit | f502b6f3c3b2cf4c121acc024d88aef1 | 26.436508 | 115 | 0.566676 | 5.214178 | false | false | false | false |
alblue/swift-corelibs-foundation | TestFoundation/TestJSONEncoder.swift | 1 | 44384 | // 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
struct TopLevelObjectWrapper<T: Codable & Equatable>: Codable, Equatable {
var value: T
static func ==(lhs: TopLevelObjectWrapper, rhs: TopLevelObjectWrapper) -> Bool {
return lhs.value == rhs.value
}
init(_ value: T) {
self.value = value
}
}
class TestJSONEncoder : XCTestCase {
// MARK: - Encoding Top-Level Empty Types
func test_encodingTopLevelEmptyStruct() {
let empty = EmptyStruct()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
func test_encodingTopLevelEmptyClass() {
let empty = EmptyClass()
_testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary)
}
// MARK: - Encoding Top-Level Single-Value Types
func test_encodingTopLevelSingleValueEnum() {
_testEncodeFailure(of: Switch.off)
_testEncodeFailure(of: Switch.on)
_testRoundTrip(of: TopLevelArrayWrapper(Switch.off))
_testRoundTrip(of: TopLevelArrayWrapper(Switch.on))
}
func test_encodingTopLevelSingleValueStruct() {
_testEncodeFailure(of: Timestamp(3141592653))
_testRoundTrip(of: TopLevelArrayWrapper(Timestamp(3141592653)))
}
func test_encodingTopLevelSingleValueClass() {
_testEncodeFailure(of: Counter())
_testRoundTrip(of: TopLevelArrayWrapper(Counter()))
}
// MARK: - Encoding Top-Level Structured Types
func test_encodingTopLevelStructuredStruct() {
// Address is a struct type with multiple fields.
let address = Address.testValue
_testRoundTrip(of: address)
}
func test_encodingTopLevelStructuredClass() {
// Person is a class with multiple fields.
let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"[email protected]\"}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON)
}
func test_encodingTopLevelStructuredSingleStruct() {
// Numbers is a struct which encodes as an array through a single value container.
let numbers = Numbers.testValue
_testRoundTrip(of: numbers)
}
func test_encodingTopLevelStructuredSingleClass() {
// Mapping is a class which encodes as a dictionary through a single value container.
let mapping = Mapping.testValue
_testRoundTrip(of: mapping)
}
func test_encodingTopLevelDeepStructuredType() {
// Company is a type with fields which are Codable themselves.
let company = Company.testValue
_testRoundTrip(of: company)
}
// MARK: - Output Formatting Tests
func test_encodingOutputFormattingDefault() {
let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"[email protected]\"}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON)
}
func test_encodingOutputFormattingPrettyPrinted() {
let expectedJSON = "{\n \"name\" : \"Johnny Appleseed\",\n \"email\" : \"[email protected]\"\n}".data(using: .utf8)!
let person = Person.testValue
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted])
}
func test_encodingOutputFormattingSortedKeys() {
let expectedJSON = "{\"email\":\"[email protected]\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)!
let person = Person.testValue
#if os(macOS) || DARWIN_COMPATIBILITY_TESTS
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
}
#else
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
#endif
}
func test_encodingOutputFormattingPrettyPrintedSortedKeys() {
let expectedJSON = "{\n \"email\" : \"[email protected]\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)!
let person = Person.testValue
#if os(macOS) || DARWIN_COMPATIBILITY_TESTS
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
}
#else
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
#endif
}
// MARK: - Date Strategy Tests
func test_encodingDate() {
// We can't encode a top-level Date, so it'll be wrapped in an array.
_testRoundTrip(of: TopLevelArrayWrapper(Date()))
}
func test_encodingDateSecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "[1000]".data(using: .utf8)!
// We can't encode a top-level Date, so it'll be wrapped in an array.
_testRoundTrip(of: TopLevelArrayWrapper(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .secondsSince1970,
dateDecodingStrategy: .secondsSince1970)
}
func test_encodingDateMillisecondsSince1970() {
// Cannot encode an arbitrary number of seconds since we've lost precision since 1970.
let seconds = 1000.0
let expectedJSON = "[1000000]".data(using: .utf8)!
// We can't encode a top-level Date, so it'll be wrapped in an array.
_testRoundTrip(of: TopLevelArrayWrapper(Date(timeIntervalSince1970: seconds)),
expectedJSON: expectedJSON,
dateEncodingStrategy: .millisecondsSince1970,
dateDecodingStrategy: .millisecondsSince1970)
}
func test_encodingDateISO8601() {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)!
// We can't encode a top-level Date, so it'll be wrapped in an array.
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .iso8601,
dateDecodingStrategy: .iso8601)
}
func test_encodingDateFormatted() {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .full
let timestamp = Date(timeIntervalSince1970: 1000)
let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)!
// We can't encode a top-level Date, so it'll be wrapped in an array.
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .formatted(formatter),
dateDecodingStrategy: .formatted(formatter))
}
func test_encodingDateCustom() {
let timestamp = Date()
// We'll encode a number instead of a date.
let encode = { (_ data: Date, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { (_: Decoder) throws -> Date in return timestamp }
// We can't encode a top-level Date, so it'll be wrapped in an array.
let expectedJSON = "[42]".data(using: .utf8)!
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
func test_encodingDateCustomEmpty() {
let timestamp = Date()
// Encoding nothing should encode an empty keyed container ({}).
let encode = { (_: Date, _: Encoder) throws -> Void in }
let decode = { (_: Decoder) throws -> Date in return timestamp }
// We can't encode a top-level Date, so it'll be wrapped in an array.
let expectedJSON = "[{}]".data(using: .utf8)!
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
expectedJSON: expectedJSON,
dateEncodingStrategy: .custom(encode),
dateDecodingStrategy: .custom(decode))
}
// MARK: - Data Strategy Tests
func test_encodingBase64Data() {
let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF])
// We can't encode a top-level Data, so it'll be wrapped in an array.
let expectedJSON = "[\"3q2+7w==\"]".data(using: .utf8)!
_testRoundTrip(of: TopLevelArrayWrapper(data), expectedJSON: expectedJSON)
}
func test_encodingCustomData() {
// We'll encode a number instead of data.
let encode = { (_ data: Data, _ encoder: Encoder) throws -> Void in
var container = encoder.singleValueContainer()
try container.encode(42)
}
let decode = { (_: Decoder) throws -> Data in return Data() }
// We can't encode a top-level Data, so it'll be wrapped in an array.
let expectedJSON = "[42]".data(using: .utf8)!
_testRoundTrip(of: TopLevelArrayWrapper(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
func test_encodingCustomDataEmpty() {
// Encoding nothing should encode an empty keyed container ({}).
let encode = { (_: Data, _: Encoder) throws -> Void in }
let decode = { (_: Decoder) throws -> Data in return Data() }
// We can't encode a top-level Data, so it'll be wrapped in an array.
let expectedJSON = "[{}]".data(using: .utf8)!
_testRoundTrip(of: TopLevelArrayWrapper(Data()),
expectedJSON: expectedJSON,
dataEncodingStrategy: .custom(encode),
dataDecodingStrategy: .custom(decode))
}
// MARK: - Non-Conforming Floating Point Strategy Tests
func test_encodingNonConformingFloats() {
_testEncodeFailure(of: TopLevelArrayWrapper(Float.infinity))
_testEncodeFailure(of: TopLevelArrayWrapper(-Float.infinity))
_testEncodeFailure(of: TopLevelArrayWrapper(Float.nan))
_testEncodeFailure(of: TopLevelArrayWrapper(Double.infinity))
_testEncodeFailure(of: TopLevelArrayWrapper(-Double.infinity))
_testEncodeFailure(of: TopLevelArrayWrapper(Double.nan))
}
func test_encodingNonConformingFloatStrings() {
let encodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
let decodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN")
_testRoundTrip(of: TopLevelArrayWrapper(Float.infinity),
expectedJSON: "[\"INF\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: TopLevelArrayWrapper(-Float.infinity),
expectedJSON: "[\"-INF\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: TopLevelArrayWrapper(FloatNaNPlaceholder()),
expectedJSON: "[\"NaN\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: TopLevelArrayWrapper(Double.infinity),
expectedJSON: "[\"INF\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
_testRoundTrip(of: TopLevelArrayWrapper(-Double.infinity),
expectedJSON: "[\"-INF\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
// Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip.
_testRoundTrip(of: TopLevelArrayWrapper(DoubleNaNPlaceholder()),
expectedJSON: "[\"NaN\"]".data(using: .utf8)!,
nonConformingFloatEncodingStrategy: encodingStrategy,
nonConformingFloatDecodingStrategy: decodingStrategy)
}
// MARK: - Encoder Features
func test_nestedContainerCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType())
} catch let error {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
func test_superEncoderCodingPaths() {
let encoder = JSONEncoder()
do {
let _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true))
} catch let error {
XCTFail("Caught error during encoding nested container types: \(error)")
}
}
// MARK: - Test encoding and decoding of built-in Codable types
func test_codingOfBool() {
test_codingOf(value: Bool(true), toAndFrom: "true")
test_codingOf(value: Bool(false), toAndFrom: "false")
do {
_ = try JSONDecoder().decode([Bool].self, from: "[1]".data(using: .utf8)!)
XCTFail("Coercing non-boolean numbers into Bools was expected to fail")
} catch { }
// Check that a Bool false or true isnt converted to 0 or 1
struct Foo: Decodable {
var intValue: Int?
var int8Value: Int8?
var int16Value: Int16?
var int32Value: Int32?
var int64Value: Int64?
var uintValue: UInt?
var uint8Value: UInt8?
var uint16Value: UInt16?
var uint32Value: UInt32?
var uint64Value: UInt64?
var floatValue: Float?
var doubleValue: Double?
var decimalValue: Decimal?
let boolValue: Bool
}
func testValue(_ valueName: String) {
do {
let jsonData = "{ \"\(valueName)\": false }".data(using: .utf8)!
_ = try JSONDecoder().decode(Foo.self, from: jsonData)
XCTFail("Decoded 'false' as non Bool for \(valueName)")
} catch {}
do {
let jsonData = "{ \"\(valueName)\": true }".data(using: .utf8)!
_ = try JSONDecoder().decode(Foo.self, from: jsonData)
XCTFail("Decoded 'true' as non Bool for \(valueName)")
} catch {}
}
testValue("intValue")
testValue("int8Value")
testValue("int16Value")
testValue("int32Value")
testValue("int64Value")
testValue("uintValue")
testValue("uint8Value")
testValue("uint16Value")
testValue("uint32Value")
testValue("uint64Value")
testValue("floatValue")
testValue("doubleValue")
testValue("decimalValue")
let falseJsonData = "{ \"boolValue\": false }".data(using: .utf8)!
if let falseFoo = try? JSONDecoder().decode(Foo.self, from: falseJsonData) {
XCTAssertFalse(falseFoo.boolValue)
} else {
XCTFail("Could not decode 'false' as a Bool")
}
let trueJsonData = "{ \"boolValue\": true }".data(using: .utf8)!
if let trueFoo = try? JSONDecoder().decode(Foo.self, from: trueJsonData) {
XCTAssertTrue(trueFoo.boolValue)
} else {
XCTFail("Could not decode 'true' as a Bool")
}
}
func test_codingOfInt8() {
test_codingOf(value: Int8(-42), toAndFrom: "-42")
}
func test_codingOfUInt8() {
test_codingOf(value: UInt8(42), toAndFrom: "42")
}
func test_codingOfInt16() {
test_codingOf(value: Int16(-30042), toAndFrom: "-30042")
}
func test_codingOfUInt16() {
test_codingOf(value: UInt16(30042), toAndFrom: "30042")
}
func test_codingOfInt32() {
test_codingOf(value: Int32(-2000000042), toAndFrom: "-2000000042")
}
func test_codingOfUInt32() {
test_codingOf(value: UInt32(2000000042), toAndFrom: "2000000042")
}
func test_codingOfInt64() {
#if !arch(arm)
test_codingOf(value: Int64(-9000000000000000042), toAndFrom: "-9000000000000000042")
#endif
}
func test_codingOfUInt64() {
#if !arch(arm)
test_codingOf(value: UInt64(9000000000000000042), toAndFrom: "9000000000000000042")
#endif
}
func test_codingOfInt() {
let intSize = MemoryLayout<Int>.size
switch intSize {
case 4: // 32-bit
test_codingOf(value: Int(-2000000042), toAndFrom: "-2000000042")
case 8: // 64-bit
#if arch(arm)
break
#else
test_codingOf(value: Int(-9000000000000000042), toAndFrom: "-9000000000000000042")
#endif
default:
XCTFail("Unexpected UInt size: \(intSize)")
}
}
func test_codingOfUInt() {
let uintSize = MemoryLayout<UInt>.size
switch uintSize {
case 4: // 32-bit
test_codingOf(value: UInt(2000000042), toAndFrom: "2000000042")
case 8: // 64-bit
#if arch(arm)
break
#else
test_codingOf(value: UInt(9000000000000000042), toAndFrom: "9000000000000000042")
#endif
default:
XCTFail("Unexpected UInt size: \(uintSize)")
}
}
func test_codingOfFloat() {
test_codingOf(value: Double(1.5), toAndFrom: "1.5")
}
func test_codingOfDouble() {
test_codingOf(value: Float(1.5), toAndFrom: "1.5")
}
func test_codingOfString() {
test_codingOf(value: "Hello, world!", toAndFrom: "\"Hello, world!\"")
}
func test_codingOfURL() {
test_codingOf(value: URL(string: "https://swift.org")!, toAndFrom: "\"https://swift.org\"")
}
// UInt and Int
func test_codingOfUIntMinMax() {
struct MyValue: Codable {
let int64Min = Int64.min
let int64Max = Int64.max
let uint64Min = UInt64.min
let uint64Max = UInt64.max
}
func compareJSON(_ s1: String, _ s2: String) {
let ss1 = s1.trimmingCharacters(in: CharacterSet(charactersIn: "{}")).split(separator: Character(",")).sorted()
let ss2 = s2.trimmingCharacters(in: CharacterSet(charactersIn: "{}")).split(separator: Character(",")).sorted()
XCTAssertEqual(ss1, ss2)
}
do {
let encoder = JSONEncoder()
let myValue = MyValue()
let result = try encoder.encode(myValue)
let r = String(data: result, encoding: .utf8) ?? "nil"
compareJSON(r, "{\"uint64Min\":0,\"uint64Max\":18446744073709551615,\"int64Min\":-9223372036854775808,\"int64Max\":9223372036854775807}")
} catch {
XCTFail(String(describing: error))
}
}
// MARK: - Helper Functions
private var _jsonEmptyDictionary: Data {
return "{}".data(using: .utf8)!
}
private func _testEncodeFailure<T : Encodable>(of value: T) {
do {
let _ = try JSONEncoder().encode(value)
XCTFail("Encode of top-level \(T.self) was expected to fail.")
} catch {}
}
private func _testRoundTrip<T>(of value: T,
expectedJSON json: Data? = nil,
outputFormatting: JSONEncoder.OutputFormatting = [],
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64,
dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64,
nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw) where T : Codable, T : Equatable {
var payload: Data! = nil
do {
let encoder = JSONEncoder()
encoder.outputFormatting = outputFormatting
encoder.dateEncodingStrategy = dateEncodingStrategy
encoder.dataEncodingStrategy = dataEncodingStrategy
encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
payload = try encoder.encode(value)
} catch {
XCTFail("Failed to encode \(T.self) to JSON: \(error)")
}
if let expectedJSON = json {
// We do not compare expectedJSON to payload directly, because they might have values like
// {"name": "Bob", "age": 22}
// and
// {"age": 22, "name": "Bob"}
// which if compared as Data would not be equal, but the contained JSON values are equal.
// So we wrap them in a JSON type, which compares data as if it were a json.
let expectedJSONObject: JSON
let payloadJSONObject: JSON
do {
expectedJSONObject = try JSON(data: expectedJSON)
} catch {
XCTFail("Invalid JSON data passed as expectedJSON: \(error)")
return
}
do {
payloadJSONObject = try JSON(data: payload)
} catch {
XCTFail("Produced data is not a valid JSON: \(error)")
return
}
XCTAssertEqual(expectedJSONObject, payloadJSONObject, "Produced JSON not identical to expected JSON.")
}
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = dateDecodingStrategy
decoder.dataDecodingStrategy = dataDecodingStrategy
decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy
let decoded = try decoder.decode(T.self, from: payload)
XCTAssertEqual(decoded, value, "\(T.self) did not round-trip to an equal value.")
} catch {
XCTFail("Failed to decode \(T.self) from JSON: \(error)")
}
}
func test_codingOf<T: Codable & Equatable>(value: T, toAndFrom stringValue: String) {
_testRoundTrip(of: TopLevelObjectWrapper(value),
expectedJSON: "{\"value\":\(stringValue)}".data(using: .utf8)!)
_testRoundTrip(of: TopLevelArrayWrapper(value),
expectedJSON: "[\(stringValue)]".data(using: .utf8)!)
}
}
// MARK: - Helper Global Functions
func expectEqualPaths(_ lhs: [CodingKey?], _ rhs: [CodingKey?], _ prefix: String) {
if lhs.count != rhs.count {
XCTFail("\(prefix) [CodingKey?].count mismatch: \(lhs.count) != \(rhs.count)")
return
}
for (k1, k2) in zip(lhs, rhs) {
switch (k1, k2) {
case (nil, nil): continue
case (let _k1?, nil):
XCTFail("\(prefix) CodingKey mismatch: \(type(of: _k1)) != nil")
return
case (nil, let _k2?):
XCTFail("\(prefix) CodingKey mismatch: nil != \(type(of: _k2))")
return
default: break
}
let key1 = k1!
let key2 = k2!
switch (key1.intValue, key2.intValue) {
case (nil, nil): break
case (let i1?, nil):
XCTFail("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != nil")
return
case (nil, let i2?):
XCTFail("\(prefix) CodingKey.intValue mismatch: nil != \(type(of: key2))(\(i2))")
return
case (let i1?, let i2?):
guard i1 == i2 else {
XCTFail("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != \(type(of: key2))(\(i2))")
return
}
break
}
XCTAssertEqual(key1.stringValue,
key2.stringValue,
"\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')")
}
}
// MARK: - Test Types
/* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */
// MARK: - Empty Types
fileprivate struct EmptyStruct : Codable, Equatable {
static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool {
return true
}
}
fileprivate class EmptyClass : Codable, Equatable {
static func ==(_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool {
return true
}
}
// MARK: - Single-Value Types
/// A simple on-off switch type that encodes as a single Bool value.
fileprivate enum Switch : Codable {
case off
case on
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
switch try container.decode(Bool.self) {
case false: self = .off
case true: self = .on
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .off: try container.encode(false)
case .on: try container.encode(true)
}
}
}
/// A simple timestamp type that encodes as a single Double value.
fileprivate struct Timestamp : Codable, Equatable {
let value: Double
init(_ value: Double) {
self.value = value
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(Double.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.value)
}
static func ==(_ lhs: Timestamp, _ rhs: Timestamp) -> Bool {
return lhs.value == rhs.value
}
}
/// A simple referential counter type that encodes as a single Int value.
fileprivate final class Counter : Codable, Equatable {
var count: Int = 0
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
count = try container.decode(Int.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.count)
}
static func ==(_ lhs: Counter, _ rhs: Counter) -> Bool {
return lhs === rhs || lhs.count == rhs.count
}
}
// MARK: - Structured Types
/// A simple address type that encodes as a dictionary of values.
fileprivate struct Address : Codable, Equatable {
let street: String
let city: String
let state: String
let zipCode: Int
let country: String
init(street: String, city: String, state: String, zipCode: Int, country: String) {
self.street = street
self.city = city
self.state = state
self.zipCode = zipCode
self.country = country
}
static func ==(_ lhs: Address, _ rhs: Address) -> Bool {
return lhs.street == rhs.street &&
lhs.city == rhs.city &&
lhs.state == rhs.state &&
lhs.zipCode == rhs.zipCode &&
lhs.country == rhs.country
}
static var testValue: Address {
return Address(street: "1 Infinite Loop",
city: "Cupertino",
state: "CA",
zipCode: 95014,
country: "United States")
}
}
/// A simple person class that encodes as a dictionary of values.
fileprivate class Person : Codable, Equatable {
let name: String
let email: String
// FIXME: This property is present only in order to test the expected result of Codable synthesis in the compiler.
// We want to test against expected encoded output (to ensure this generates an encodeIfPresent call), but we need an output format for that.
// Once we have a VerifyingEncoder for compiler unit tests, we should move this test there.
let website: URL?
init(name: String, email: String, website: URL? = nil) {
self.name = name
self.email = email
self.website = website
}
static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
return lhs.name == rhs.name &&
lhs.email == rhs.email &&
lhs.website == rhs.website
}
static var testValue: Person {
return Person(name: "Johnny Appleseed", email: "[email protected]")
}
}
/// A simple company struct which encodes as a dictionary of nested values.
fileprivate struct Company : Codable, Equatable {
let address: Address
var employees: [Person]
init(address: Address, employees: [Person]) {
self.address = address
self.employees = employees
}
static func ==(_ lhs: Company, _ rhs: Company) -> Bool {
return lhs.address == rhs.address && lhs.employees == rhs.employees
}
static var testValue: Company {
return Company(address: Address.testValue, employees: [Person.testValue])
}
}
// MARK: - Helper Types
/// A key type which can take on any string or integer value.
/// This needs to mirror _JSONKey.
fileprivate struct _TestKey : CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
}
/// Wraps a type T so that it can be encoded at the top level of a payload.
fileprivate struct TopLevelArrayWrapper<T> : Codable, Equatable where T : Codable, T : Equatable {
let value: T
init(_ value: T) {
self.value = value
}
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(value)
}
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
value = try container.decode(T.self)
assert(container.isAtEnd)
}
static func ==(_ lhs: TopLevelArrayWrapper<T>, _ rhs: TopLevelArrayWrapper<T>) -> Bool {
return lhs.value == rhs.value
}
}
fileprivate struct FloatNaNPlaceholder : Codable, Equatable {
init() {}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Float.nan)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let float = try container.decode(Float.self)
if !float.isNaN {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
}
}
static func ==(_ lhs: FloatNaNPlaceholder, _ rhs: FloatNaNPlaceholder) -> Bool {
return true
}
}
fileprivate struct DoubleNaNPlaceholder : Codable, Equatable {
init() {}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Double.nan)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let double = try container.decode(Double.self)
if !double.isNaN {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN."))
}
}
static func ==(_ lhs: DoubleNaNPlaceholder, _ rhs: DoubleNaNPlaceholder) -> Bool {
return true
}
}
/// A type which encodes as an array directly through a single value container.
struct Numbers : Codable, Equatable {
let values = [4, 8, 15, 16, 23, 42]
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let decodedValues = try container.decode([Int].self)
guard decodedValues == values else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "The Numbers are wrong!"))
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(values)
}
static func ==(_ lhs: Numbers, _ rhs: Numbers) -> Bool {
return lhs.values == rhs.values
}
static var testValue: Numbers {
return Numbers()
}
}
/// A type which encodes as a dictionary directly through a single value container.
fileprivate final class Mapping : Codable, Equatable {
let values: [String : URL]
init(values: [String : URL]) {
self.values = values
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
values = try container.decode([String : URL].self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(values)
}
static func ==(_ lhs: Mapping, _ rhs: Mapping) -> Bool {
return lhs === rhs || lhs.values == rhs.values
}
static var testValue: Mapping {
return Mapping(values: ["Apple": URL(string: "http://apple.com")!,
"localhost": URL(string: "http://127.0.0.1")!])
}
}
struct NestedContainersTestType : Encodable {
let testSuperEncoder: Bool
init(testSuperEncoder: Bool = false) {
self.testSuperEncoder = testSuperEncoder
}
enum TopLevelCodingKeys : Int, CodingKey {
case a
case b
case c
}
enum IntermediateCodingKeys : Int, CodingKey {
case one
case two
}
func encode(to encoder: Encoder) throws {
if self.testSuperEncoder {
var topLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(topLevelContainer.codingPath, [], "New first-level keyed container has non-empty codingPath.")
let superEncoder = topLevelContainer.superEncoder(forKey: .a)
expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(topLevelContainer.codingPath, [], "First-level keyed container's codingPath changed.")
expectEqualPaths(superEncoder.codingPath, [TopLevelCodingKeys.a], "New superEncoder had unexpected codingPath.")
_testNestedContainers(in: superEncoder, baseCodingPath: [TopLevelCodingKeys.a])
} else {
_testNestedContainers(in: encoder, baseCodingPath: [])
}
}
func _testNestedContainers(in encoder: Encoder, baseCodingPath: [CodingKey?]) {
expectEqualPaths(encoder.codingPath, baseCodingPath, "New encoder has non-empty codingPath.")
// codingPath should not change upon fetching a non-nested container.
var firstLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "New first-level keyed container has non-empty codingPath.")
// Nested Keyed Container
do {
// Nested container for key should have a new key pushed on.
var secondLevelContainer = firstLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .a)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "New second-level keyed container had unexpected codingPath.")
// Inserting a keyed container should not change existing coding paths.
let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .one)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.one], "New third-level keyed container had unexpected codingPath.")
// Inserting an unkeyed container should not change existing coding paths.
let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer(forKey: .two)
expectEqualPaths(encoder.codingPath, baseCodingPath + [], "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath + [], "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.two], "New third-level unkeyed container had unexpected codingPath.")
}
// Nested Unkeyed Container
do {
// Nested container for key should have a new key pushed on.
var secondLevelContainer = firstLevelContainer.nestedUnkeyedContainer(forKey: .b)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "New second-level keyed container had unexpected codingPath.")
// Appending a keyed container should not change existing coding paths.
let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self)
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 0)], "New third-level keyed container had unexpected codingPath.")
// Appending an unkeyed container should not change existing coding paths.
let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer()
expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.")
expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.")
expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.")
expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 1)], "New third-level unkeyed container had unexpected codingPath.")
}
}
}
// MARK: - Helpers
fileprivate struct JSON: Equatable {
private var jsonObject: Any
fileprivate init(data: Data) throws {
self.jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
}
static func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.jsonObject, rhs.jsonObject) {
case let (lhs, rhs) as ([AnyHashable: Any], [AnyHashable: Any]):
return NSDictionary(dictionary: lhs) == NSDictionary(dictionary: rhs)
case let (lhs, rhs) as ([Any], [Any]):
return NSArray(array: lhs) == NSArray(array: rhs)
default:
return false
}
}
}
// MARK: - Run Tests
extension TestJSONEncoder {
static var allTests: [(String, (TestJSONEncoder) -> () throws -> Void)] {
return [
("test_encodingTopLevelEmptyStruct", test_encodingTopLevelEmptyStruct),
("test_encodingTopLevelEmptyClass", test_encodingTopLevelEmptyClass),
("test_encodingTopLevelSingleValueEnum", test_encodingTopLevelSingleValueEnum),
("test_encodingTopLevelSingleValueStruct", test_encodingTopLevelSingleValueStruct),
("test_encodingTopLevelSingleValueClass", test_encodingTopLevelSingleValueClass),
("test_encodingTopLevelStructuredStruct", test_encodingTopLevelStructuredStruct),
("test_encodingTopLevelStructuredClass", test_encodingTopLevelStructuredClass),
("test_encodingTopLevelDeepStructuredType", test_encodingTopLevelDeepStructuredType),
("test_encodingDate", test_encodingDate),
("test_encodingDateSecondsSince1970", test_encodingDateSecondsSince1970),
("test_encodingDateMillisecondsSince1970", test_encodingDateMillisecondsSince1970),
("test_encodingDateISO8601", test_encodingDateISO8601),
("test_encodingDateFormatted", test_encodingDateFormatted),
("test_encodingDateCustom", test_encodingDateCustom),
("test_encodingDateCustomEmpty", test_encodingDateCustomEmpty),
("test_encodingBase64Data", test_encodingBase64Data),
("test_encodingCustomData", test_encodingCustomData),
("test_encodingCustomDataEmpty", test_encodingCustomDataEmpty),
("test_encodingNonConformingFloats", test_encodingNonConformingFloats),
("test_encodingNonConformingFloatStrings", test_encodingNonConformingFloatStrings),
("test_nestedContainerCodingPaths", test_nestedContainerCodingPaths),
("test_superEncoderCodingPaths", test_superEncoderCodingPaths),
("test_codingOfBool", test_codingOfBool),
("test_codingOfInt8", test_codingOfInt8),
("test_codingOfUInt8", test_codingOfUInt8),
("test_codingOfInt16", test_codingOfInt16),
("test_codingOfUInt16", test_codingOfUInt16),
("test_codingOfInt32", test_codingOfInt32),
("test_codingOfUInt32", test_codingOfUInt32),
("test_codingOfInt64", test_codingOfInt64),
("test_codingOfUInt64", test_codingOfUInt64),
("test_codingOfInt", test_codingOfInt),
("test_codingOfUInt", test_codingOfUInt),
("test_codingOfUIntMinMax", test_codingOfUIntMinMax),
("test_codingOfFloat", test_codingOfFloat),
("test_codingOfDouble", test_codingOfDouble),
("test_codingOfString", test_codingOfString),
("test_codingOfURL", test_codingOfURL),
]
}
}
| apache-2.0 | cf9d3af869e995d2be4ed80dcb6b2229 | 39.570384 | 200 | 0.631692 | 5.058006 | false | true | false | false |
drunknbass/Emby.ApiClient.Swift | Emby.ApiClient/apiinteraction/FindServersInnerResponse.swift | 1 | 2984 | //
// FindServersInnerResponse.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 05/11/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
//package mediabrowser.apiinteraction.connectionmanager;
//
//import mediabrowser.apiinteraction.Response;
//import mediabrowser.model.apiclient.ServerDiscoveryInfo;
//import mediabrowser.model.apiclient.ServerInfo;
//import mediabrowser.model.extensions.IntHelper;
//
//import java.util.ArrayList;
public class FindServersInnerResponse: EmbyApiClient.Response<Array<ServerDiscoveryInfo>> {
private let connectionManager: ConnectionManager
private let response: EmbyApiClient.Response<Array<ServerInfo>>
public init(connectionManager: ConnectionManager, response: EmbyApiClient.Response<Array<ServerInfo>>) {
self.connectionManager = connectionManager;
self.response = response;
super.init()
}
// @Override
// public void onResponse(ArrayList<ServerDiscoveryInfo> foundServers) {
//
// ArrayList<ServerInfo> servers = new ArrayList<ServerInfo>();
//
// for (int i = 0; i < foundServers.size(); i++) {
//
// ServerInfo server = new ServerInfo();
// ServerDiscoveryInfo foundServer = foundServers.get(i);
//
// server.setId(foundServer.getId());
// server.setLocalAddress(foundServer.getAddress());
// server.setName(foundServer.getName());
//
// server.setManualAddress(ConvertEndpointAddressToManualAddress(foundServer));
//
// servers.add(server);
// }
//
// response.onResponse(servers);
// }
//
// @Override
// public void onError(Exception ex) {
//
// Array<ServerInfo> servers = new Array<ServerInfo>();
//
// response.onResponse(servers);
// }
//
// private String ConvertEndpointAddressToManualAddress(ServerDiscoveryInfo info)
// {
// if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(info.getAddress()) && !tangible.DotNetToJavaStringHelper.isNullOrEmpty(info.getEndpointAddress()))
// {
// String address = info.getEndpointAddress().split(":")[0];
//
// // Determine the port, if any
// String[] parts = info.getAddress().split(":");
// if (parts.length > 1)
// {
// String portString = parts[parts.length-1];
//
// int port = 0;
// tangible.RefObject<Integer> tempRef_expected = new tangible.RefObject<Integer>(port);
// if (IntHelper.TryParseCultureInvariant(portString, tempRef_expected))
// {
// address += ":" + portString;
// }
// }
//
// return connectionManager.NormalizeAddress(address);
// }
//
// return null;
// }
} | mit | 1dcf0059816fed9db14a6629b8798329 | 33.298851 | 161 | 0.598726 | 4.298271 | false | false | false | false |
apple/swift-atomics | Sources/Atomics/AtomicStrongReference.swift | 1 | 19471 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Atomics open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import _AtomicsShims
// Double-wide atomic primitives on x86_64 CPUs aren't available by default
// on Linux distributions, and we cannot currently enable them automatically.
#if !(os(Linux) && arch(x86_64)) || ENABLE_DOUBLEWIDE_ATOMICS
/// A class type that supports atomic strong references.
public protocol AtomicReference: AnyObject, AtomicOptionalWrappable
where
AtomicRepresentation == AtomicReferenceStorage<Self>,
AtomicOptionalRepresentation == AtomicOptionalReferenceStorage<Self>
{
// These were added as a workaround for https://bugs.swift.org/browse/SR-10251
// FIXME: We should remove these once the package requires a
// compiler version that contains that fix.
override associatedtype AtomicRepresentation = AtomicReferenceStorage<Self>
override associatedtype AtomicOptionalRepresentation =
AtomicOptionalReferenceStorage<Self>
}
/// The maximum number of other threads that can start accessing a
/// strong reference before an in-flight update needs to cancel and
/// retry.
@inlinable @inline(__always)
internal var _concurrencyWindow: Int { 20 }
extension Unmanaged {
internal func retain(by delta: Int) {
_sa_retain_n(toOpaque(), UInt32(delta))
}
internal func release(by delta: Int) {
_sa_release_n(toOpaque(), UInt32(delta))
}
}
extension Unmanaged {
fileprivate static func passRetained(_ instance: __owned Instance?) -> Self? {
guard let instance = instance else { return nil }
// Note: Swift 5.2 doesn't like this optional promotion without the explicit cast
return .passRetained(instance) as Self
}
}
extension DoubleWord {
fileprivate init(_raw: UnsafeRawPointer?, readers: Int, version: Int) {
let r = UInt(bitPattern: readers) & Self._readersMask
assert(r == readers)
self.init(
high: r | (UInt(bitPattern: version) &<< Self._readersBitWidth),
low: UInt(bitPattern: _raw))
}
@inline(__always)
fileprivate var _raw: UnsafeMutableRawPointer? {
get { UnsafeMutableRawPointer(bitPattern: low) }
set { low = UInt(bitPattern: newValue) }
}
@inline(__always)
fileprivate var _unmanaged: Unmanaged<AnyObject>? {
guard let raw = _raw else { return nil }
return .fromOpaque(raw)
}
@inline(__always)
fileprivate static var _readersBitWidth: Int {
// This reserves 8 bits for the accesses-in-flight counter on 32-bit
// systems, and 16 bits on 64-bit systems.
Int.bitWidth / 4
}
@inline(__always)
fileprivate static var _readersMask: UInt { (1 &<< _readersBitWidth) - 1 }
@inline(__always)
fileprivate var _readers: Int {
get { Int(bitPattern: high & Self._readersMask) }
set {
let n = UInt(bitPattern: newValue) & Self._readersMask
assert(n == newValue)
high = (high & ~Self._readersMask) | n
}
}
@inline(__always)
fileprivate var _version: Int {
get { Int(bitPattern: high &>> Self._readersBitWidth) }
set {
// Silently truncate any high bits we cannot store.
high = (
(UInt(bitPattern: newValue) &<< Self._readersBitWidth) |
high & Self._readersMask)
}
}
}
extension Optional where Wrapped == AnyObject {
fileprivate var _raw: UnsafeMutableRawPointer? {
guard let value = self else { return nil }
return Unmanaged.passUnretained(value).toOpaque()
}
}
extension UnsafeMutablePointer where Pointee == _AtomicReferenceStorage {
@inlinable @inline(__always)
internal var _extract: UnsafeMutablePointer<DoubleWord.AtomicRepresentation> {
UnsafeMutableRawPointer(self)
.assumingMemoryBound(to: DoubleWord.AtomicRepresentation.self)
}
}
@usableFromInline
internal struct _AtomicReferenceStorage {
internal typealias Storage = DoubleWord.AtomicRepresentation
internal var _storage: Storage
@usableFromInline
internal init(_ value: __owned AnyObject?) {
let dword = DoubleWord(
_raw: Unmanaged.passRetained(value)?.toOpaque(),
readers: 0,
version: 0)
_storage = Storage(dword)
}
@usableFromInline
internal func dispose() -> AnyObject? {
let value = _storage.dispose()
precondition(value._readers == 0,
"Attempt to dispose of a busy atomic strong reference \(value)")
return value._unmanaged?.takeRetainedValue()
}
private static func _startLoading(
from pointer: UnsafeMutablePointer<Self>,
hint: DoubleWord? = nil
) -> DoubleWord {
var old = hint ?? Storage.atomicLoad(at: pointer._extract, ordering: .relaxed)
if old._raw == nil {
atomicMemoryFence(ordering: .acquiring)
return old
}
// Increment reader count
while true {
let new = DoubleWord(
_raw: old._raw,
readers: old._readers &+ 1,
version: old._version)
var done: Bool
(done, old) = Storage.atomicWeakCompareExchange(
expected: old,
desired: new,
at: pointer._extract,
successOrdering: .acquiring,
failureOrdering: .acquiring)
if done { return new }
if old._raw == nil { return old }
}
}
private static func _finishLoading(
_ value: DoubleWord,
from pointer: UnsafeMutablePointer<Self>
) -> AnyObject? {
if value._raw == nil { return nil }
// Retain result before we exit the access.
let result = value._unmanaged!.takeUnretainedValue()
// Decrement reader count, using the version number to prevent any
// ABA issues.
var current = value
var done = false
repeat {
assert(current._readers >= 1)
(done, current) = Storage.atomicWeakCompareExchange(
expected: current,
desired: DoubleWord(
_raw: current._raw,
readers: current._readers &- 1,
version: current._version),
at: pointer._extract,
successOrdering: .acquiringAndReleasing,
failureOrdering: .acquiring)
} while !done && current._raw == value._raw && current._version == value._version
if !done {
// The reference changed while we were loading it. Cancel out
// our part of the refcount bias for the loaded instance.
value._unmanaged!.release()
}
return result
}
@usableFromInline
internal static func atomicLoad(
at pointer: UnsafeMutablePointer<Self>
) -> AnyObject? {
let new = _startLoading(from: pointer)
return _finishLoading(new, from: pointer)
}
/// Try updating the current value from `old` to `new`. Don't do anything if the
/// current value differs from `old`.
///
/// Returns a tuple `(exchanged, original)` where `exchanged` indicates whether the
/// update was successful. If `exchange` true, then `original` contains the original
/// reference value; otherwise `original` is nil.
///
/// On an unsuccessful exchange, this function updates `old` to the latest known value,
/// and reenters the current thread as a reader of it.
private static func _tryExchange(
old: inout DoubleWord,
new: Unmanaged<AnyObject>?,
at pointer: UnsafeMutablePointer<Self>
) -> (exchanged: Bool, original: AnyObject?) {
let new = DoubleWord(_raw: new?.toOpaque(), readers: 0, version: old._version &+ 1)
guard let ref = old._unmanaged else {
// Try replacing the current nil value with the desired new value.
let (done, current) = Storage.atomicCompareExchange(
expected: old,
desired: new,
at: pointer._extract,
ordering: .acquiringAndReleasing)
if done {
return (true, nil)
}
// Someone else changed the reference. Give up for now.
old = _startLoading(from: pointer, hint: current)
return (false, nil)
}
assert(old._readers >= 1)
var delta = old._readers + _concurrencyWindow
ref.retain(by: delta)
while true {
// Try replacing the current value with the desired new value.
let (done, current) = Storage.atomicCompareExchange(
expected: old,
desired: new,
at: pointer._extract,
ordering: .acquiringAndReleasing)
if done {
// Successfully replaced the object. Clean up extra retains.
assert(current._readers == old._readers)
assert(current._raw == old._raw)
assert(current._readers <= delta)
ref.release(by: delta - current._readers + 1) // +1 is for our own role as a reader.
return (true, ref.takeRetainedValue())
}
if current._version != old._version {
// Someone else changed the reference. Give up for now.
ref.release(by: delta + 1) // +1 covers our reader bias
old = _startLoading(from: pointer, hint: current)
return (false, nil)
}
// Some readers entered or left while we were processing things. Try again.
assert(current._raw == old._raw)
assert(current._raw != nil)
assert(current._readers >= 1)
if current._readers > delta {
// We need to do more retains to cover readers.
let d = current._readers + _concurrencyWindow
ref.retain(by: d - delta)
delta = d
}
old = current
}
}
@usableFromInline
internal static func atomicExchange(
_ desired: __owned AnyObject?,
at pointer: UnsafeMutablePointer<Self>
) -> AnyObject? {
let new = Unmanaged.passRetained(desired)
var old = _startLoading(from: pointer)
var (exchanged, original) = _tryExchange(old: &old, new: new, at: pointer)
while !exchanged {
(exchanged, original) = _tryExchange(old: &old, new: new, at: pointer)
}
return original
}
@usableFromInline
internal static func atomicCompareExchange(
expected: AnyObject?,
desired: __owned AnyObject?,
at pointer: UnsafeMutablePointer<Self>
) -> (exchanged: Bool, original: AnyObject?) {
let expectedRaw = expected._raw
let new = Unmanaged.passRetained(desired)
var old = _startLoading(from: pointer)
while old._raw == expectedRaw {
let (exchanged, original) = _tryExchange(old: &old, new: new, at: pointer)
if exchanged {
assert(original === expected)
return (true, original)
}
}
// We did not find the expected value. Cancel the retain of the new value
// and return the old value.
new?.release()
return (false, _finishLoading(old, from: pointer))
}
}
@frozen
public struct AtomicReferenceStorage<Value: AnyObject> {
@usableFromInline
internal var _storage: _AtomicReferenceStorage
@inlinable
public init(_ value: __owned Value) {
_storage = .init(value)
}
@inlinable
public func dispose() -> Value {
return unsafeDowncast(_storage.dispose()!, to: Value.self)
}
}
extension AtomicReferenceStorage {
@inlinable @inline(__always)
@_alwaysEmitIntoClient
static func _extract(
_ ptr: UnsafeMutablePointer<Self>
) -> UnsafeMutablePointer<_AtomicReferenceStorage> {
// `Self` is layout-compatible with its only stored property.
return UnsafeMutableRawPointer(ptr)
.assumingMemoryBound(to: _AtomicReferenceStorage.self)
}
}
extension AtomicReferenceStorage: AtomicStorage {
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicLoad(
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicLoadOrdering
) -> Value {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicLoad(at: Self._extract(pointer))
return unsafeDowncast(result!, to: Value.self)
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicStore(
_ desired: __owned Value,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicStoreOrdering
) {
// FIXME: All orderings are treated as acquiring-and-releasing.
_ = _AtomicReferenceStorage.atomicExchange(
desired,
at: _extract(pointer))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicExchange(
_ desired: __owned Value,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicUpdateOrdering
) -> Value {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicExchange(
desired,
at: _extract(pointer))
return unsafeDowncast(result!, to: Value.self)
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicCompareExchange(
expected: Value,
desired: __owned Value,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicUpdateOrdering
) -> (exchanged: Bool, original: Value) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
return (result.exchanged, unsafeDowncast(result.original!, to: Value.self))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicCompareExchange(
expected: Value,
desired: __owned Value,
at pointer: UnsafeMutablePointer<Self>,
successOrdering: AtomicUpdateOrdering,
failureOrdering: AtomicLoadOrdering
) -> (exchanged: Bool, original: Value) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
return (result.exchanged, unsafeDowncast(result.original!, to: Value.self))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicWeakCompareExchange(
expected: Value,
desired: __owned Value,
at pointer: UnsafeMutablePointer<Self>,
successOrdering: AtomicUpdateOrdering,
failureOrdering: AtomicLoadOrdering
) -> (exchanged: Bool, original: Value) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
return (result.exchanged, unsafeDowncast(result.original!, to: Value.self))
}
}
@frozen
public struct AtomicOptionalReferenceStorage<Instance: AnyObject> {
@usableFromInline
internal var _storage: _AtomicReferenceStorage
@inlinable
public init(_ value: __owned Instance?) {
_storage = .init(value)
}
@inlinable
public func dispose() -> Instance? {
guard let value = _storage.dispose() else { return nil }
return unsafeDowncast(value, to: Instance.self)
}
}
extension AtomicOptionalReferenceStorage {
@inlinable @inline(__always)
@_alwaysEmitIntoClient
static func _extract(
_ ptr: UnsafeMutablePointer<Self>
) -> UnsafeMutablePointer<_AtomicReferenceStorage> {
// `Self` is layout-compatible with its only stored property.
return UnsafeMutableRawPointer(ptr)
.assumingMemoryBound(to: _AtomicReferenceStorage.self)
}
}
extension AtomicOptionalReferenceStorage: AtomicStorage {
public typealias Value = Instance?
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicLoad(
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicLoadOrdering
) -> Instance? {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicLoad(at: Self._extract(pointer))
guard let r = result else { return nil }
return unsafeDowncast(r, to: Instance.self)
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicStore(
_ desired: __owned Instance?,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicStoreOrdering
) {
// FIXME: All orderings are treated as acquiring-and-releasing.
_ = _AtomicReferenceStorage.atomicExchange(
desired,
at: _extract(pointer))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicExchange(
_ desired: __owned Instance?,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicUpdateOrdering
) -> Instance? {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicExchange(
desired,
at: _extract(pointer))
guard let r = result else { return nil }
return unsafeDowncast(r, to: Instance.self)
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicCompareExchange(
expected: Instance?,
desired: __owned Instance?,
at pointer: UnsafeMutablePointer<Self>,
ordering: AtomicUpdateOrdering
) -> (exchanged: Bool, original: Instance?) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
guard let original = result.original else { return (result.exchanged, nil) }
return (result.exchanged, unsafeDowncast(original, to: Instance.self))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicCompareExchange(
expected: Instance?,
desired: __owned Instance?,
at pointer: UnsafeMutablePointer<Self>,
successOrdering: AtomicUpdateOrdering,
failureOrdering: AtomicLoadOrdering
) -> (exchanged: Bool, original: Instance?) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
guard let original = result.original else { return (result.exchanged, nil) }
return (result.exchanged, unsafeDowncast(original, to: Instance.self))
}
@inlinable @inline(__always)
@_alwaysEmitIntoClient
@_semantics("atomics.requires_constant_orderings")
public static func atomicWeakCompareExchange(
expected: Instance?,
desired: __owned Instance?,
at pointer: UnsafeMutablePointer<Self>,
successOrdering: AtomicUpdateOrdering,
failureOrdering: AtomicLoadOrdering
) -> (exchanged: Bool, original: Instance?) {
// FIXME: All orderings are treated as acquiring-and-releasing.
let result = _AtomicReferenceStorage.atomicCompareExchange(
expected: expected,
desired: desired,
at: _extract(pointer))
guard let original = result.original else { return (result.exchanged, nil) }
return (result.exchanged, unsafeDowncast(original, to: Instance.self))
}
}
#endif // ENABLE_DOUBLEWIDE_ATOMICS
| apache-2.0 | 60f2d6b890f9745bfa4150fb58ad370e | 32.862609 | 92 | 0.684094 | 4.390304 | false | false | false | false |
LiuToTo/OneSunChat | OneSunChat/OneSunChat/BasicClass/BasicViewController.swift | 1 | 855 | //
// OSunBasicViewController.swift
// OneSunChat
//
// Created by 刘ToTo on 16/2/19.
// Copyright © 2016年 刘ToTo. All rights reserved.
//
import UIKit
class BasicViewController: UIViewController {
// MARK: - initialize
convenience init?(title:String) {
self.init()
self.title = title
}
// MARK: - layout
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0);
}
// MARK: - custom method
// MARK: - lazyloading
lazy var backBarButton: UIBarButtonItem = {
let backImage:UIImage = UIImage(named: "back_nav_icon")!
var backBarButton = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("viewDidLoad"))
return backBarButton
}()
}
| mit | 47cdc22ef6da73ee9010d526954d1a8d | 23.228571 | 143 | 0.629717 | 4.156863 | false | false | false | false |
webventil/OpenSport | OpenSport/OpenSport/VoiceCoach.swift | 1 | 1425 | //
// VoiceCoach.swift
// OpenSport
//
// Created by Arne Tempelhof on 18.11.14.
// Copyright (c) 2014 Arne Tempelhof. All rights reserved.
//
import UIKit
import AVFoundation
internal class VoiceCoach: NSObject, AVSpeechSynthesizerDelegate {
var synthesizer = AVSpeechSynthesizer()
internal class func shared() -> VoiceCoach {
struct Static {
static let voiceCoach = VoiceCoach()
}
return Static.voiceCoach
}
internal func speak(string: String) {
if NSUserDefaults.standardUserDefaults().boolForKey("enableVoiceControl") {
var audioSession = AVAudioSession.sharedInstance()
var success = audioSession.setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.DuckOthers, error: nil)
audioSession.setActive(true, error: nil)
synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self
var utterance = AVSpeechUtterance(string: string)
utterance.rate = 0.2 * AVSpeechUtteranceDefaultSpeechRate
synthesizer.speakUtterance(utterance)
}
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer!, didFinishSpeechUtterance utterance: AVSpeechUtterance!) {
AVAudioSession.sharedInstance().setActive(false, withOptions: AVAudioSessionSetActiveOptions.OptionNotifyOthersOnDeactivation, error: nil)
}
}
| mit | 9d2ca50ff46ab2411734d84b8bcfc0c6 | 32.139535 | 149 | 0.705263 | 5.317164 | false | false | false | false |
EddieCeausu/Projects | swift/random array generation/random_array_generator.swift | 1 | 1999 | import Darwin
func arraygen() -> [Int] {
print("How large is your array?")
let arraysize = Int(readLine()!)!
var array = [Int]()
print("What is your upperlimit?")
let upperlimit = UInt32(readLine()!)!
for _ in 0...arraysize {
array.append(Int(arc4random_uniform(upperlimit)))
}
return array.sorted()
}
func randomnum() -> Int {
print("What is the upperlimit of the number?")
let upperlimit = UInt32(readLine()!)!
var array = [Int]()
for _ in 0...50 {
array.append(Int(arc4random_uniform(upperlimit)))
}
return array[Int(arc4random_uniform(upperlimit)/upperlimit)]
}
var done: Bool = false
while !done {
print("Random Number or Array?")
var response = String(readLine()!).lowercased()
if (response == "number" || response == "random number") {
var rdmnum = randomnum()
print(rdmnum)
}
else if response == "array" || response == "random array" {
var intlist = arraygen()
if intlist.count >= 5000 {
file = "random_array-\(intlist.count)"
contents = String(describing: intlist).replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "[", with: "").replacingOccurrences(of: ",", with: " ")
if let directory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
path = URL(fileURLWithPath: directory).appendingPathComponent(file)
print("File was placed at: \(path) under \(file)")
//writing
do {
try contents.write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
catch {print("Unable to write to: \(path)")}
}
} else {
print(intlist)
}
}
else if((response != "number" || response != "random number") && (response != "array" || response != "random array")) {
print("Try again")
}
}
| gpl-3.0 | a9108b55c62491bc5871bba2a9c7fdb4 | 36.018519 | 180 | 0.6003 | 4.19958 | false | false | false | false |
shajrawi/swift | test/SILGen/property_wrappers.swift | 1 | 11486 | // RUN: %target-swift-frontend -primary-file %s -emit-silgen | %FileCheck %s
// FIXME: switch to %target-swift-emit-silgen once we have syntax tree support
@_propertyWrapper
struct Wrapper<T> {
var value: T
}
@_propertyWrapper
struct WrapperWithInitialValue<T> {
var value: T
init(initialValue: T) {
self.value = initialValue
}
}
protocol DefaultInit {
init()
}
extension Int: DefaultInit { }
struct HasMemberwiseInit<T: DefaultInit> {
@Wrapper(value: false)
var x: Bool
@WrapperWithInitialValue
var y: T = T()
@WrapperWithInitialValue(initialValue: 17)
var z: Int
}
func forceHasMemberwiseInit() {
_ = HasMemberwiseInit(x: Wrapper(value: true), y: 17, z: WrapperWithInitialValue(initialValue: 42))
_ = HasMemberwiseInit<Int>(x: Wrapper(value: true))
_ = HasMemberwiseInit(y: 17)
_ = HasMemberwiseInit<Int>(z: WrapperWithInitialValue(initialValue: 42))
_ = HasMemberwiseInit<Int>()
}
// CHECK: sil_global hidden @$s17property_wrappers9UseStaticV13$staticWibbleAA4LazyOySaySiGGvpZ : $Lazy<Array<Int>>
// HasMemberwiseInit.x.setter
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV1xSbvs : $@convention(method) <T where T : DefaultInit> (Bool, @inout HasMemberwiseInit<T>) -> () {
// CHECK: bb0(%0 : $Bool, %1 : $*HasMemberwiseInit<T>):
// CHECK: [[MODIFY_SELF:%.*]] = begin_access [modify] [unknown] %1 : $*HasMemberwiseInit<T>
// CHECK: [[X_BACKING:%.*]] = struct_element_addr [[MODIFY_SELF]] : $*HasMemberwiseInit<T>, #HasMemberwiseInit.$x
// CHECK: [[X_BACKING_VALUE:%.*]] = struct_element_addr [[X_BACKING]] : $*Wrapper<Bool>, #Wrapper.value
// CHECK: assign %0 to [[X_BACKING_VALUE]] : $*Bool
// CHECK: end_access [[MODIFY_SELF]] : $*HasMemberwiseInit<T>
// variable initialization expression of HasMemberwiseInit.$x
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2$xAA7WrapperVySbGvpfi : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> {
// CHECK: integer_literal $Builtin.Int1, 0
// CHECK-NOT: return
// CHECK: function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers7WrapperV5valueACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // user: %9
// CHECK: return {{%.*}} : $Wrapper<Bool>
// variable initialization expression of HasMemberwiseInit.$y
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2$yAA23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <T where T : DefaultInit> () -> @out T {
// CHECK: bb0(%0 : $*T):
// CHECK-NOT: return
// CHECK: witness_method $T, #DefaultInit.init!allocator.1 : <Self where Self : DefaultInit> (Self.Type) -> () -> Self : $@convention(witness_method: DefaultInit) <τ_0_0 where τ_0_0 : DefaultInit> (@thick τ_0_0.Type) -> @out τ_0_0
// variable initialization expression of HasMemberwiseInit.$z
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2$zAA23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> {
// CHECK: bb0:
// CHECK-NOT: return
// CHECK: integer_literal $Builtin.IntLiteral, 17
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07initialF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0>
// default argument 0 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA_ : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool>
// default argument 1 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA0_ : $@convention(thin) <T where T : DefaultInit> () -> @out T {
// default argument 2 of HasMemberwiseInit.init(x:y:z:)
// CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA1_ : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> {
// HasMemberwiseInit.init()
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitVACyxGycfC : $@convention(method) <T where T : DefaultInit> (@thin HasMemberwiseInit<T>.Type) -> @out HasMemberwiseInit<T> {
// Initialization of x
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2$xAA7WrapperVySbGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> Wrapper<Bool>
// Initialization of y
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2$yAA23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> @out τ_0_0
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07initialF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0>
// Initialization of z
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2$zAA23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> WrapperWithInitialValue<Int>
// CHECK: return
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers9HasNestedV2$y33_{{.*}}14PrivateWrapperAELLVyx_SayxGGvpfi : $@convention(thin) <T> () -> @owned Array<T> {
// CHECK: bb0:
// CHECK: function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
struct HasNested<T> {
@_propertyWrapper
private struct PrivateWrapper<U> {
var value: U
init(initialValue: U) {
self.value = initialValue
}
}
@PrivateWrapper
private var y: [T] = []
static func blah(y: [T]) -> HasNested<T> {
return HasNested<T>()
}
}
// FIXME: For now, we are only checking that we don't crash.
struct HasDefaultInit {
@Wrapper(value: true)
var x
@WrapperWithInitialValue
var y = 25
static func defaultInit() -> HasDefaultInit {
return HasDefaultInit()
}
static func memberwiseInit(x: Bool, y: Int) -> HasDefaultInit {
return HasDefaultInit(x: Wrapper(value: x), y: y)
}
}
struct WrapperWithAccessors {
@Wrapper
var x: Int
// Synthesized setter
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers20WrapperWithAccessorsV1xSivs : $@convention(method) (Int, @inout WrapperWithAccessors) -> ()
// CHECK-NOT: return
// CHECK: struct_element_addr {{%.*}} : $*WrapperWithAccessors, #WrapperWithAccessors.$x
mutating func test() {
x = 17
}
}
func consumeOldValue(_: Int) { }
func consumeNewValue(_: Int) { }
struct WrapperWithDidSetWillSet {
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivs
// CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivw
// CHECK: struct_element_addr {{%.*}} : $*WrapperWithDidSetWillSet, #WrapperWithDidSetWillSet.$x
// CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.value
// CHECK-NEXT: assign %0 to {{%.*}} : $*Int
// CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivW
@Wrapper
var x: Int {
didSet {
consumeNewValue(oldValue)
}
willSet {
consumeOldValue(newValue)
}
}
mutating func test(x: Int) {
self.x = x
}
}
@_propertyWrapper
struct WrapperWithStorageValue<T> {
var value: T
var wrapperValue: Wrapper<T> {
return Wrapper(value: value)
}
}
struct UseWrapperWithStorageValue {
// UseWrapperWithStorageValue.$x.getter
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers26UseWrapperWithStorageValueV2$xAA0D0VySiGvg : $@convention(method) (UseWrapperWithStorageValue) -> Wrapper<Int>
// CHECK-NOT: return
// CHECK: function_ref @$s17property_wrappers23WrapperWithStorageValueV07wrapperF0AA0C0VyxGvg
@WrapperWithStorageValue(value: 17) var x: Int
}
@_propertyWrapper
enum Lazy<Value> {
case uninitialized(() -> Value)
case initialized(Value)
init(initialValue: @autoclosure @escaping () -> Value) {
self = .uninitialized(initialValue)
}
var value: Value {
mutating get {
switch self {
case .uninitialized(let initializer):
let value = initializer()
self = .initialized(value)
return value
case .initialized(let value):
return value
}
}
set {
self = .initialized(newValue)
}
}
}
struct UseLazy<T: DefaultInit> {
@Lazy var foo = 17
@Lazy var bar = T()
@Lazy var wibble = [1, 2, 3]
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers7UseLazyV3foo3bar6wibbleACyxGSi_xSaySiGtcfC : $@convention(method) <T where T : DefaultInit> (Int, @in T, @owned Array<Int>, @thin UseLazy<T>.Type) -> @out UseLazy<T>
// CHECK: function_ref @$s17property_wrappers7UseLazyV4$fooAA0D0OySiGvpfiSiycfu_ : $@convention(thin) (@owned Int) -> Int
// CHECK: function_ref @$s17property_wrappers4LazyO12initialValueACyxGxyXA_tcfC : $@convention(method) <τ_0_0> (@owned @callee_guaranteed () -> @out τ_0_0, @thin Lazy<τ_0_0>.Type) -> @out Lazy<τ_0_0>
}
struct X { }
func triggerUseLazy() {
_ = UseLazy<Int>()
_ = UseLazy<Int>(foo: 17)
_ = UseLazy(bar: 17)
_ = UseLazy<Int>(wibble: [1, 2, 3])
}
struct UseStatic {
// CHECK: sil hidden [transparent] [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvgZ
// CHECK: sil hidden [global_init] [ossa] @$s17property_wrappers9UseStaticV13$staticWibbleAA4LazyOySaySiGGvau
// CHECK: sil hidden [transparent] [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvsZ
@Lazy static var staticWibble = [1, 2, 3]
}
extension WrapperWithInitialValue {
func test() { }
}
class ClassUsingWrapper {
@WrapperWithInitialValue var x = 0
}
// CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers21testClassUsingWrapper1cyAA0deF0C_tF : $@convention(thin) (@guaranteed ClassUsingWrapper) -> ()
func testClassUsingWrapper(c: ClassUsingWrapper) {
// CHECK: class_method [[GETTER:%.*]] : $ClassUsingWrapper, #ClassUsingWrapper.$x!getter.1
c.$x.test()
}
// CHECK-LABEL: sil_vtable ClassUsingWrapper {
// CHECK: #ClassUsingWrapper.x!getter.1: (ClassUsingWrapper) -> () -> Int : @$s17property_wrappers17ClassUsingWrapperC1xSivg // ClassUsingWrapper.x.getter
// CHECK: #ClassUsingWrapper.x!setter.1: (ClassUsingWrapper) -> (Int) -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivs // ClassUsingWrapper.x.setter
// CHECK: #ClassUsingWrapper.x!modify.1: (ClassUsingWrapper) -> () -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivM // ClassUsingWrapper.x.modify
// CHECK: #ClassUsingWrapper.$x!getter.1: (ClassUsingWrapper) -> () -> WrapperWithInitialValue<Int> : @$s17property_wrappers17ClassUsingWrapperC2$xAA0E16WithInitialValueVySiGvg // ClassUsingWrapper.$x.getter
// CHECK: #ClassUsingWrapper.$x!setter.1: (ClassUsingWrapper) -> (WrapperWithInitialValue<Int>) -> () : @$s17property_wrappers17ClassUsingWrapperC2$xAA0E16WithInitialValueVySiGvs // ClassUsingWrapper.$x.setter
// CHECK: #ClassUsingWrapper.$x!modify.1: (ClassUsingWrapper) -> () -> () : @$s17property_wrappers17ClassUsingWrapperC2$xAA0E16WithInitialValueVySiGvM // ClassUsingWrapper.$x.modify
| apache-2.0 | a72e775a0c029efa33157561795e58c8 | 41.128676 | 230 | 0.719435 | 3.606862 | false | false | false | false |
yourtion/BestNPM-iOS | BestNPM/AppDelegate.swift | 1 | 3355 | //
// AppDelegate.swift
// BestNPM
//
// Created by YourtionGuo on 7/29/15.
// Copyright (c) 2015 Yourtion. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
// if let secondaryAsNavController = secondaryViewController as? UINavigationController {
// if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
// if topAsDetailController.detailItem == nil {
// // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
// return true
// }
// }
// }
return true
}
}
| mit | 506d3c573e6a92cfe2c87491580d7353 | 52.253968 | 285 | 0.747243 | 6.055957 | false | false | false | false |
bengottlieb/Chronicle | Chronicle/Listener/LogHistoryManager.swift | 1 | 1863 | //
// LogHistoryManager.swift
// Chronicle
//
// Created by Ben Gottlieb on 6/7/15.
// Copyright (c) 2015 Stand Alone, inc. All rights reserved.
//
import Foundation
public class LogHistoryManager {
public static var instance = LogHistoryManager()
public struct notifications {
public static let historyRegistered = "com.standalone.historyRegistered"
}
public var histories: [NSUUID: LogHistory] = [:]
var queue: dispatch_queue_t
init() {
var attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)
queue = dispatch_queue_create("logger-queue", attr)
}
func routeMessage(message: Message) {
if let uuid = message.senderUUID, history = self.histories[uuid] {
history.recordMessage(message)
}
}
func registerLogHistory(history: LogHistory) {
dispatch_async(self.queue) {
if self.histories[history.sessionUUID] == nil {
println("registering history for \(history.appIdentifier)")
self.histories[history.sessionUUID] = history
history.storageURL = self.baseLogsDirectoryURL.URLByAppendingPathComponent(history.appIdentifier).URLByAppendingPathComponent(history.sessionUUID.UUIDString)
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(LogHistoryManager.notifications.historyRegistered, object: history)
}
}
}
}
var baseLogsDirectoryURL: NSURL {
#if os(iOS)
var base = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
return NSURL(string: base)!
#else
var base = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true)[0] as! String
var url = NSURL(fileURLWithPath: base)
return url!.URLByAppendingPathComponent(NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String)
#endif
}
} | mit | 25028b059d60108265d9b2dd19ffe8b9 | 30.59322 | 161 | 0.746108 | 3.922105 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Swift 4.0/CoreDataTutorial/CoreDataTutorial/AppDelegate.swift | 2 | 4612 | //
// AppDelegate.swift
// CoreDataTutorial
//
// Created by Shridhar Mali on 12/28/17.
// Copyright © 2017 Shridhar Mali. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataTutorial")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | 8a65052c1045d4336ba2ad58ff716ea0 | 48.580645 | 285 | 0.687053 | 5.881378 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.