repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JTExperiments/SwiftBoxCollectionViewLayout
|
refs/heads/master
|
SwiftBox/Layout.swift
|
bsd-3-clause
|
4
|
//
// Layout.swift
// SwiftBox
//
// Created by Josh Abernathy on 1/30/15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import Foundation
/// An evaluated layout.
///
/// Layouts may not be created manually. They only ever come from laying out a
/// Node. See Node.layout.
public struct Layout {
public let frame: CGRect
public let children: [Layout]
internal init(frame: CGRect, children: [Layout]) {
self.frame = frame
self.children = children
}
}
extension Layout: Printable {
public var description: String {
return descriptionForDepth(0)
}
private func descriptionForDepth(depth: Int) -> String {
let selfDescription = "{origin={\(frame.origin.x), \(frame.origin.y)}, size={\(frame.size.width), \(frame.size.height)}}"
if children.count > 0 {
let indentation = reduce(0...depth, "\n") { accum, _ in accum + "\t" }
let childrenDescription = indentation.join(children.map { $0.descriptionForDepth(depth + 1) })
return "\(selfDescription)\(indentation)\(childrenDescription)"
} else {
return selfDescription
}
}
}
|
5271951a5b6e8a9198ae768b345aa660
| 25.95 | 123 | 0.687384 | false | false | false | false |
Azuritul/AZDropdownMenu
|
refs/heads/develop
|
Example/AZDropdownMenu/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// AZDropdownMenu
//
// Created by Chris Wu on 01/05/2016.
// Copyright (c) 2016 Chris Wu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let rootViewController = ViewController()
let nav = UINavigationController(rootViewController: rootViewController)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.tintColor = UIColor.black
self.window!.rootViewController = nav
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
7f9136072dc34d184e38a6a482ce0d56
| 24.354167 | 144 | 0.714873 | false | false | false | false |
Urinx/SomeCodes
|
refs/heads/master
|
Swift/swiftDemo/SpriteKit/hello/hello/GameViewController.swift
|
gpl-2.0
|
1
|
//
// GameViewController.swift
// hello
//
// Created by Eular on 15/4/23.
// Copyright (c) 2015年 Eular. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
597ddf5bcb9270aac1e2858ecb72db09
| 29.898551 | 104 | 0.621951 | false | false | false | false |
acumenrev/CANNavApp
|
refs/heads/master
|
CANNavApp/CANNavApp/Classes/ViewControllers/SearchViewController.swift
|
apache-2.0
|
1
|
//
// SearchViewController.swift
// CANNavApp
//
// Created by Tri Vo on 7/15/16.
// Copyright © 2016 acumenvn. All rights reserved.
//
import UIKit
import QuartzCore
import CoreLocation
import Alamofire
protocol SearchViewControllerDelegate {
func searchViewController(viewController: SearchViewController, choseLocation location : MyLocation, forFromAddress boolValue : Bool) -> Void
}
class SearchViewController: UIViewController {
var mSearchRequest : Alamofire.Request? = nil
var mLastTimeSendRequest : NSTimeInterval = 0
@IBOutlet var mViewMap: UIView!
@IBOutlet var mMapView: GMSMapView!
@IBOutlet var mViewPick: UIView!
@IBOutlet var mTblViewMain: UITableView!
@IBOutlet var mViewSearchAddress: UIView!
@IBOutlet var mTxtSearch: UITextField!
@IBOutlet var mViewSearchModeText: UIView!
@IBOutlet var mViewSearchModeMap: UIView!
var mMarker : GMSMarker? = nil
var mListAddress : Array<QueryLocationResultModel> = Array<QueryLocationResultModel>()
var mDelegate : SearchViewControllerDelegate? = nil
var mMyLocation : MyLocation?
var mSearchForFromAddress : Bool = false
var bSearchModeMapActive : Bool = true
let mSelectedColor : UIColor = UIColor(red: 255/255, green: 214/255, blue: 92/255, alpha: 1)
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?, delegate: SearchViewControllerDelegate?, locationInfo : MyLocation?, searchForFromAddress : Bool) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.mDelegate = delegate
self.mMyLocation = locationInfo
self.mSearchForFromAddress = searchForFromAddress
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
registerNibs()
// setup UI
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Other methods
/**
Setup UI
*/
func setupUI() -> Void {
mViewPick.layer.cornerRadius = 12.0
mViewPick.clipsToBounds = true
refreshSearchModeBar()
setupMapView()
// setup marker
setupMarker()
self.view.sendSubviewToBack(mViewSearchAddress)
self.view.bringSubviewToFront(mViewMap)
}
/**
Setup MapView
*/
func setupMapView() -> Void {
// config Google Maps
mMapView.userInteractionEnabled = true
mMapView.mapType = kGMSTypeNormal
mMapView.settings.myLocationButton = false
mMapView.myLocationEnabled = false
mMapView.settings.compassButton = true
mMapView.settings.zoomGestures = true
mMapView.settings.scrollGestures = true
mMapView.settings.indoorPicker = false
mMapView.settings.tiltGestures = false
mMapView.settings.rotateGestures = true
mMapView.delegate = self
}
/**
Setup marker
*/
func setupMarker() -> Void {
if mMarker == nil {
mMarker = GMSMarker()
mMarker?.map = mMapView
mMarker?.icon = UIImage(named: "default_marker")
mMarker?.title = ""
mMarker?.zIndex = 1
if mMyLocation != nil {
mMarker?.position = (mMyLocation?.mLocationCoordinate)!
// animate map move to user location
mMapView.camera = GMSCameraPosition.cameraWithTarget((mMyLocation?.mLocationCoordinate)!, zoom: 16)
} else {
recenterMarkerInMapView()
}
}
}
/**
Register nibs for table view
*/
func registerNibs() -> Void {
mTblViewMain.registerCellNib(SearchTableViewCell.self)
}
/**
Refresh search mode bar
*/
func refreshSearchModeBar() -> Void {
mViewSearchModeMap.backgroundColor = UIColor.clearColor()
mViewSearchModeText.backgroundColor = UIColor.clearColor()
if bSearchModeMapActive == false {
mViewSearchModeText.backgroundColor = mSelectedColor
} else {
mViewSearchModeMap.backgroundColor = mSelectedColor
}
}
// MARK: - Actions
@IBAction func btnSet_Touched(sender: AnyObject) {
let newLocation = MyLocation(location: mMarker!.position, name: mTxtSearch.text!)
if self.mDelegate != nil {
self.mDelegate?.searchViewController(self, choseLocation: newLocation, forFromAddress: mSearchForFromAddress)
}
self.dismissViewControllerAnimated(true) {
}
}
@IBAction func btnBack_Touched(sender: AnyObject) {
self.view.endEditing(true)
self.dismissViewControllerAnimated(true) {
}
}
@IBAction func btnSearchMap_Touched(sender: AnyObject) {
bSearchModeMapActive = true
mViewSearchAddress.hidden = true
mViewMap.hidden = false
self.view.sendSubviewToBack(mViewSearchAddress)
self.view.bringSubviewToFront(mViewMap)
self.view.endEditing(true)
refreshSearchModeBar()
}
@IBAction func btnSearchAddress_Touched(sender: AnyObject) {
bSearchModeMapActive = false
mViewSearchAddress.hidden = false
mViewMap.hidden = true
self.view.sendSubviewToBack(mViewMap)
self.view.bringSubviewToFront(mViewSearchAddress)
refreshSearchModeBar()
// active keyboard
mTxtSearch.becomeFirstResponder()
}
}
// MARK: - TextField Delegate
extension SearchViewController : UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
mViewSearchAddress.hidden = false
mViewMap.hidden = true
bSearchModeMapActive = false
refreshSearchModeBar()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let range = range.stringRangeForText(textField.text!)
let output = textField.text!.stringByReplacingCharactersInRange(range, withString: string)
if output.length > 3 {
// send request
let currentTimeInMs = NSDate().timeIntervalSince1970
if (currentTimeInMs - mLastTimeSendRequest) > 2 {
// time gap between 2 requests must be greater than 2 seconds
if TUtilsSwift.appDelegate().bCanReachInternet == true {
NetworkManager.sharedInstance.queryLatLongBasedOnAddress(output, completion: { (locationResults) in
if self.mListAddress.count > 0 {
self.mListAddress.removeAll()
}
self.mListAddress += locationResults
// reload table data
self.mTblViewMain.reloadData()
}, fail: { (failError) in
})
} else {
self.navigationController?.presentViewController(self.showNoInternetConnectionMessage(), animated: true, completion: nil)
}
}
} else {
mListAddress.removeAll()
mTblViewMain.reloadData()
}
return true
}
}
// MARK: - GMSMapView Delegate
extension SearchViewController : GMSMapViewDelegate {
func mapView(mapView: GMSMapView, willMove gesture: Bool) {
mViewPick.hidden = true
self.recenterMarkerInMapView()
// resign text field
self.view.endEditing(true)
}
func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) {
mViewPick.hidden = false
if mSearchRequest != nil {
// cancel previous request
mSearchRequest?.cancel()
}
// request location
if TUtilsSwift.appDelegate().bCanReachInternet == true {
// request
NetworkManager.sharedInstance.queryAddressBasedOnLatLng(position.target.latitude, lngValue: position.target.longitude, completion: { (locationResult) in
self.mTxtSearch.text = locationResult?.formattedAddress
}, fail: { (failError) in
})
}
}
func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) {
self.recenterMarkerInMapView()
}
func recenterMarkerInMapView() -> Void {
// get the center of mapview
let center = mMapView.convertPoint(mMapView.center, fromView: mViewMap)
// reset ther marker position so it moves without animation
mMapView.clear()
mMarker?.appearAnimation = kGMSMarkerAnimationNone
mMarker?.position = mMapView.projection.coordinateForPoint(center)
mMarker?.map = mMapView
}
}
// MARK: - UIScrollView Delegate
extension SearchViewController : UIScrollViewDelegate {
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.view.endEditing(true)
}
}
// MARK: - UITableView Delegate
extension SearchViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mListAddress.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchTableViewCell", forIndexPath: indexPath) as! SearchTableViewCell
cell.selectionStyle = .Gray
let location = self.mListAddress[indexPath.row]
cell.setAddress(location.formattedAddress!)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.view.endEditing(true)
let location = self.mListAddress[indexPath.row]
if self.mDelegate != nil {
self.mDelegate?.searchViewController(self, choseLocation: MyLocation(location: CLLocationCoordinate2DMake(location.lat!, location.lng!), name: location.formattedAddress!), forFromAddress: self.mSearchForFromAddress)
}
self.dismissViewControllerAnimated(true) {
}
}
}
|
5d2f4d7e454ad191d603d78ed39ebaab
| 31.242775 | 227 | 0.625224 | false | false | false | false |
tjw/swift
|
refs/heads/master
|
test/SILGen/indirect_enum.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -module-name indirect_enum -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
indirect enum TreeA<T> {
case Nil
case Leaf(T)
case Branch(left: TreeA<T>, right: TreeA<T>)
}
// CHECK-LABEL: sil hidden @$S13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () {
func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) {
// CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $TreeA<T>, [[ARG3:%.*]] : $TreeA<T>):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeA<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
let _ = TreeA<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeA<T>.Branch(left: l, right: r)
}
// CHECK: // end sil function '$S13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF'
// CHECK-LABEL: sil hidden @$S13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () {
func TreeA_reabstract(_ f: @escaping (Int) -> Int) {
// CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (Int) -> Int):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[THUNK:%.*]] = function_ref @$SS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]])
// CHECK-NEXT: store [[FN]] to [init] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
// CHECK: return
let _ = TreeA<(Int) -> Int>.Leaf(f)
}
// CHECK: } // end sil function '$S13indirect_enum16TreeA_reabstractyyS2icF'
enum TreeB<T> {
case Nil
case Leaf(T)
indirect case Branch(left: TreeB<T>, right: TreeB<T>)
}
// CHECK-LABEL: sil hidden @$S13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF
func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt
// CHECK-NEXT: destroy_addr [[NIL]]
// CHECK-NEXT: dealloc_stack [[NIL]]
let _ = TreeB<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt
// CHECK-NEXT: destroy_addr [[LEAF]]
// CHECK-NEXT: dealloc_stack [[LEAF]]
let _ = TreeB<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: copy_addr %1 to [initialization] [[LEFT]] : $*TreeB<T>
// CHECK-NEXT: copy_addr %2 to [initialization] [[RIGHT]] : $*TreeB<T>
// CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]]
// CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1
// CHECK-NEXT: destroy_addr [[BRANCH]]
// CHECK-NEXT: dealloc_stack [[BRANCH]]
let _ = TreeB<T>.Branch(left: l, right: r)
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> ()
func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) {
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $TreeInt, [[ARG3:%.*]] : $TreeInt):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeInt.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, [[ARG1]]
// CHECK-NOT: destroy_value [[LEAF]]
let _ = TreeInt.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeInt.Branch(left: l, right: r)
}
// CHECK: } // end sil function '$S13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF'
enum TreeInt {
case Nil
case Leaf(Int)
indirect case Branch(left: TreeInt, right: TreeInt)
}
enum TrivialButIndirect {
case Direct(Int)
indirect case Indirect(Int)
}
func a() {}
func b<T>(_ x: T) {}
func c<T>(_ x: T, _ y: T) {}
func d() {}
// CHECK-LABEL: sil hidden @$S13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () {
func switchTreeA<T>(_ x: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : $TreeA<T>):
// -- x +2
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>,
// CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]],
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE:bb2]],
// CHECK: case #TreeA.Branch!enumelt.1: [[BRANCH_CASE:bb3]],
switch x {
// CHECK: [[NIL_CASE]]:
// CHECK: function_ref @$S13indirect_enum1ayyF
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]]
// CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T
// CHECK: function_ref @$S13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// -- x +1
// CHECK: destroy_value [[LEAF_BOX]]
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]]
// CHECK: [[LEFT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 0
// CHECK: [[RIGHT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 1
// CHECK: switch_enum [[LEFT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]],
// CHECK: default [[FAIL_LEFT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]]
// CHECK: switch_enum [[RIGHT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]],
// CHECK: default [[FAIL_RIGHT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]]
// CHECK: copy_addr [[LEFT_LEAF_VALUE]]
// CHECK: copy_addr [[RIGHT_LEAF_VALUE]]
// -- x +1
// CHECK: destroy_value [[NODE_BOX]]
// CHECK: br [[OUTER_CONT]]
// CHECK: [[FAIL_RIGHT]]:
// CHECK: br [[DEFAULT:bb[0-9]+]]
// CHECK: [[FAIL_LEFT]]:
// CHECK: br [[DEFAULT]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[DEFAULT]]:
// -- x +1
// CHECK: destroy_value [[ARG_COPY]]
default:
d()
}
// CHECK: [[OUTER_CONT:%.*]]:
// -- x +0
}
// CHECK: } // end sil function '$S13indirect_enum11switchTreeAyyAA0D1AOyxGlF'
// CHECK-LABEL: sil hidden @$S13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F
func switchTreeB<T>(_ x: TreeB<T>) {
// CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] :
// CHECK: switch_enum_addr [[SCRATCH]]
switch x {
// CHECK: bb{{.*}}:
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: function_ref @$S13indirect_enum1ayyF
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] :
// CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]]
// CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] :
// CHECK: function_ref @$S13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[LEAF]]
// CHECK: dealloc_stack [[LEAF]]
// CHECK-NOT: destroy_addr [[LEAF_COPY]]
// CHECK: dealloc_stack [[LEAF_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] :
// CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]]
// -- box +1 immutable
// CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]]
// CHECK: [[TUPLE:%.*]] = project_box [[BOX]]
// CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] :
// CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] :
// CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] :
// CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] :
// CHECK: function_ref @$S13indirect_enum1c{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[Y]]
// CHECK: dealloc_stack [[Y]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK-NOT: destroy_addr [[RIGHT_COPY]]
// CHECK: dealloc_stack [[RIGHT_COPY]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// -- box +0
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[RIGHT_FAIL]]:
// CHECK: destroy_addr [[LEFT_LEAF]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[LEFT_FAIL]]:
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[INNER_CONT]]:
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: function_ref @$S13indirect_enum1dyyF
// CHECK: br [[OUTER_CONT]]
default:
d()
}
// CHECK: [[OUTER_CONT]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F
func guardTreeA<T>(_ tree: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : $TreeA<T>):
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]:
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load [take] [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: [[BORROWED_TUPLE_COPY:%.*]] = begin_borrow [[TUPLE_COPY]]
// CHECK: [[L:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]]
// CHECK: [[COPY_L:%.*]] = copy_value [[L]]
// CHECK: [[R:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]]
// CHECK: [[COPY_R:%.*]] = copy_value [[R]]
// CHECK: end_borrow [[BORROWED_TUPLE_COPY]] from [[TUPLE_COPY]]
// CHECK: destroy_value [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_value [[COPY_R]]
// CHECK: destroy_value [[COPY_L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]:
// CHECK: br
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load [take] [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: [[BORROWED_TUPLE_COPY:%.*]] = begin_borrow [[TUPLE_COPY]]
// CHECK: [[L:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]]
// CHECK: [[COPY_L:%.*]] = copy_value [[L]]
// CHECK: [[R:%.*]] = tuple_extract [[BORROWED_TUPLE_COPY]]
// CHECK: [[COPY_R:%.*]] = copy_value [[R]]
// CHECK: end_borrow [[BORROWED_TUPLE_COPY]] from [[TUPLE_COPY]]
// CHECK: destroy_value [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_value [[COPY_R]]
// CHECK: destroy_value [[COPY_L]]
if case .Branch(left: let l, right: let r) = tree { }
}
}
// CHECK-LABEL: sil hidden @$S13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F
func guardTreeB<T>(_ tree: TreeB<T>) {
do {
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP]]
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP]]
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
if case .Branch(left: let l, right: let r) = tree { }
}
}
// SEMANTIC ARC TODO: This test needs to be made far more comprehensive.
// CHECK-LABEL: sil hidden @$S13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () {
func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) {
// CHECK: bb0([[ARG:%.*]] : $TrivialButIndirect):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt.1: [[NO:bb[0-9]+]]
//
// CHECK: [[NO]]([[PAYLOAD:%.*]] : ${ var Int }):
// CHECK: destroy_value [[PAYLOAD]]
guard case .Direct(let foo) = x else { return }
// CHECK: [[YES]]({{%.*}} : $Int):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt.1: [[NO:bb[0-9]+]]
// CHECK: [[NO]]({{%.*}} : $Int):
// CHECK-NOT: destroy_value
// CHECK: [[YES]]([[BOX:%.*]] : ${ var Int }):
// CHECK: destroy_value [[BOX]]
guard case .Indirect(let bar) = x else { return }
}
// CHECK: } // end sil function '$S13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
|
c51c42c2967c1f3b2161f432fc8f160d
| 44.92278 | 184 | 0.536447 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Legacy/Neocom/Neocom/DgmTypePickerPresenter.swift
|
lgpl-2.1
|
2
|
//
// DgmTypePickerPresenter.swift
// Neocom
//
// Created by Artem Shimanski on 11/30/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import CloudData
class DgmTypePickerPresenter: Presenter {
typealias View = DgmTypePickerViewController
typealias Interactor = DgmTypePickerInteractor
weak var view: View?
lazy var interactor: Interactor! = Interactor(presenter: self)
required init(view: View) {
self.view = view
}
func configure() {
interactor.configure()
applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in
self?.applicationWillEnterForeground()
}
}
private var applicationWillEnterForegroundObserver: NotificationObserver?
}
|
48704af8871e012657cb30c3f07f097c
| 26.290323 | 200 | 0.776596 | false | true | false | false |
hirohisa/PageController
|
refs/heads/master
|
Example project/Example/UseStoryboardContentViewController.swift
|
mit
|
1
|
//
// UseStoryboardContentViewController.swift
// Example
//
// Created by Hirohisa Kawasaki on 2018/08/23.
// Copyright © 2018 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
}
class UseStoryboardContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
tableView.backgroundColor = .blue
view.backgroundColor = .red
print(#function)
print(tableView.frame)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(#function)
print(tableView.frame)
print(tableView.contentInset)
print(tableView.contentOffset)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// XXX: index 0, set wrong frame size to tableView
if #available(iOS 11.0, *) {} else {
if tableView.frame != view.bounds {
tableView.frame = view.bounds
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.label.text = String(indexPath.row)
return cell
}
}
|
ba3de3d893589b5923a86107fa5b13d5
| 27.964286 | 106 | 0.665228 | false | false | false | false |
NghiaTranUIT/Titan
|
refs/heads/master
|
TitanCore/TitanCore/SlackReporter.swift
|
mit
|
2
|
//
// SlackReporter.swift
// TitanCore
//
// Created by Nghia Tran on 4/4/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Foundation
import Alamofire
enum SlackReporterDataType {
case Error
case Response
}
struct SlackReporterData {
let type: SlackReporterDataType
// Slack
private lazy var usernameSlack: String = {
switch self.type {
case .Error:
return "Susu"
case .Response:
return "Rolex"
}
}()
private lazy var icon_emoji: String = {
switch self.type {
case .Error:
return ":dog:"
case .Response:
return ":stopwatch:"
}
}()
// Data
private var error: NSError?
private var responseTime: CGFloat? = 0
private var apiName: String = ""
private var fileName: String = ""
private var functionName: String = ""
private var line: String = ""
private var additionInfo: String = ""
private lazy var buildNumber: String? = {
guard let appInfo = Bundle.main.infoDictionary else {return nil}
let appVersion = appInfo[kCFBundleVersionKey as String] as? String
return appVersion
}()
init(error: NSError?, fileName: String, functionName: String, line: Int) {
self.type = .Error
self.error = error
self.functionName = functionName
self.line = String(line)
// Filename
let componment = fileName.components(separatedBy: "/")
if let _fileName = componment.last {
self.fileName = _fileName
}
else {
self.fileName = "Unknow"
}
}
init(responseTime: CGFloat?, apiName: String, response: Alamofire.DataResponse<AnyObject>?) {
self.type = .Response
self.responseTime = responseTime ?? 0
self.apiName = apiName
self.additionInfo = self.infoTextFromResponse(response: response)
}
mutating func toParam() -> [String: String] {
let text = self.toLog()
let username = self.usernameSlack
let icon = self.icon_emoji
let param: [String: String] = ["username": username,
"icon_emoji": icon,
"text": text]
return param
}
private func infoTextFromResponse(response: Alamofire.DataResponse<AnyObject>?) -> String {
guard let response = response else {return ""}
var text: String = ""
if let URL = response.request?.url?.absoluteString {
text += " *URL* = \(URL)"
}
return text
}
private mutating func toLog() -> String {
// Current User first
var text: String = ""
text += ":dark_sunglasses: "
// Build version
if let buildVersion = self.buildNumber {
text += " :macOS: \(buildVersion)"
}
// Info
switch self.type {
case .Error:
text += ":round_pushpin:\(fileName):\(line) :mag_right:\(functionName)"
if let error = self.error {
text += " 👉 \(error.localizedDescription)"
}
else {
text += " 👉 Unknow"
}
return text
case .Response:
text += ":round_pushpin:\(self.apiName):"
if let responseTime = self.responseTime {
text += " 👉 \(responseTime)"
}
else {
text += " 👉 Unknow"
}
text += " :rocket: \(self.additionInfo)"
return text
}
}
}
class SlackReporter: NSObject {
// MARK:
// MARK: Variable
private let Token = Constants.Logger.Slack.Token
private let ErrorChannel = Constants.Logger.Slack.ErrorChannel
private let ResponseChannel = Constants.Logger.Slack.ResponseChannel
private lazy var URLErrorChannel: String = {
return Constants.Logger.Slack.ErrorChannel_Webhook
}()
private lazy var URLResponseChannel: String = {
return Constants.Logger.Slack.ResponseChannel_Webhook
}()
// MARK:
// MARK: Public
func reportErrorData(_ data: SlackReporterData) {
// Build param
var data = data
let param = data.toParam()
Alamofire.request(self.URLErrorChannel, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { (_) in
}
}
func reportResponseData(data: SlackReporterData) {
// Build param
var data = data
let param = data.toParam()
Alamofire.request(self.self.URLResponseChannel, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { (_) in
}
}
// MARK:
// MARK: Private
static let shareInstance = SlackReporter()
}
extension SlackReporter {
// Test
func testSlackReport() {
let error = NSError.errorWithMessage(message: "Hi, I'm from Error Report")
let data = SlackReporterData(error: error, fileName: #file, functionName: #function, line:#line)
self.reportErrorData(data)
}
// Test
func testSlackResponseReport() {
let data = SlackReporterData(responseTime: 0.2, apiName: "TestAPIName", response: nil)
self.reportResponseData(data: data)
}
}
|
9b35892478e7f37a30ec503a9181e236
| 27.292308 | 143 | 0.556462 | false | false | false | false |
Crebs/WSCloudKitController
|
refs/heads/master
|
WSCloudKitController/CKRecord+Extension.swift
|
mit
|
1
|
//
// CKRecord+Extension.swift
// WSCloudKitController
//
// Created by Riley Crebs on 11/6/15.
// Copyright (c) 2015 Incravo. All rights reserved.
//
import Foundation
import CloudKit
public extension CKRecord {
/**
Updates the CKRecord object from a basic NSObject. Will only update
properties that conform to CKRecordValue, will skip the rest.
@param object NSObject to update the responder with.
*/
public func updateFromObject(object :AnyObject?) {
let objectsClass: AnyClass = object!.classForCoder;
self.updateFromObject(object, objectClass: objectsClass)
}
/**
Class method To make a CKRecord object from a basic NSObject.
Will only handle properties that CKRecord can handle, will skip the rest.
@param object NSObject to convert into a CKRecord object.
@param recordId Record id use to create the CKRecord.
@return returns a CKRecord object created from basic NSObject
*/
public class func recordFromObject(object :AnyObject?, recordId :CKRecordID) -> CKRecord {
let objectsClass: AnyClass = object!.classForCoder;
let typeName: String = NSStringFromClass(objectsClass).componentsSeparatedByString(".").last!
let record: CKRecord = CKRecord(recordType: typeName, recordID: recordId)
record.updateFromObject(object, objectClass: objectsClass)
return record
}
private func updateFromObject(object: AnyObject?, objectClass: AnyClass) {
var count:UInt32 = 0
let properties = class_copyPropertyList(objectClass, &count)
for (var i:UInt32 = 0; i < count; ++i) {
let property = properties[Int(i)]
let cname = property_getName(property)
let name: String = String.fromCString(cname)!
let value: AnyObject? = object?.valueForKeyPath(name)
if CKRecord.isValidCloudKitClass(value!) {
self.setValue(value, forKey: name)
}
}
}
private class func isValidCloudKitClass(object: AnyObject) -> Bool {
return (object.isKindOfClass(NSNumber.self)
|| object.isKindOfClass(NSString.self)
|| object.isKindOfClass(NSDate.self)
|| object.isKindOfClass(CKAsset.self)
|| object.isKindOfClass(NSData.self)
|| object.isKindOfClass(CLLocation.self)
|| object.isKindOfClass(CKReference.self)
|| object.isKindOfClass(NSArray.self))
}
}
|
a0ac7095eaa86666faaf286c5ca8d12c
| 36 | 101 | 0.658449 | false | false | false | false |
groue/GRDB.swift
|
refs/heads/master
|
Tests/GRDBTests/NumericOverflowTests.swift
|
mit
|
1
|
import XCTest
import GRDB
// I think those there is no double between those two, and this is the exact threshold:
private let maxInt64ConvertibleDouble = Double(9223372036854775295 as Int64)
private let minInt64NonConvertibleDouble = Double(9223372036854775296 as Int64)
// Not sure about the exact threshold
private let minInt64ConvertibleDouble = Double(Int64.min)
private let maxInt64NonConvertibleDouble: Double = -9.223372036854777e+18
// Not sure about the exact threshold
private let maxInt32ConvertibleDouble: Double = 2147483647.999999
private let minInt32NonConvertibleDouble: Double = 2147483648
// Not sure about the exact threshold
private let minInt32ConvertibleDouble: Double = -2147483648.999999
private let maxInt32NonConvertibleDouble: Double = -2147483649
class NumericOverflowTests: GRDBTestCase {
func testHighInt64FromDoubleOverflows() {
XCTAssertEqual(Int64.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!, 9223372036854774784)
XCTAssertTrue(Int64.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil)
}
func testLowInt64FromDoubleOverflows() {
XCTAssertEqual(Int64.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int64.min)
XCTAssertTrue(Int64.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil)
}
func testHighInt32FromDoubleOverflows() {
XCTAssertEqual(Int32.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int32.max)
XCTAssertTrue(Int32.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil)
}
func testLowInt32FromDoubleOverflows() {
XCTAssertEqual(Int32.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int32.min)
XCTAssertTrue(Int32.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil)
}
func testHighIntFromDoubleOverflows() {
#if arch(i386) || arch(arm)
// 32 bits Int
XCTAssertEqual(Int.fromDatabaseValue(maxInt32ConvertibleDouble.databaseValue)!, Int.max)
XCTAssertTrue(Int.fromDatabaseValue(minInt32NonConvertibleDouble.databaseValue) == nil)
#elseif arch(x86_64) || arch(arm64)
// 64 bits Int
XCTAssertEqual(Int64(Int.fromDatabaseValue(maxInt64ConvertibleDouble.databaseValue)!), 9223372036854774784)
XCTAssertTrue(Int.fromDatabaseValue((minInt64NonConvertibleDouble).databaseValue) == nil)
#else
fatalError("Unknown architecture")
#endif
}
func testLowIntFromDoubleOverflows() {
#if arch(i386) || arch(arm)
// 32 bits Int
XCTAssertEqual(Int.fromDatabaseValue(minInt32ConvertibleDouble.databaseValue)!, Int.min)
XCTAssertTrue(Int.fromDatabaseValue(maxInt32NonConvertibleDouble.databaseValue) == nil)
#elseif arch(x86_64) || arch(arm64)
// 64 bits Int
XCTAssertEqual(Int.fromDatabaseValue(minInt64ConvertibleDouble.databaseValue)!, Int.min)
XCTAssertTrue(Int.fromDatabaseValue(maxInt64NonConvertibleDouble.databaseValue) == nil)
#else
fatalError("Unknown architecture")
#endif
}
}
|
aca2a3339b2b642d237ee45cd4b2218a
| 44.914286 | 119 | 0.74051 | false | true | false | false |
finder39/Swignals
|
refs/heads/master
|
Source/Swignal4Args.swift
|
mit
|
1
|
//
// Swignal4Args.swift
// Plug
//
// Created by Joseph Neuman on 7/6/16.
// Copyright © 2016 Plug. All rights reserved.
//
import Foundation
open class Swignal4Args<A,B,C,D>: SwignalBase {
public override init() {
}
open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) {
let observer = Observer4Args(swignal: self, observer: observer, callback: callback)
addSwignalObserver(observer)
}
open func fire(_ arg1: A, arg2: B, arg3: C, arg4: D) {
synced(self) {
for watcher in self.swignalObservers {
watcher.fire(arg1, arg2, arg3, arg4)
}
}
}
}
private class Observer4Args<L: AnyObject,A,B,C,D>: ObserverGenericBase<L> {
let callback: (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()
init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) {
self.callback = callback
super.init(swignal: swignal, observer: observer)
}
override func fire(_ args: Any...) {
if let arg1 = args[0] as? A,
let arg2 = args[1] as? B,
let arg3 = args[2] as? C,
let arg4 = args[3] as? D {
fire(arg1: arg1, arg2: arg2, arg3: arg3, arg4: arg4)
} else {
assert(false, "Types incorrect")
}
}
fileprivate func fire(arg1: A, arg2: B, arg3: C, arg4: D) {
if let observer = observer {
callback(observer, arg1, arg2, arg3, arg4)
}
}
}
|
ace54959ee6b7b95507fadb95cb8204b
| 29.722222 | 143 | 0.545509 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Location/MapKit+Helper.swift
|
gpl-3.0
|
1
|
//
// 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 MapKit
import WireDataModel
extension CLLocationCoordinate2D {
var location: CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
}
extension CLPlacemark {
func formattedAddress(_ includeCountry: Bool) -> String? {
let lines: [String]?
lines = [subThoroughfare, thoroughfare, locality, subLocality, administrativeArea, postalCode, country].compactMap { $0 }
return includeCountry ? lines?.joined(separator: ", ") : lines?.dropLast().joined(separator: ", ")
}
}
extension MKMapView {
var zoomLevel: Int {
get {
let float = log2(360 * (Double(frame.height / 256) / region.span.longitudeDelta))
// MKMapView does not like NaN and Infinity, so we return 16 as a default, as 0 would represent the whole world
guard float.isNormal else { return 16 }
return Int(float)
}
set {
setCenterCoordinate(centerCoordinate, zoomLevel: newValue)
}
}
func setCenterCoordinate(_ coordinate: CLLocationCoordinate2D, zoomLevel: Int, animated: Bool = false) {
guard CLLocationCoordinate2DIsValid(coordinate) else { return }
let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(zoomLevel: zoomLevel, viewSize: Float(frame.height)))
setRegion(region, animated: animated)
}
}
extension MKCoordinateSpan {
init(zoomLevel: Int, viewSize: Float) {
self.init(latitudeDelta: min(360 / pow(2, Double(zoomLevel)) * Double(viewSize) / 256, 180), longitudeDelta: 0)
}
}
extension LocationData {
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
}
}
extension MKMapView {
func locationData(name: String?) -> LocationData {
return .locationData(
withLatitude: Float(centerCoordinate.latitude),
longitude: Float(centerCoordinate.longitude),
name: name,
zoomLevel: Int32(zoomLevel)
)
}
func storeLocation() {
let location: LocationData = locationData(name: nil)
Settings.shared[.lastUserLocation] = location
}
func restoreLocation(animated: Bool) {
guard let location: LocationData = Settings.shared[.lastUserLocation] else { return }
setCenterCoordinate(location.coordinate, zoomLevel: Int(location.zoomLevel), animated: animated)
}
}
|
ef3bef0526085b9ca1e3cc97f495aeba
| 31.06 | 136 | 0.685278 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/NameBinding/Inputs/accessibility_other.swift
|
apache-2.0
|
10
|
import has_accessibility
public let a = 0
internal let b = 0
private let c = 0
extension Foo {
public static func a() {}
internal static func b() {}
private static func c() {}
}
struct PrivateInit {
private init() {}
}
extension Foo {
private func method() {}
private typealias TheType = Float
}
extension OriginallyEmpty {
func method() {}
typealias TheType = Float
}
private func privateInBothFiles() {}
func privateInPrimaryFile() {} // expected-note {{previously declared here}}
private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
|
845ecd935454003797c7f2dab885b628
| 19.206897 | 80 | 0.704778 | false | false | false | false |
aschwaighofer/swift
|
refs/heads/master
|
test/IDE/structure.swift
|
apache-2.0
|
2
|
// RUN: %swift-ide-test -structure -source-filename %s | %FileCheck %s
// CHECK: <class>class <name>MyCls</name> : <inherited><elem-typeref>OtherClass</elem-typeref></inherited> {
// CHECK: <property>var <name>bar</name> : <type>Int</type></property>
// CHECK: <property>var <name>anotherBar</name> : <type>Int</type> = 42</property>
// CHECK: <cvar>class var <name>cbar</name> : <type>Int</type> = 0</cvar>
class MyCls : OtherClass {
var bar : Int
var anotherBar : Int = 42
class var cbar : Int = 0
// CHECK: <ifunc>func <name>foo(<param>_ arg1: <type>Int</type></param>, <param><name>name</name>: <type>String</type></param>, <param><name>param</name> par: <type>String</type></param>)</name> {
// CHECK: <lvar>var <name>abc</name></lvar>
// CHECK: <if>if <elem-condexpr>1</elem-condexpr> <brace>{
// CHECK: <call><name>foo</name>(<arg>1</arg>, <arg><name>name</name>:"test"</arg>, <arg><name>param</name>:"test2"</arg>)</call>
// CHECK: }</brace>
// CHECK: }</ifunc>
func foo(_ arg1: Int, name: String, param par: String) {
var abc
if 1 {
foo(1, name:"test", param:"test2")
}
}
// CHECK: <ifunc><name>init (<param><name>x</name>: <type>Int</type></param>)</name></ifunc>
init (x: Int)
// CHECK: <cfunc>class func <name>cfoo()</name></cfunc>
class func cfoo()
// CHECK: }</class>
}
// CHECK: <struct>struct <name>MyStruc</name> {
// CHECK: <property>var <name>myVar</name>: <type>Int</type></property>
// CHECK: <svar>static var <name>sbar</name> : <type>Int</type> = 0</svar>
// CHECK: <sfunc>static func <name>cfoo()</name></sfunc>
// CHECK: }</struct>
struct MyStruc {
var myVar: Int
static var sbar : Int = 0
static func cfoo()
}
// CHECK: <protocol>protocol <name>MyProt</name> {
// CHECK: <ifunc>func <name>foo()</name></ifunc>
// CHECK: <ifunc>func <name>foo2()</name> throws</ifunc>
// CHECK: <ifunc>func <name>foo3()</name> throws -> <type>Int</type></ifunc>
// CHECK: <ifunc>func <name>foo4<<generic-param><name>T</name></generic-param>>()</name> where T: MyProt</ifunc>
// CHECK: <ifunc><name>init()</name></ifunc>
// CHECK: <ifunc><name>init(<param><name>a</name>: <type>Int</type></param>)</name> throws</ifunc>
// CHECK: <ifunc><name>init<<generic-param><name>T</name></generic-param>>(<param><name>a</name>: <type>T</type></param>)</name> where T: MyProt</ifunc>
// CHECK: }</protocol>
protocol MyProt {
func foo()
func foo2() throws
func foo3() throws -> Int
func foo4<T>() where T: MyProt
init()
init(a: Int) throws
init<T>(a: T) where T: MyProt
}
// CHECK: <extension>extension <name>MyStruc</name> {
// CHECK: <ifunc>func <name>foo()</name> {
// CHECK: }</ifunc>
// CHECK: }</extension>
extension MyStruc {
func foo() {
}
}
// CHECK: <gvar>var <name>gvar</name> : <type>Int</type> = 0</gvar>
var gvar : Int = 0
// CHECK: <ffunc>func <name>ffoo()</name> {}</ffunc>
func ffoo() {}
// CHECK: <foreach>for <elem-id><lvar><name>i</name></lvar></elem-id> in <elem-expr>0...5</elem-expr> <brace>{}</brace></foreach>
for i in 0...5 {}
// CHECK: <foreach>for <elem-id>var (<lvar><name>i</name></lvar>, <lvar><name>j</name></lvar>)</elem-id> in <elem-expr>array</elem-expr> <brace>{}</brace></foreach>
for var (i, j) in array {}
// CHECK: <while>while <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></while>
while var v = o, z = o where v > z {}
// CHECK: <while>while <elem-condexpr>v == 0</elem-condexpr> <brace>{}</brace></while>
while v == 0 {}
// CHECK: <repeat-while>repeat <brace>{}</brace> while <elem-expr>v == 0</elem-expr></repeat-while>
repeat {} while v == 0
// CHECK: <if>if <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></if>
if var v = o, z = o where v > z {}
// CHECK: <switch>switch <elem-expr>v</elem-expr> {
// CHECK: <case>case <elem-pattern>1</elem-pattern>: break;</case>
// CHECK: <case>case <elem-pattern>2</elem-pattern>, <elem-pattern>3</elem-pattern>: break;</case>
// CHECK: <case>case <elem-pattern><call><name>Foo</name>(<arg>var <lvar><name>x</name></lvar></arg>, <arg>var <lvar><name>y</name></lvar></arg>)</call> where x < y</elem-pattern>: break;</case>
// CHECK: <case>case <elem-pattern>2 where <call><name>foo</name>()</call></elem-pattern>, <elem-pattern>3 where <call><name>bar</name>()</call></elem-pattern>: break;</case>
// CHECK: <case><elem-pattern>default</elem-pattern>: break;</case>
// CHECK: }</switch>
switch v {
case 1: break;
case 2, 3: break;
case Foo(var x, var y) where x < y: break;
case 2 where foo(), 3 where bar(): break;
default: break;
}
// CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>]</array></gvar>
let myArray = [1, 2, 3]
// CHECK: <gvar>let <name>myDict</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>:<elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>:<elem-expr>3</elem-expr>]</dictionary></gvar>
let myDict = [1:1, 2:2, 3:3]
// CHECK: <gvar>let <name>myArray2</name> = <array>[<elem-expr>1</elem-expr>]</array></gvar>
let myArray2 = [1]
// CHECK: <gvar>let <name>myDict2</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>]</dictionary></gvar>
let myDict2 = [1:1]
// CHECK: <foreach>for <brace>{}</brace></foreach>
for {}
// CHECK: <class>class <name><#MyCls#></name> : <inherited><elem-typeref><#OtherClass#></elem-typeref></inherited> {}
class <#MyCls#> : <#OtherClass#> {}
// CHECK: <ffunc>func <name><#test1#> ()</name> {
// CHECK: <foreach>for <elem-id><lvar><name><#name#></name></lvar></elem-id> in <elem-expr><#items#></elem-expr> <brace>{}</brace></foreach>
// CHECK: }</ffunc>
func <#test1#> () {
for <#name#> in <#items#> {}
}
// CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr><#item1#></elem-expr>, <elem-expr><#item2#></elem-expr>]</array></gvar>
let myArray = [<#item1#>, <#item2#>]
// CHECK: <ffunc>func <name>test1()</name> {
// CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>, <arg><closure><brace>{}</brace></closure></arg>)</call>
// CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>) <arg><closure><brace>{}</brace></closure></arg></call>
// CHECK: }</ffunc>
func test1() {
dispatch_async(dispatch_get_main_queue(), {})
dispatch_async(dispatch_get_main_queue()) {}
}
// CHECK: <enum>enum <name>SomeEnum</name> {
// CHECK: <enum-case>case <enum-elem><name>North</name></enum-elem></enum-case>
// CHECK: <enum-case>case <enum-elem><name>South</name></enum-elem>, <enum-elem><name>East</name></enum-elem></enum-case>
// CHECK: <enum-case>case <enum-elem><name>QRCode(<param><type>String</type></param>)</name></enum-elem></enum-case>
// CHECK: <enum-case>case</enum-case>
// CHECK: }</enum>
enum SomeEnum {
case North
case South, East
case QRCode(String)
case
}
// CHECK: <enum>enum <name>Rawness</name> : <inherited><elem-typeref>Int</elem-typeref></inherited> {
// CHECK: <enum-case>case <enum-elem><name>One</name> = <elem-initexpr>1</elem-initexpr></enum-elem></enum-case>
// CHECK: <enum-case>case <enum-elem><name>Two</name> = <elem-initexpr>2</elem-initexpr></enum-elem>, <enum-elem><name>Three</name> = <elem-initexpr>3</elem-initexpr></enum-elem></enum-case>
// CHECK: }</enum>
enum Rawness : Int {
case One = 1
case Two = 2, Three = 3
}
// CHECK: <ffunc>func <name>rethrowFunc(<param>_ f: <type>() throws -> ()</type> = <closure><brace>{}</brace></closure></param>)</name> rethrows {}</ffunc>
func rethrowFunc(_ f: () throws -> () = {}) rethrows {}
class NestedPoundIf{
func foo1() {
#if os(macOS)
var a = 1
#if USE_METAL
var b = 2
#if os(iOS)
var c = 3
#else
var c = 3
#endif
#else
var b = 2
#endif
#else
var a = 1
#endif
}
func foo2() {}
func foo3() {}
}
// CHECK: <ifunc>func <name>foo2()</name> {}</ifunc>
// CHECK: <ifunc>func <name>foo3()</name> {}</ifunc>
class A {
func foo(_ i : Int, animations: () -> ()) {}
func perform() {foo(5, animations: {})}
// CHECK: <ifunc>func <name>perform()</name> {<call><name>foo</name>(<arg>5</arg>, <arg><name>animations</name>: <closure><brace>{}</brace></closure></arg>)</call>}</ifunc>
}
// CHECK: <typealias>typealias <name>OtherA</name> = A</typealias>
typealias OtherA = A
// CHECK: <typealias>typealias <name>EqBox</name><<generic-param><name>Boxed</name></generic-param>> = Box<Boxed> where Boxed: Equatable</typealias>
typealias EqBox<Boxed> = Box<Boxed> where Boxed: Equatable
class SubscriptTest {
subscript(index: Int) -> Int {
return 0
}
// CHECK: <subscript><name>subscript(<param>index: <type>Int</type></param>)</name> -> <type>Int</type> {
// CHECK: return 0
// CHECK: }</subscript>
subscript(string: String) -> Int {
get {
return 0
}
set(value) {
print(value)
}
}
// CHECK: <subscript><name>subscript(<param>string: <type>String</type></param>)</name> -> <type>Int</type> {
// CHECK: get {
// CHECK: return 0
// CHECK: }
// CHECK: set(<param>value</param>) {
// CHECK: <call><name>print</name>(value)</call>
// CHECK: }</subscript>
}
class ReturnType {
func foo() -> Int { return 0 }
// CHECK: <ifunc>func <name>foo()</name> -> <type>Int</type> {
// CHECK: return 0
// CHECK: }</ifunc>
func foo2<T>() -> T {}
// CHECK: <ifunc>func <name>foo2<<generic-param><name>T</name></generic-param>>()</name> -> <type>T</type> {}</ifunc>
func foo3() -> () -> Int {}
// CHECK: <ifunc>func <name>foo3()</name> -> <type>() -> Int</type> {}</ifunc>
}
protocol FooProtocol {
associatedtype Bar
// CHECK: <associatedtype>associatedtype <name>Bar</name></associatedtype>
associatedtype Baz: Equatable
// CHECK: <associatedtype>associatedtype <name>Baz</name>: Equatable</associatedtype>
associatedtype Qux where Qux: Equatable
// CHECK: <associatedtype>associatedtype <name>Qux</name> where Qux: Equatable</associatedtype>
associatedtype Bar2 = Int
// CHECK: <associatedtype>associatedtype <name>Bar2</name> = Int</associatedtype>
associatedtype Baz2: Equatable = Int
// CHECK: <associatedtype>associatedtype <name>Baz2</name>: Equatable = Int</associatedtype>
associatedtype Qux2 = Int where Qux2: Equatable
// CHECK: <associatedtype>associatedtype <name>Qux2</name> = Int where Qux2: Equatable</associatedtype>
}
// CHECK: <struct>struct <name>Generic</name><<generic-param><name>T</name>: <inherited><elem-typeref>Comparable</elem-typeref></inherited></generic-param>, <generic-param><name>X</name></generic-param>> {
// CHECK: <subscript><name>subscript<<generic-param><name>U</name></generic-param>>(<param>generic: <type>U</type></param>)</name> -> <type>Int</type> { return 0 }</subscript>
// CHECK: <typealias>typealias <name>Foo</name><<generic-param><name>Y</name></generic-param>> = Bar<Y></typealias>
// CHECK: }</struct>
struct Generic<T: Comparable, X> {
subscript<U>(generic: U) -> Int { return 0 }
typealias Foo<Y> = Bar<Y>
}
a.b(c: d?.e?.f, g: h)
// CHECK: <call><name>a.b</name>(<arg><name>c</name>: d?.e?.f</arg>, <arg><name>g</name>: h</arg>)</call>
struct Tuples {
var foo: (Int, String) {
return (1, "test")
// CHECK: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>"test"</elem-expr>)</tuple>
}
func foo2() {
foo3(x: (1, 20))
// CHECK: <call><name>foo3</name>(<arg><name>x</name>: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>20</elem-expr>)</tuple></arg>)</call>
let y = (x, foo4(a: 0))
// CHECK: <lvar>let <name>y</name> = <tuple>(<elem-expr>x</elem-expr>, <elem-expr><call><name>foo4</name>(<arg><name>a</name>: 0</arg>)</call></elem-expr>)</tuple></lvar>
let z = (name1: 1, name2: 2)
// CHECK: <lvar>let <name>z</name> = <tuple>(name1: <elem-expr>1</elem-expr>, name2: <elem-expr>2</elem-expr>)</tuple></lvar>
}
}
completion(a: 1) { (x: Any, y: Int) -> Int in
return x as! Int + y
}
// CHECK: <call><name>completion</name>(<arg><name>a</name>: 1</arg>) <arg><closure>{ (<param>x: <type>Any</type></param>, <param>y: <type>Int</type></param>) -> <type>Int</type> in
// CHECK: return x as! Int + y
// CHECK: }</closure></arg></call>
myFunc(foo: 0,
bar: baz == 0)
// CHECK: <call><name>myFunc</name>(<arg><name>foo</name>: 0</arg>,
// CHECK: <arg><name>bar</name>: baz == 0</arg>)</call>
enum FooEnum {
// CHECK: <enum>enum <name>FooEnum</name> {
case blah(x: () -> () = {
// CHECK: <enum-case>case <enum-elem><name>blah(<param><name>x</name>: <type>() -> ()</type> = <closure><brace>{
@Tuples func foo(x: MyStruc) {}
// CHECK: @Tuples <ffunc>func <name>foo(<param><name>x</name>: <type>MyStruc</type></param>)</name> {}</ffunc>
})
// CHECK: }</brace></closure></param>)</name></enum-elem></enum-case>
}
// CHECK: }</enum>
firstCall("\(1)", 1)
// CHECK: <call><name>firstCall</name>(<arg>"\(1)"</arg>, <arg>1</arg>)</call>
secondCall("\(a: {struct Foo {let x = 10}; return Foo().x}())", 1)
// CHECK: <call><name>secondCall</name>(<arg>"\(a: <call><name><closure><brace>{<struct>struct <name>Foo</name> {<property>let <name>x</name> = 10</property>}</struct>; return <call><name>Foo</name>()</call>.x}</brace></closure></name>()</call>)"</arg>, <arg>1</arg>)</call>
thirdCall("""
\("""
\({
return a()
}())
""")
""")
// CHECK: <call><name>thirdCall</name>("""
// CHECK-NEXT: \("""
// CHECK-NEXT: \(<call><name><closure>{
// CHECK-NEXT: return <call><name>a</name>()</call>
// CHECK-NEXT: }</closure></name>()</call>)
// CHECK-NEXT: """)
// CHECK-NEXT: """)</call>
fourthCall(a: @escaping () -> Int)
// CHECK: <call><name>fourthCall</name>(<arg><name>a</name>: @escaping () -> Int</arg>)</call>
// CHECK: <call><name>foo</name> <closure>{ [unowned <lvar><name>self</name></lvar>, <lvar><name>x</name></lvar>] in _ }</closure></call>
foo { [unowned self, x] in _ }
|
1ed66e6dfa7ca799fdeb1dd5ba1b3f64
| 41.607784 | 274 | 0.603612 | false | false | false | false |
chernyog/CYWeibo
|
refs/heads/master
|
CYWeibo/CYWeibo/CYWeibo/Classes/UI/OAuth/OAuthViewController.swift
|
mit
|
1
|
//
// OAuthViewController.swift
// 04-TDD
//
// Created by 陈勇 on 15/3/3.
// Copyright (c) 2015年 zhssit. All rights reserved.
//
import UIKit
// 定义全局常量
/// 登录成功的通知
let WB_Login_Successed_Notification = "WB_Login_Successed_Notification"
class OAuthViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
// 加载授权界面
loadAuthPage()
}
/// 加载授权界面
func loadAuthPage()
{
// url
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
let request = NSURLRequest(URL: NSURL(string: urlString)!)
webView.loadRequest(request)
}
}
// MARK:- 常量区
let appKey = "2013929282"
let appSecret = "a8ef9f6c61af740a6cd5742874f348ff"
let redirectUri = "http://zhssit.com/"
let grantType = "authorization_code"
let WB_API_URL_String = "https://api.weibo.com"
let WB_Redirect_URL_String = "http://zhssit.com/"
// MARK: - <UIWebViewDelegate>
extension OAuthViewController: UIWebViewDelegate
{
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let result = self.checkLoadPageAndRuturnCodeWithUrl(request.URL!)
if let code = result.code
{
// 请求参数
let params = ["client_id": appKey,
"client_secret": appSecret,
"grant_type": grantType,
"redirect_uri": WB_Redirect_URL_String,
"code": code]
let urlString = "https://api.weibo.com/oauth2/access_token"
NetworkManager.sharedManager.requestJSON(.POST, urlString, params, completion: { (result, error) -> () in
println("==================================================================")
// println(result) // liufan2000
// let accessToken = DictModel4Swift.sharedInstance.objectWithDictionary(result as! NSDictionary, cls: AccessToken.self) as! AccessToken
let accessToken = AccessToken(dict: result as! NSDictionary)
accessToken.saveAccessToken()
println("***********" + accessToken.access_token!)
println("==================================================================")
// 切换UI
NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil)
})
}
return result.isLoadPage
}
/// 根据URL判断是否需要加载页面和返回code
///
/// :param: url url
///
func checkLoadPageAndRuturnCodeWithUrl(url: NSURL)->(isLoadPage: Bool,code: String?,isReloadAuth: Bool)
{
let urlString = url.absoluteString!
if !urlString.hasPrefix(WB_API_URL_String)
{
if urlString.hasPrefix(WB_Redirect_URL_String)
{
// http://zhssit.com/?code=584b72d000009d5eca69ed7fd3de103b
if let query = url.query
{
let flag: NSString = "code="
if query.hasPrefix(flag as String) // 授权
{
// 截取字符串
let code = (query as NSString).substringFromIndex(flag.length)
return (false, code, false)
}
else // 取消授权
{
return (false, nil, true)
}
}
}
return (false, nil,false)
}
return (true, nil, false)
}
}
/*
系统URL
登录 加载页面
https://api.weibo.com/oauth2/authorize?client_id=2013929282&redirect_uri=http://zhssit.com/
登录成功 加载页面
https://api.weibo.com/oauth2/authorize
注册 不加载页面
http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=3fgubw&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2013929282%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fzhssit.com%252F%26from%3D%26with_cookie%3D
切换账号 不加载页面
http://login.sina.com.cn/sso/logout.php?entry=openapi&r=http%3A%2F%2Flogin.sina.com.cn%2Fsso%2Flogout.php%3Fentry%3Dopenapi%26r%3Dhttps%253A%252F%252Fapi.weibo.com%252Foauth2%252Fauthorize%253Fclient_id%253D2013929282%2526redirect_uri%253Dhttp%253A%252F%252Fzhssit.com%252F
取消授权 不加载页面,加载授权界面
http://zhssit.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
授权 不加载页面 返回code
http://zhssit.com/?code=584b72d000009d5eca69ed7fd3de103b
*/
|
482704b3c75f6d76ce714ff1e0344dcd
| 33.637037 | 273 | 0.597647 | false | false | false | false |
edstewbob/cs193p-winter-2015
|
refs/heads/master
|
Calculator/Calculator/ViewController.swift
|
mit
|
2
|
//
// ViewController.swift
// Calculator
//
// Created by jrm on 3/5/15.
// Copyright (c) 2015 Riesam LLC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var history: UILabel!
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
var numberHasADecimalPoint = false
@IBAction func back(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
if count(display.text!) > 0 {
var text = display.text!
text = dropLast(text)
if count(text) > 0 {
display.text = text
}else{
display.text = "0"
}
}
}
addToHistory("🔙")
}
@IBAction func plusMinus(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
//change the sign of the number and allow typing to continue
var text = display.text!
if(text[text.startIndex] == "-"){
display.text = dropFirst(text)
}else{
display.text = "-" + text
}
addToHistory("±")
}else{
operate(sender)
}
}
@IBAction func appendDigit(sender: UIButton) {
if let digit = sender.currentTitle{
if( numberHasADecimalPoint && digit == "."){
// do nothing; additional decimal point is not allowed
}else {
if (digit == "."){
numberHasADecimalPoint = true
}
if userIsInTheMiddleOfTypingANumber {
var text = display.text!
if(text[text.startIndex] == "0"){
text = dropFirst(text)
}
display.text = text + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
//println("digit = \(digit)")
addToHistory(digit)
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
performEnter("")
}
addToHistory(operation)
switch operation {
case "×": performBinaryOperation { $0 * $1 }
case "÷": performBinaryOperation { $1 / $0 }
case "+": performBinaryOperation { $0 + $1 }
case "−": performBinaryOperation { $1 - $0 }
case "√": performUnaryOperation { sqrt($0) }
case "sin": performUnaryOperation { sin($0) }
case "cos": performUnaryOperation { cos($0) }
case "π":
displayValue = M_PI
//enter()
performEnter("constant")
case "±": performUnaryOperation { -$0 }
default: break
}
}
@IBAction func clear(sender: UIButton) {
display.text = "0"
history.text = " "
operandStack.removeAll()
history.text = " "
//println("operandStack = \(operandStack)")
}
/*
* NOTE: I renamed the overloaded performOperation() functions to be two separate functions because
* Objective-C does not support method overloading. The the overloaded functions were working in Xcode 6.2
* but generate errors in Xcode 6.3. See stackover flow
* http://stackoverflow.com/questions/29457720/swift-compiler-error-which-i-dont-understand
*/
func performBinaryOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
performEnter("operation")
}
}
func performUnaryOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
performEnter("operation")
//enter()
}
}
func addToHistory(value: String) {
if let oldText = history.text {
history.text = oldText + " " + value
}else {
history.text = value
}
//get rid of any extra = chars
if let historyText = history.text {
let endIndex = advance(historyText.endIndex, -1)
let range = Range(start: historyText.startIndex, end: endIndex)
let newhistory = historyText.stringByReplacingOccurrencesOfString(
" =",
withString: "",
options: nil,
range: range)
history.text = newhistory
}
}
var operandStack = Array<Double>()
@IBAction func enter() {
performEnter("enterButtonClicked")
}
func performEnter(type: String){
switch(type){
case "operation":
addToHistory("=")
case "enterButtonClicked":
addToHistory("⏎")
case "contant":
addToHistory("⏎")
default:
break
}
userIsInTheMiddleOfTypingANumber = false
numberHasADecimalPoint = false
if let value = displayValue{
operandStack.append(value)
}else {
displayValue = 0
}
//println("operandStack = \(operandStack)")
}
var displayValue: Double? {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
if let value = newValue{
display.text = "\(value)"
}else{
display.text = "0"
}
//display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
|
af19ae36f3450126e38eb23ab63040b0
| 29.546392 | 111 | 0.515862 | false | false | false | false |
klaus01/Centipede
|
refs/heads/master
|
Centipede/UIKit/CE_UIWebView.swift
|
mit
|
1
|
//
// CE_UIWebView.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import UIKit
extension UIWebView {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: UIWebView_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIWebView_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: UIWebView_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is UIWebView_Delegate {
return obj as! UIWebView_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal func getDelegateInstance() -> UIWebView_Delegate {
return UIWebView_Delegate()
}
@discardableResult
public func ce_webView_shouldStartLoadWith(handle: @escaping (UIWebView, URLRequest, UIWebViewNavigationType) -> Bool) -> Self {
ce._webView_shouldStartLoadWith = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_webViewDidStartLoad(handle: @escaping (UIWebView) -> Void) -> Self {
ce._webViewDidStartLoad = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_webViewDidFinishLoad(handle: @escaping (UIWebView) -> Void) -> Self {
ce._webViewDidFinishLoad = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_webView_didFailLoadWithError(handle: @escaping (UIWebView, Error) -> Void) -> Self {
ce._webView_didFailLoadWithError = handle
rebindingDelegate()
return self
}
}
internal class UIWebView_Delegate: NSObject, UIWebViewDelegate {
var _webView_shouldStartLoadWith: ((UIWebView, URLRequest, UIWebViewNavigationType) -> Bool)?
var _webViewDidStartLoad: ((UIWebView) -> Void)?
var _webViewDidFinishLoad: ((UIWebView) -> Void)?
var _webView_didFailLoadWithError: ((UIWebView, Error) -> Void)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(webView(_:shouldStartLoadWith:navigationType:)) : _webView_shouldStartLoadWith,
#selector(webViewDidStartLoad(_:)) : _webViewDidStartLoad,
#selector(webViewDidFinishLoad(_:)) : _webViewDidFinishLoad,
#selector(webView(_:didFailLoadWithError:)) : _webView_didFailLoadWithError,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return _webView_shouldStartLoadWith!(webView, request, navigationType)
}
@objc func webViewDidStartLoad(_ webView: UIWebView) {
_webViewDidStartLoad!(webView)
}
@objc func webViewDidFinishLoad(_ webView: UIWebView) {
_webViewDidFinishLoad!(webView)
}
@objc func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
_webView_didFailLoadWithError!(webView, error)
}
}
|
79aaac71218109ea68eb2d01e9baeda3
| 32.943396 | 136 | 0.643691 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/LayoutExampleSceneViewController+VerticalMosaicBlueprintLayout.swift
|
mit
|
1
|
import Blueprints
import Cocoa
extension LayoutExampleSceneViewController {
func configureMosaicLayout() {
let mosaicBlueprintLayout = VerticalMosaicBlueprintLayout(
patternHeight: 400,
minimumInteritemSpacing: minimumInteritemSpacing,
minimumLineSpacing: minimumLineSpacing,
sectionInset: sectionInsets,
patterns: [
MosaicPattern(alignment: .left,
direction: .vertical,
amount: 2,
multiplier: 0.6),
MosaicPattern(alignment: .left,
direction: .horizontal,
amount: 2,
multiplier: 0.33),
MosaicPattern(alignment: .left,
direction: .vertical,
amount: 1,
multiplier: 0.5),
MosaicPattern(alignment: .left,
direction: .vertical,
amount: 1,
multiplier: 0.5)
])
let titleCollectionReusableViewSize = CGSize(width: view.bounds.width, height: 61)
mosaicBlueprintLayout.headerReferenceSize = titleCollectionReusableViewSize
mosaicBlueprintLayout.footerReferenceSize = titleCollectionReusableViewSize
NSView.animate(withDuration: 0.5) { [weak self] in
self?.layoutExampleCollectionView.collectionViewLayout = mosaicBlueprintLayout
self?.scrollLayoutExampleCollectionViewToTopItem()
}
}
}
|
75c739081992ea7ecc6d702a358c36d3
| 40.4 | 90 | 0.539251 | false | false | false | false |
natecook1000/Euler
|
refs/heads/master
|
Euler.swift
|
mit
|
1
|
// Euler.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// 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
// Custom Operators Using Math Symbols
// See: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-XID_85
// MARK: - Mathematical Constants -
// MARK: Pi
let π = M_PI
// MARK: Tau
let 𝝉 = M_PI * 2
// MARK: e
let 𝑒 = M_E
// MARK: - Logic -
// MARK: Negation
prefix operator ¬ {}
prefix func ¬ (value: Bool) -> Bool {
return !value
}
prefix operator ~ {}
prefix func ~ (value: Bool) -> Bool {
return !value
}
// MARK: Logical Conjunction
infix operator ∧ { associativity left precedence 120 }
func ∧ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left && right()
}
// MARK: Logical Disjunction
infix operator ∨ { associativity left precedence 110 }
func ∨ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left || right()
}
// MARK: Logical XOR
infix operator ⊻ { associativity left precedence 140 }
func ⊻ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left != right()
}
infix operator ⊕ { associativity left precedence 140 }
func ⊕ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left != right()
}
infix operator ↮ { associativity left precedence 140 }
func ↮ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left != right()
}
infix operator ≢ { associativity left precedence 140 }
func ≢ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return left != right()
}
// MARK: Logical NAND
infix operator ⊼ { associativity left precedence 120 }
func ⊼ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return ¬(left ∧ right())
}
infix operator ↑ { associativity left precedence 120 }
func ↑ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return ¬(left ∧ right())
}
// MARK: Logical NOR
infix operator ⊽ { associativity left precedence 110 }
func ⊽ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return ¬(left ∨ right())
}
infix operator ↓ { associativity left precedence 110 }
func ↓ (left: Bool, @autoclosure right: () -> Bool) -> Bool {
return ¬(left ∨ right())
}
// MARK: Logical Assertion
prefix operator ⊦ {}
prefix func ⊦ (@autoclosure condition: () -> Bool) {
assert(condition(), "Assertion Failed")
}
// MARK: - Arithmetic -
// MARK: Multiplication
infix operator × { associativity left precedence 150 }
func × (left: Double, right: Double) -> Double {
return left * right
}
// MARK: Division
infix operator ÷ { associativity left precedence 150 }
func ÷ (left: Double, right: Double) -> Double {
return left / right
}
infix operator ∕ { associativity left precedence 150 }
func ∕ (left: Double, right: Double) -> Double {
return left / right
}
// MARK: Square Root
prefix operator √ {}
prefix func √ (number: Double) -> Double {
return sqrt(number)
}
// MARK: Cube Root
prefix operator ∛ {}
prefix func ∛ (number: Double) -> Double {
return cbrt(number)
}
// MARK: Tesseract Root
prefix operator ∜ {}
prefix func ∜ (number: Double) -> Double {
return pow(number, 1.0 / 4.0)
}
// MARK: Plus / Minus
infix operator ± { associativity left precedence 140 }
func ± (left: Double, right: Double) -> (Double, Double) {
return (left + right, left - right)
}
prefix operator ± {}
prefix func ± (value: Double) -> (Double, Double) {
return 0 ± value
}
// MARK: Minus / Plus
infix operator ∓ { associativity left precedence 140 }
func ∓ (left: Double, right: Double) -> (Double, Double) {
return (left - right, left + right)
}
prefix operator ∓ {}
prefix func ∓ (value: Double) -> (Double, Double) {
return 0 ∓ value
}
// MARK: Divides
infix operator ∣ { associativity left precedence 150 }
func ∣ (left: Int, right: Int) -> Bool {
return left % right == 0
}
// MARK: Does Not Divide
infix operator ∤ { associativity left }
func ∤ (left: Int, right: Int) -> Bool {
return ¬(left ∣ right)
}
// MARK: Sets -
// MARK: Set Membership
infix operator ∈ { associativity left }
func ∈<T: Equatable> (left: T, right: [T]) -> Bool {
return right.contains(left)
}
func ∈<T> (left: T, right: Set<T>) -> Bool {
return right.contains(left)
}
// MARK: Set Non-Membership
infix operator ∉ { associativity left }
func ∉<T: Equatable> (left: T, right: [T]) -> Bool {
return ¬(left ∈ right)
}
func ∉<T> (left: T, right: Set<T>) -> Bool {
return ¬(left ∈ right)
}
// MARK: Converse Set Membership
infix operator ∋ { associativity left }
func ∋<T: Equatable> (left: [T], right: T) -> Bool {
return right ∈ left
}
func ∋<T> (left: Set<T>, right: T) -> Bool {
return right ∈ left
}
// MARK: Converse Set Non-Membership
infix operator ∌ { associativity left }
func ∌<T: Equatable> (left: [T], right: T) -> Bool {
return right ∉ left
}
func ∌<T> (left: Set<T>, right: T) -> Bool {
return right ∉ left
}
// MARK: Set Intersection
infix operator ∩ { associativity left }
func ∩<T: Equatable> (left: [T], right: [T]) -> [T] {
var intersection: [T] = []
for value in left {
if value ∈ right {
intersection.append(value)
}
}
return intersection
}
func ∩<T> (left: Set<T>, right: Set<T>) -> Set<T> {
return left.intersect(right)
}
// MARK: Set Union
infix operator ∪ { associativity left }
func ∪<T: Equatable> (left: [T], right: [T]) -> [T] {
var union: [T] = []
for value in left + right {
if ¬(value ∈ union) {
union.append(value)
}
}
return union
}
func ∪<T> (left: Set<T>, right: Set<T>) -> Set<T> {
return left.union(right)
}
// MARK: Subset
infix operator ⊆ { associativity left }
func ⊆<T: Equatable> (left: [T], right: [T]) -> Bool {
return left == right || (left ⊂ right)
}
func ⊆<T> (left: Set<T>, right: Set<T>) -> Bool {
return left.isSubsetOf(right)
}
// MARK: Proper Subset
infix operator ⊂ { associativity left }
func ⊂<T: Equatable> (left: [T], right: [T]) -> Bool {
for value in left {
if ¬(value ∈ right) {
return false
}
}
return true
}
func ⊂<T> (left: Set<T>, right: Set<T>) -> Bool {
return left.isStrictSubsetOf(right)
}
// MARK: Not A Subset Of
infix operator ⊄ { associativity left }
func ⊄<T: Equatable> (left: [T], right: [T]) -> Bool {
return ¬(left ⊂ right)
}
func ⊄<T> (left: Set<T>, right: Set<T>) -> Bool {
return ¬(left ⊂ right)
}
// MARK: Superset
infix operator ⊇ { associativity left }
func ⊇<T: Equatable> (left: [T], right: [T]) -> Bool {
return right ⊆ left
}
func ⊇<T> (left: Set<T>, right: Set<T>) -> Bool {
return right ⊆ left
}
// MARK: Proper Superset
infix operator ⊃ { associativity left }
func ⊃<T: Equatable> (left: [T], right: [T]) -> Bool {
return right ⊂ left
}
func ⊃<T> (left: Set<T>, right: Set<T>) -> Bool {
return right ⊂ left
}
// MARK: Not A Superset Of
infix operator ⊅ { associativity left }
func ⊅<T: Equatable> (left: [T], right: [T]) -> Bool {
return ¬(left ⊃ right)
}
func ⊅<T> (left: Set<T>, right: Set<T>) -> Bool {
return ¬(left ⊃ right)
}
// MARK: - Sequences -
// MARK: Summation
prefix operator ∑ {}
prefix func ∑ (values: [Double]) -> Double {
return values.reduce(0.0, combine: +)
}
// MARK: Cartesian Product
prefix operator ∏ {}
prefix func ∏ (values: [Double]) -> Double {
return values.reduce(1.0, combine: *)
}
// MARK: - Vectors -
// MARK: Dot Product
infix operator ⋅ {}
func ⋅ (left: [Double], right: [Double]) -> Double {
precondition(left.count == right.count, "arguments must have same count")
let product = zip(left, right).map { (l, r) in l * r }
return ∑product
}
// MARK: Cross Product
func × (left: (Double, Double, Double), right: (Double, Double, Double)) -> (Double, Double, Double) {
let a = left.1 * right.2 - left.2 * right.1
let b = left.2 * right.0 - left.0 * right.2
let c = left.0 * right.1 - left.1 * right.0
return (a, b, c)
}
// Mark: Norm
prefix operator ‖ {}
prefix func ‖ (vector: [Double]) -> Double {
return √(∑vector.map({$0 * $0}))
}
// MARK: Angle
infix operator ⦡ {}
func ⦡ (left: [Double], right: [Double]) -> Double {
return acos((left ⋅ right) / (‖left * ‖right))
}
// MARK: - Comparison -
// MARK: Equality
infix operator ⩵ { associativity left }
func ⩵<T: Equatable> (left: T, right: T) -> Bool {
return left == right
}
// MARK: Inequality
infix operator ≠ { associativity left }
func ≠<T: Equatable> (left: T, right: T) -> Bool {
return left != right
}
// MARK: Less Than Or Equal To
infix operator ≤ { associativity left }
func ≤<T: Comparable> (left: T, right: T) -> Bool {
return left <= right
}
// MARK: Less Than And Not Equal To
infix operator ≨ { associativity left }
func ≨<T: Comparable> (left: T, right: T) -> Bool {
return left < right && left != right
}
// MARK: Greater Than Or Equal To
infix operator ≥ { associativity left }
func ≥<T: Comparable> (left: T, right: T) -> Bool {
return left >= right
}
// MARK: Greater Than And Not Equal To
infix operator ≩ { associativity left }
func ≩<T: Comparable> (left: T, right: T) -> Bool {
return left > right && left != right
}
// MARK: Between
infix operator ≬ { associativity left }
func ≬<T: Comparable> (left: T, right: (T, T)) -> Bool {
return left > right.0 && left < right.1
}
// MARK: Approximate Equality
infix operator ≈ { associativity left }
func ≈(left: Double, right: Double) -> Bool {
let 𝜺 = 1e-3
return abs(nextafter(left, right) - right) < 𝜺
}
// MARK: Approximate Inequality
infix operator ≉ { associativity left }
func ≉(left: Double, right: Double) -> Bool {
return !(left ≈ right)
}
// MARK: - Calculus -
// MARK: 1st Derivative
postfix operator ′ {}
postfix func ′(function: (Double) -> (Double)) -> (Double) -> (Double) {
let h = 1e-3
return { (x) in
return round((function(x + h) - function(x - h)) / (2 * h) / h) * h
}
}
// MARK: 2nd Derivative
postfix operator ′′ {}
postfix func ′′(function: (Double) -> (Double)) -> (Double) -> (Double) {
return (function′)′
}
// MARK: 3rd Derivative
postfix operator ′′′ {}
postfix func ′′′(function: (Double) -> (Double)) -> (Double) -> (Double) {
return ((function′)′)′
}
// MARK: Nth Derivative
infix operator ′ { associativity left }
func ′(left: (Double -> Double), right: UInt) -> (Double) -> (Double) {
return (0 ..< right).reduce(left) { (function, _) in
return function′
}
}
// MARK: Definite Integral
infix operator ∫ { associativity left }
func ∫(left: (a: Double, b: Double), right: (Double) -> (Double)) -> Double {
let n = Int(1e2 + 1)
let h = (left.b - left.a) / Double(n)
return (h / 3.0) * (1 ..< n).reduce(right(left.a)) {
let coefficient = $1 % 2 == 0 ? 4.0 : 2.0
return $0 + coefficient * right(left.a + Double($1) * h)
} + right(left.b)
}
// MARK: Indefinite Integral / Antiderivative
prefix operator ∫ {}
prefix func ∫(function: (Double) -> (Double)) -> (Double) -> (Double) {
return { x in
return (0, x)∫function
}
}
// MARK: - Functions -
// MARK: Composition
infix operator ∘ { associativity left }
func ∘<T, U, V>(left: (U) -> (V), right: (T) -> (U)) -> (T) -> (V) {
return { (x) in
left(right(x))
}
}
|
d7600ccc14b3b78c7a503e8f195d6402
| 22.009225 | 182 | 0.619277 | false | false | false | false |
xu6148152/binea_project_for_ios
|
refs/heads/master
|
helloworld1/helloworld1/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// helloworld1
//
// Created by Binea Xu on 15/2/20.
// Copyright (c) 2015年 Binea Xu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// println("Hello, world")
// let implicitFloat:Float = 4
// println(implicitFloat)
// let label = "The width is"
// let width = 94
// let widthLabel = label
// println(widthLabel)
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largestType:String = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestType = kind
}
}
}
// var result = "largestType \(largestType) largest \(largest)"
println("largestType \(largestType) largest \(largest)")
// 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.
}
}
|
ae5ed804bfafb6123de67a70957164a5
| 26.14 | 80 | 0.540162 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/SILGen/specialize_attr.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s
// CHECK-LABEL: @_specialize(Int, Float)
// CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
@_specialize(Int, Float)
func specializeThis<T, U>(_ t: T, u: U) {}
public protocol PP {
associatedtype PElt
}
public protocol QQ {
associatedtype QElt
}
public struct RR : PP {
public typealias PElt = Float
}
public struct SS : QQ {
public typealias QElt = Int
}
public struct GG<T : PP> {}
// CHECK-LABEL: public class CC<T : PP> {
// CHECK-NEXT: @_specialize(RR, SS)
// CHECK-NEXT: @inline(never) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>)
public class CC<T : PP> {
@inline(never)
@_specialize(RR, SS)
public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-LABEL: sil hidden [_specialize <Int, Float>] @_TF15specialize_attr14specializeThisu0_rFTx1uq__T_ : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-LABEL: sil [noinline] [_specialize <RR, SS, Float, Int>] @_TFC15specialize_attr2CC3foouRd__S_2QQrfTqd__1gGVS_2GGx__Tqd__GS2_x__ : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
// -----------------------------------------------------------------------------
// Test user-specialized subscript accessors.
public protocol TestSubscriptable {
associatedtype Element
subscript(i: Int) -> Element { get set }
}
public class ASubscriptable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(Int)
get {
return storage[i]
}
@_specialize(Int)
set(rhs) {
storage[i] = rhs
}
}
}
// ASubscriptable.subscript.getter with _specialize
// CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
// ASubscriptable.subscript.setter with _specialize
// CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
// ASubscriptable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr14ASubscriptablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
public class Addressable<Element> : TestSubscriptable {
var storage: UnsafeMutablePointer<Element>
init(capacity: Int) {
storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
}
public subscript(i: Int) -> Element {
@_specialize(Int)
unsafeAddress {
return UnsafePointer<Element>(storage + i)
}
@_specialize(Int)
unsafeMutableAddress {
return UnsafeMutablePointer<Element>(storage + i)
}
}
}
// Addressable.subscript.unsafeAddressor with _specialize
// CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressablelu9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
// Addressable.subscript.unsafeMutableAddressor with _specialize
// CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressableau9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
// Addressable.subscript.getter with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
// Addressable.subscript.setter with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
// Addressable.subscript.materializeForSet with no attribute
// CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
|
0d46df8dfc5e81222d8603f2e8cd917a
| 40.194444 | 283 | 0.70263 | false | false | false | false |
square/wire
|
refs/heads/master
|
wire-library/wire-runtime-swift/src/main/swift/ProtoIntCodable+Implementations.swift
|
apache-2.0
|
1
|
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
// MARK: -
extension Int32: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed32 fields
self = try Int32(bitPattern: reader.readFixed32())
case .signed:
// sint32 fields
self = try reader.readVarint32().zigZagDecoded()
case .variable:
// int32 fields
self = try Int32(bitPattern: reader.readVarint32())
}
}
// MARK: - ProtoIntEncodable
/** Encode an `int32`, `sfixed32`, or `sint32` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed32 fields
writer.writeFixed32(self)
case .signed:
// sint32 fields
writer.writeVarint(zigZagEncoded())
case .variable:
// int32 fields
writer.writeVarint(UInt32(bitPattern: self))
}
}
}
// MARK: -
extension UInt32: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed32 fields
self = try reader.readFixed32()
case .signed:
fatalError("Unsupported")
case .variable:
// uint32 fields
self = try reader.readVarint32()
}
}
// MARK: - ProtoIntEncodable
/** Encode a `uint32` or `fixed32` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed32 fields
writer.writeFixed32(self)
case .signed:
fatalError("Unsupported")
case .variable:
// uint32 fields
writer.writeVarint(self)
}
}
}
// MARK: -
extension Int64: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed64 fields
self = try Int64(bitPattern: reader.readFixed64())
case .signed:
// sint64 fields
self = try reader.readVarint64().zigZagDecoded()
case .variable:
// int64 fields
self = try Int64(bitPattern: reader.readVarint64())
}
}
// MARK: - ProtoIntEncodable
/** Encode `int64`, `sint64`, or `sfixed64` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed64 fields
writer.writeFixed64(self)
case .signed:
// sint64 fields
writer.writeVarint(zigZagEncoded())
case .variable:
// int64 fields
writer.writeVarint(UInt64(bitPattern: self))
}
}
}
// MARK: -
extension UInt64: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed64 fields
self = try reader.readFixed64()
case .signed:
fatalError("Unsupported")
case .variable:
// uint64 fields
self = try reader.readVarint64()
}
}
// MARK: - ProtoIntEncodable
/** Encode a `uint64` or `fixed64` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed64 fields
writer.writeFixed64(self)
case .signed:
fatalError("Unsupported")
case .variable:
// uint64 fields
writer.writeVarint(self)
}
}
}
|
a0103106e519d388634967bc135f1ba3
| 26.005917 | 83 | 0.584575 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
refs/heads/master
|
Sources/DiscoveryV1/Models/SourceOptions.swift
|
apache-2.0
|
1
|
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
The **options** object defines which items to crawl from the source system.
*/
public struct SourceOptions: Codable, Equatable {
/**
Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source**
object is set to `box`.
*/
public var folders: [SourceOptionsFolder]?
/**
Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the
**type** field of the **source** object is set to `salesforce`.
*/
public var objects: [SourceOptionsObject]?
/**
Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and
required when the **type** field of the **source** object is set to `sharepoint`.
*/
public var siteCollections: [SourceOptionsSiteColl]?
/**
Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the
**source** object is set to `web_crawl`.
*/
public var urls: [SourceOptionsWebCrawl]?
/**
Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the
**source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified.
*/
public var buckets: [SourceOptionsBuckets]?
/**
When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array
must not be specified.
*/
public var crawlAllBuckets: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case folders = "folders"
case objects = "objects"
case siteCollections = "site_collections"
case urls = "urls"
case buckets = "buckets"
case crawlAllBuckets = "crawl_all_buckets"
}
/**
Initialize a `SourceOptions` with member variables.
- parameter folders: Array of folders to crawl from the Box source. Only valid, and required, when the **type**
field of the **source** object is set to `box`.
- parameter objects: Array of Salesforce document object types to crawl from the Salesforce source. Only valid,
and required, when the **type** field of the **source** object is set to `salesforce`.
- parameter siteCollections: Array of Microsoft SharePointoint Online site collections to crawl from the
SharePoint source. Only valid and required when the **type** field of the **source** object is set to
`sharepoint`.
- parameter urls: Array of Web page URLs to begin crawling the web from. Only valid and required when the
**type** field of the **source** object is set to `web_crawl`.
- parameter buckets: Array of cloud object store buckets to begin crawling. Only valid and required when the
**type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is
`false` or not specified.
- parameter crawlAllBuckets: When `true`, all buckets in the specified cloud object store are crawled. If set to
`true`, the **buckets** array must not be specified.
- returns: An initialized `SourceOptions`.
*/
public init(
folders: [SourceOptionsFolder]? = nil,
objects: [SourceOptionsObject]? = nil,
siteCollections: [SourceOptionsSiteColl]? = nil,
urls: [SourceOptionsWebCrawl]? = nil,
buckets: [SourceOptionsBuckets]? = nil,
crawlAllBuckets: Bool? = nil
)
{
self.folders = folders
self.objects = objects
self.siteCollections = siteCollections
self.urls = urls
self.buckets = buckets
self.crawlAllBuckets = crawlAllBuckets
}
}
|
a52436bf7f15588841e7cce3cdb0d5a5
| 41.140187 | 119 | 0.674872 | false | false | false | false |
apple/swift-nio
|
refs/heads/main
|
Sources/NIOCore/IPProtocol.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// In the Internet Protocol version 4 (IPv4) [RFC791] there is a field
/// called "Protocol" to identify the next level protocol. This is an 8
/// bit field. In Internet Protocol version 6 (IPv6) [RFC8200], this field
/// is called the "Next Header" field.
public struct NIOIPProtocol: RawRepresentable, Hashable {
public typealias RawValue = UInt8
public var rawValue: RawValue
@inlinable
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
extension NIOIPProtocol {
/// - precondition: `rawValue` must fit into an `UInt8`
public init(_ rawValue: Int) {
self.init(rawValue: UInt8(rawValue))
}
}
// Subset of https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml with an RFC
extension NIOIPProtocol {
/// IPv6 Hop-by-Hop Option - [RFC8200]
public static let hopopt = Self(rawValue: 0)
/// Internet Control Message - [RFC792]
public static let icmp = Self(rawValue: 1)
/// Internet Group Management - [RFC1112]
public static let igmp = Self(rawValue: 2)
/// Gateway-to-Gateway - [RFC823]
public static let ggp = Self(rawValue: 3)
/// IPv4 encapsulation - [RFC2003]
public static let ipv4 = Self(rawValue: 4)
/// Stream - [RFC1190][RFC1819]
public static let st = Self(rawValue: 5)
/// Transmission Control - [RFC9293]
public static let tcp = Self(rawValue: 6)
/// Exterior Gateway Protocol - [RFC888][David_Mills]
public static let egp = Self(rawValue: 8)
/// Network Voice Protocol - [RFC741][Steve_Casner]
public static let nvpIi = Self(rawValue: 11)
/// User Datagram - [RFC768][Jon_Postel]
public static let udp = Self(rawValue: 17)
/// Host Monitoring - [RFC869][Bob_Hinden]
public static let hmp = Self(rawValue: 20)
/// Reliable Data Protocol - [RFC908][Bob_Hinden]
public static let rdp = Self(rawValue: 27)
/// Internet Reliable Transaction - [RFC938][Trudy_Miller]
public static let irtp = Self(rawValue: 28)
/// ISO Transport Protocol Class 4 - [RFC905][<mystery contact>]
public static let isoTp4 = Self(rawValue: 29)
/// Bulk Data Transfer Protocol - [RFC969][David_Clark]
public static let netblt = Self(rawValue: 30)
/// Datagram Congestion Control Protocol - [RFC4340]
public static let dccp = Self(rawValue: 33)
/// IPv6 encapsulation - [RFC2473]
public static let ipv6 = Self(rawValue: 41)
/// Reservation Protocol - [RFC2205][RFC3209][Bob_Braden]
public static let rsvp = Self(rawValue: 46)
/// Generic Routing Encapsulation - [RFC2784][Tony_Li]
public static let gre = Self(rawValue: 47)
/// Dynamic Source Routing Protocol - [RFC4728]
public static let dsr = Self(rawValue: 48)
/// Encap Security Payload - [RFC4303]
public static let esp = Self(rawValue: 50)
/// Authentication Header - [RFC4302]
public static let ah = Self(rawValue: 51)
/// NBMA Address Resolution Protocol - [RFC1735]
public static let narp = Self(rawValue: 54)
/// ICMP for IPv6 - [RFC8200]
public static let ipv6Icmp = Self(rawValue: 58)
/// No Next Header for IPv6 - [RFC8200]
public static let ipv6Nonxt = Self(rawValue: 59)
/// Destination Options for IPv6 - [RFC8200]
public static let ipv6Opts = Self(rawValue: 60)
/// EIGRP - [RFC7868]
public static let eigrp = Self(rawValue: 88)
/// OSPFIGP - [RFC1583][RFC2328][RFC5340][John_Moy]
public static let ospfigp = Self(rawValue: 89)
/// Ethernet-within-IP Encapsulation - [RFC3378]
public static let etherip = Self(rawValue: 97)
/// Encapsulation Header - [RFC1241][Robert_Woodburn]
public static let encap = Self(rawValue: 98)
/// Protocol Independent Multicast - [RFC7761][Dino_Farinacci]
public static let pim = Self(rawValue: 103)
/// IP Payload Compression Protocol - [RFC2393]
public static let ipcomp = Self(rawValue: 108)
/// Virtual Router Redundancy Protocol - [RFC5798]
public static let vrrp = Self(rawValue: 112)
/// Layer Two Tunneling Protocol - [RFC3931][Bernard_Aboba]
public static let l2tp = Self(rawValue: 115)
/// Fibre Channel - [Murali_Rajagopal][RFC6172]
public static let fc = Self(rawValue: 133)
/// MANET Protocols - [RFC5498]
public static let manet = Self(rawValue: 138)
/// Host Identity Protocol - [RFC7401]
public static let hip = Self(rawValue: 139)
/// Shim6 Protocol - [RFC5533]
public static let shim6 = Self(rawValue: 140)
/// Wrapped Encapsulating Security Payload - [RFC5840]
public static let wesp = Self(rawValue: 141)
/// Robust Header Compression - [RFC5858]
public static let rohc = Self(rawValue: 142)
/// Ethernet - [RFC8986]
public static let ethernet = Self(rawValue: 143)
/// AGGFRAG encapsulation payload for ESP - [RFC-ietf-ipsecme-iptfs-19]
public static let aggfrag = Self(rawValue: 144)
}
extension NIOIPProtocol: CustomStringConvertible {
private var name: String? {
switch self {
case .hopopt: return "IPv6 Hop-by-Hop Option"
case .icmp: return "Internet Control Message"
case .igmp: return "Internet Group Management"
case .ggp: return "Gateway-to-Gateway"
case .ipv4: return "IPv4 encapsulation"
case .st: return "Stream"
case .tcp: return "Transmission Control"
case .egp: return "Exterior Gateway Protocol"
case .nvpIi: return "Network Voice Protocol"
case .udp: return "User Datagram"
case .hmp: return "Host Monitoring"
case .rdp: return "Reliable Data Protocol"
case .irtp: return "Internet Reliable Transaction"
case .isoTp4: return "ISO Transport Protocol Class 4"
case .netblt: return "Bulk Data Transfer Protocol"
case .dccp: return "Datagram Congestion Control Protocol"
case .ipv6: return "IPv6 encapsulation"
case .rsvp: return "Reservation Protocol"
case .gre: return "Generic Routing Encapsulation"
case .dsr: return "Dynamic Source Routing Protocol"
case .esp: return "Encap Security Payload"
case .ah: return "Authentication Header"
case .narp: return "NBMA Address Resolution Protocol"
case .ipv6Icmp: return "ICMP for IPv6"
case .ipv6Nonxt: return "No Next Header for IPv6"
case .ipv6Opts: return "Destination Options for IPv6"
case .eigrp: return "EIGRP"
case .ospfigp: return "OSPFIGP"
case .etherip: return "Ethernet-within-IP Encapsulation"
case .encap: return "Encapsulation Header"
case .pim: return "Protocol Independent Multicast"
case .ipcomp: return "IP Payload Compression Protocol"
case .vrrp: return "Virtual Router Redundancy Protocol"
case .l2tp: return "Layer Two Tunneling Protocol"
case .fc: return "Fibre Channel"
case .manet: return "MANET Protocols"
case .hip: return "Host Identity Protocol"
case .shim6: return "Shim6 Protocol"
case .wesp: return "Wrapped Encapsulating Security Payload"
case .rohc: return "Robust Header Compression"
case .ethernet: return "Ethernet"
case .aggfrag: return "AGGFRAG encapsulation payload for ESP"
default: return nil
}
}
public var description: String {
let name = self.name ?? "Unknown Protocol"
return "\(name) - \(rawValue)"
}
}
|
8b31644b4ffef748ee3ca8bc65826909
| 43.779661 | 97 | 0.655816 | false | false | false | false |
bigscreen/mangindo-ios
|
refs/heads/master
|
Mangindo/Modules/Contents/ContentsModule.swift
|
mit
|
1
|
//
// ContentsModule.swift
// Mangindo
//
// Created by Gallant Pratama on 27/11/18.
// Copyright © 2018 Gallant Pratama. All rights reserved.
//
import UIKit
class ContentsModule {
private let segue: UIStoryboardSegue
init(segue: UIStoryboardSegue) {
self.segue = segue
}
func instantiate(pageTitle: String, mangaTitleId: String, chapter: Int) {
let controller = segue.destination as! ContentsViewController
let presenter = ContentsPresenter(view: controller, service: NetworkService.shared, mangaTitleId: mangaTitleId, chapter: chapter)
controller.pageTitle = pageTitle
controller.presenter = presenter
}
}
|
a13f4f8ff108cd376f9cd67b299a903c
| 26.6 | 137 | 0.694203 | false | false | false | false |
vapor/vapor
|
refs/heads/main
|
Sources/Vapor/HTTP/Headers/HTTPHeaderExpires.swift
|
mit
|
1
|
import NIO
extension HTTPHeaders {
public struct Expires {
/// The date represented by the header.
public let expires: Date
internal static func parse(_ dateString: String) -> Expires? {
// https://tools.ietf.org/html/rfc7231#section-7.1.1.1
let fmt = DateFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(secondsFromGMT: 0)
fmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
// Obsolete RFC 850 format
fmt.dateFormat = "EEEE, dd-MMM-yy HH:mm:ss zzz"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
// Obsolete ANSI C asctime() format
fmt.dateFormat = "EEE MMM d HH:mm:s yyyy"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
return nil
}
init(expires: Date) {
self.expires = expires
}
/// Generates the header string for this instance.
public func serialize() -> String {
let fmt = DateFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(secondsFromGMT: 0)
fmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return fmt.string(from: expires)
}
}
/// Gets the value of the `Expires` header, if present.
/// ### Note ###
/// `Expires` is legacy and you should switch to using `CacheControl` if possible.
public var expires: Expires? {
get { self.first(name: .expires).flatMap(Expires.parse) }
set {
if let new = newValue?.serialize() {
self.replaceOrAdd(name: .expires, value: new)
} else {
self.remove(name: .expires)
}
}
}
}
|
a0963e5291c0aa430ec637cbb1a1bb6c
| 31.596774 | 86 | 0.531915 | false | true | false | false |
simonkim/AVCapture
|
refs/heads/master
|
AVCapture/AVEncoderVideoToolbox/CoreMedia.swift
|
apache-2.0
|
1
|
//
// CMVideoFormatDescription.swift
// AVCapture
//
// Created by Simon Kim on 2016. 9. 10..
// Copyright © 2016 DZPub.com. All rights reserved.
//
import Foundation
import CoreMedia
extension CMVideoFormatDescription {
/*
* returns number of parameter sets and size of NALUnitLength in bytes
*/
func getH264ParameterSetInfo() -> (status: OSStatus, count: Int, NALHeaderLength: Int32) {
var count: Int = 0
var NALHeaderLength: Int32 = 0
// get parameter set count and nal header length
let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
self, 0, nil, nil, &count, &NALHeaderLength)
return (status: status, count: count, NALHeaderLength: NALHeaderLength)
}
func getH264ParameterSet(at index:Int) -> (status: OSStatus, p: UnsafePointer<UInt8>?, length: Int){
var pParamSet: UnsafePointer<UInt8>? = nil
var length: Int = 0
let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
self, index, &pParamSet, &length, nil, nil)
return (status: status, p: pParamSet, length: length)
}
}
public extension CMSampleBuffer {
public var formatDescription: CMFormatDescription?
{
return CMSampleBufferGetFormatDescription(self)
}
public var sampleTimingInfo: CMSampleTimingInfo? {
get {
var timingInfo: CMSampleTimingInfo? = CMSampleTimingInfo()
let status = CMSampleBufferGetSampleTimingInfo(self, 0, &timingInfo!)
if ( status != noErr ) {
timingInfo = nil
}
return timingInfo
}
}
public var presentationTimeStamp: CMTime {
return CMSampleBufferGetPresentationTimeStamp(self)
}
public var decodeTimeStamp: CMTime {
return CMSampleBufferGetDecodeTimeStamp(self)
}
public func makeDataReady() -> OSStatus {
return CMSampleBufferMakeDataReady(self)
}
}
extension CMFormatDescription {
public var mediaSubType: FourCharCode
{
return CMFormatDescriptionGetMediaSubType(self)
}
}
extension CMVideoDimensions: Equatable {
public static func == (lhs: CMVideoDimensions, rhs: CMVideoDimensions) -> Bool {
return
lhs.width == rhs.width &&
lhs.height == rhs.height
}
}
|
eb0a44d089b1a39c40561729301d5228
| 28.580247 | 104 | 0.642738 | false | false | false | false |
nslogo/DouYuZB
|
refs/heads/master
|
DouYuZB/DouYuZB/Classes/Home/Controller/RecommendViewController.swift
|
mit
|
1
|
//
// RecommendViewController.swift
// DouYuZB
//
// Created by nie on 16/9/21.
// Copyright © 2016年 ZoroNie. All rights reserved.
//
import UIKit
fileprivate let kItemMargin : CGFloat = 10
fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2
fileprivate let kNormalItemH = kItemW * 3 / 4
fileprivate let kPrettyItemH = kItemW * 4 / 3
fileprivate let kHeaderViewH : CGFloat = 50
fileprivate let kNormalCellID = "kNormalCellID"
fileprivate let kPrettyCellID = "kPrettyCellID"
fileprivate let kHeaderViewID = "KHeaderViewID"
class RecommendViewController: UIViewController {
//懒加载
fileprivate lazy var collectionView : UICollectionView = { [unowned self] in
//创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)//头
//创建uicollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]//设置页面随着父控件的缩小尔缩小
collectionView.dataSource = self
collectionView.delegate = self
//注册cell
//代码创建默认cell注册
//collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
//NIB创建默认cell注册
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil)
, forCellWithReuseIdentifier: kNormalCellID)
//NIB创建颜值cell注册
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil)
, forCellWithReuseIdentifier: kPrettyCellID)
//注册header
//代码创建注册
//collectionView.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KHeaderViewID)
//NIB创建注册
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.backgroundColor = UIColor.white
return collectionView
}()
//系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//创建UI
setUpUI()
// UINib(nibName: "CollectionNormalCell", bundle: nil)
}
}
// MARK: - 设置 UI
extension RecommendViewController {
fileprivate func setUpUI() {
view.addSubview(collectionView)
}
}
// MARK: - UICollectionViewDataSource
extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell : UICollectionViewCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath)
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath)
}
//cell.backgroundColor = UIColor.blue
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
return headerView
}
}
|
7040adae92a924e7cd65fbd0b1e0c99f
| 36.279661 | 186 | 0.700386 | false | false | false | false |
edragoev1/pdfjet
|
refs/heads/master
|
Sources/PDFjet/Courier_BoldOblique.swift
|
mit
|
1
|
class Courier_BoldOblique {
static let name = "Courier-BoldOblique"
static let bBoxLLx: Int16 = -57
static let bBoxLLy: Int16 = -250
static let bBoxURx: Int16 = 869
static let bBoxURy: Int16 = 801
static let underlinePosition: Int16 = -100
static let underlineThickness: Int16 = 50
static let notice = "Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved."
static let metrics = Array<[Int16]>(arrayLiteral:
[32,600],
[33,600],
[34,600],
[35,600],
[36,600],
[37,600],
[38,600],
[39,600],
[40,600],
[41,600],
[42,600],
[43,600],
[44,600],
[45,600],
[46,600],
[47,600],
[48,600],
[49,600],
[50,600],
[51,600],
[52,600],
[53,600],
[54,600],
[55,600],
[56,600],
[57,600],
[58,600],
[59,600],
[60,600],
[61,600],
[62,600],
[63,600],
[64,600],
[65,600],
[66,600],
[67,600],
[68,600],
[69,600],
[70,600],
[71,600],
[72,600],
[73,600],
[74,600],
[75,600],
[76,600],
[77,600],
[78,600],
[79,600],
[80,600],
[81,600],
[82,600],
[83,600],
[84,600],
[85,600],
[86,600],
[87,600],
[88,600],
[89,600],
[90,600],
[91,600],
[92,600],
[93,600],
[94,600],
[95,600],
[96,600],
[97,600],
[98,600],
[99,600],
[100,600],
[101,600],
[102,600],
[103,600],
[104,600],
[105,600],
[106,600],
[107,600],
[108,600],
[109,600],
[110,600],
[111,600],
[112,600],
[113,600],
[114,600],
[115,600],
[116,600],
[117,600],
[118,600],
[119,600],
[120,600],
[121,600],
[122,600],
[123,600],
[124,600],
[125,600],
[126,600],
[127,600],
[128,600],
[129,600],
[130,600],
[131,600],
[132,600],
[133,600],
[134,600],
[135,600],
[136,600],
[137,600],
[138,600],
[139,600],
[140,600],
[141,600],
[142,600],
[143,600],
[144,600],
[145,600],
[146,600],
[147,600],
[148,600],
[149,600],
[150,600],
[151,600],
[152,600],
[153,600],
[154,600],
[155,600],
[156,600],
[157,600],
[158,600],
[159,600],
[160,600],
[161,600],
[162,600],
[163,600],
[164,600],
[165,600],
[166,600],
[167,600],
[168,600],
[169,600],
[170,600],
[171,600],
[172,600],
[173,600],
[174,600],
[175,600],
[176,600],
[177,600],
[178,600],
[179,600],
[180,600],
[181,600],
[182,600],
[183,600],
[184,600],
[185,600],
[186,600],
[187,600],
[188,600],
[189,600],
[190,600],
[191,600],
[192,600],
[193,600],
[194,600],
[195,600],
[196,600],
[197,600],
[198,600],
[199,600],
[200,600],
[201,600],
[202,600],
[203,600],
[204,600],
[205,600],
[206,600],
[207,600],
[208,600],
[209,600],
[210,600],
[211,600],
[212,600],
[213,600],
[214,600],
[215,600],
[216,600],
[217,600],
[218,600],
[219,600],
[220,600],
[221,600],
[222,600],
[223,600],
[224,600],
[225,600],
[226,600],
[227,600],
[228,600],
[229,600],
[230,600],
[231,600],
[232,600],
[233,600],
[234,600],
[235,600],
[236,600],
[237,600],
[238,600],
[239,600],
[240,600],
[241,600],
[242,600],
[243,600],
[244,600],
[245,600],
[246,600],
[247,600],
[248,600],
[249,600],
[250,600],
[251,600],
[252,600],
[253,600],
[254,600],
[255,600]
)
}
|
87c4365eba0cc68b11c6a7e771b4245d
| 18.817797 | 117 | 0.345734 | false | false | false | false |
dipen30/Qmote
|
refs/heads/master
|
KodiRemote/KodiRemote/Controllers/MovieDetailsViewController.swift
|
apache-2.0
|
1
|
//
// MovieDetailsViewController.swift
// Kodi Remote
//
// Created by Quixom Technology on 19/08/16.
// Copyright © 2016 Quixom Technology. All rights reserved.
//
import UIKit
class MovieDetailsViewController: UIViewController {
@IBOutlet var movieArtImage: UIImageView!
@IBOutlet var movieImage: UIImageView!
@IBOutlet var movieName: UILabel!
@IBOutlet var movieTagline: UILabel!
@IBOutlet var movieRuntime: UILabel!
@IBOutlet var movieGenre: UILabel!
@IBOutlet var movieRatings: UILabel!
@IBOutlet var moviePlot: UITextView!
@IBOutlet weak var movieDirectors: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var playButtonTop: NSLayoutConstraint!
@IBOutlet weak var downloadButton: UIButton!
var url: URL!
var videoTitle: String!
var fileHash: String!
var movieid = Int()
var moviefile = String()
var movieView: UIView!
var rc: RemoteCalls!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port)
movie_id = movieid
self.rc.jsonRpcCall("VideoLibrary.GetMovieDetails", params: "{\"movieid\":\(movieid),\"properties\":[\"genre\",\"year\",\"rating\",\"director\",\"trailer\",\"tagline\",\"plot\",\"imdbnumber\",\"runtime\",\"votes\",\"thumbnail\",\"art\"]}"){(response: AnyObject?) in
DispatchQueue.main.async {
self.generateResponse(response as! NSDictionary)
self.playButton.isHidden = false
self.downloadButton.isHidden = false
}
}
self.moviefile = self.moviefile.replacingOccurrences(of: "\\", with: "/")
self.rc.jsonRpcCall("Files.PrepareDownload", params: "{\"path\":\"\(self.moviefile)\"}"){ (response: AnyObject?) in
let data = response as! NSDictionary
let path = "/" + String(describing: (data["details"] as! NSDictionary)["path"]!)
let host = "http://" + global_ipaddress + ":" + global_port
self.url = URL(string: host + path)
// if Same video is already in progress then do not allow user
// to download the video
self.fileHash = md5(string: self.url.lastPathComponent)
if downloadQueue[self.fileHash] != nil{
DispatchQueue.main.async {
self.downloadButton.isEnabled = false
}
downloadQueue[self.fileHash] = self.downloadButton
}
// change the color of download icon if file exists
if is_file_exists("Videos", filename: self.url!.lastPathComponent){
DispatchQueue.main.async {
self.downloadButton.tintColor = UIColor(red:0.01, green:0.66, blue:0.96, alpha:1.0)
}
}
}
}
deinit {
movie_id = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateViewBasedOnScreenSize()
self.playButton.layer.cornerRadius = 0.5 * self.playButton.bounds.size.width
self.playButton.layer.borderWidth = 2.0
self.playButton.layer.borderColor = UIColor(red:0.00, green:0.80, blue:1.00, alpha:1.0).cgColor
self.playButton.clipsToBounds = true
self.movieName.text = ""
self.movieTagline.text = ""
self.movieRuntime.text = ""
self.movieGenre.text = ""
self.movieRatings.text = ""
self.moviePlot.text = ""
self.movieDirectors.text = ""
}
func updateViewBasedOnScreenSize(){
// Updated constrains based on screen size
let viewWidth = self.view.bounds.size.width
if viewWidth < 350 {
self.playButtonTop.constant = 135.0
}else if viewWidth > 350 && viewWidth < 400 {
self.playButtonTop.constant = 145.0
}else if viewWidth > 400 {
self.playButtonTop.constant = 160.0
}
}
@IBAction func playMovie(_ sender: AnyObject) {
self.rc.jsonRpcCall("Player.Open", params: "{\"item\":{\"movieid\":\(self.movieid)}}"){ (response: AnyObject?) in
}
}
func generateResponse(_ jsonData: AnyObject){
let movieDetails = jsonData["moviedetails"] as! NSDictionary
self.movieName.text = String(describing: movieDetails["label"]!)
self.videoTitle = String(describing: movieDetails["label"]!)
self.movieTagline.text = String(describing: movieDetails["tagline"]!)
self.movieRuntime.text = String((movieDetails["runtime"]! as! Int) / 60) + " min | " + String(describing: movieDetails["year"]!)
self.movieGenre.text = String((movieDetails["genre"]! as AnyObject).componentsJoined(by: ", "))
self.movieRatings.text = String(format: "%.1f", movieDetails["rating"]! as! Double) + "/10"
self.moviePlot.text = String(describing: movieDetails["plot"]!)
self.movieDirectors.text = "Directors: " + String((movieDetails["director"]! as AnyObject).componentsJoined(by: ", "))
self.movieImage.contentMode = .scaleAspectFit
self.movieImage.layer.zPosition = 1
let thumbnail = String(describing: movieDetails["thumbnail"]!)
if thumbnail != "" {
let url = URL(string: getThumbnailUrl(thumbnail))
self.movieImage.kf.setImage(with: url!)
}
self.movieArtImage.contentMode = .scaleAspectFill
let art = movieDetails["art"] as! NSDictionary
if (art as AnyObject).count != 0 {
let fanart = art["fanart"] as! String
if fanart != "" {
let url = URL(string: getThumbnailUrl(fanart))
self.movieArtImage.kf.setImage(with: url!)
}
}
}
@IBAction func downloadMovie(_ sender: AnyObject) {
if is_file_exists("Videos", filename: self.url!.lastPathComponent){
print("Play Video locally")
// let videoUrl = getLocalFilePath("Videos", filename: self.url!.lastPathComponent!)
// let playerVC = MobilePlayerViewController(contentURL: videoUrl)
// playerVC.title = self.videoTitle
// playerVC.activityItems = [videoUrl]
// presentMoviePlayerViewControllerAnimated(playerVC)
}else{
if downloadQueue[self.fileHash] != nil{
print("Downloading for this file is in progress")
}else{
downloadQueue.setValue(self.downloadButton, forKey: self.fileHash)
Downloader(destdirname: "Videos").download(self.url!)
self.downloadButton.isEnabled = false
}
}
}
}
|
a1b50ed9a679029bcdcb8a32867be411
| 38.056497 | 273 | 0.59728 | false | false | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
Classes/Issues/DiffHunk/IssueDiffHunkPathCell.swift
|
mit
|
1
|
//
// IssueDiffHunkPathCell.swift
// Freetime
//
// Created by Ryan Nystrom on 7/3/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueDiffHunkPathCell: UICollectionViewCell, ListBindable {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = Styles.Colors.Gray.lighter.color
label.adjustsFontSizeToFitWidth = true
label.textColor = Styles.Colors.Gray.dark.color
label.font = Styles.Text.code.preferredFont
contentView.addSubview(label)
label.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.left.equalToSuperview()
make.width.lessThanOrEqualToSuperview().offset(-Styles.Sizes.rowSpacing)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentView()
}
// MARK: ListBindable
func bindViewModel(_ viewModel: Any) {
guard let viewModel = viewModel as? String else { return }
label.text = viewModel
}
}
|
483e28c11e6029f49a6b14080248893a
| 24.916667 | 84 | 0.662379 | false | false | false | false |
NemProject/NEMiOSApp
|
refs/heads/develop
|
NEMWallet/Models/BlockModel.swift
|
mit
|
1
|
//
// BlockModel.swift
//
// This file is covered by the LICENSE file in the root of this project.
// Copyright (c) 2016 NEM
//
import Foundation
import SwiftyJSON
/**
Represents a block on the NEM blockchain.
Visit the [documentation](http://bob.nem.ninja/docs/#harvestInfo)
for more information.
*/
public class Block: SwiftyJSONMappable {
// MARK: - Model Properties
/// The id of the block.
public var id: Int!
/// The height of the block.
public var height: Int!
/// The total fee collected by harvesting the block.
public var totalFee: Int!
/// The number of seconds elapsed since the creation of the nemesis block.
public var timeStamp: Int!
/// The block difficulty.
public var difficulty: Int!
// MARK: - Model Lifecycle
public required init?(jsonData: JSON) {
id = jsonData["id"].intValue
height = jsonData["height"].intValue
totalFee = jsonData["totalFee"].intValue
timeStamp = jsonData["timeStamp"].intValue
difficulty = jsonData["difficulty"].intValue
}
}
|
049f1d66b939a52fb22616f8c9719cb7
| 24.155556 | 78 | 0.634276 | false | false | false | false |
red-spotted-newts-2014/rest-less-ios
|
refs/heads/master
|
Rest Less/workoutClass.playground/section-1.swift
|
mit
|
1
|
import UIKit
class WorkoutLogger {
var userName: String
var workoutName: String
var reps = [String]()
var plannedTimes: [Int]
var actualTimes = [Double]()
var finalTime = Double()
var missedReps: Int {
get {
return reps.count - actualTimes.count
}
}
init(userName:String, workoutName:String, plannedTimes:[Int]) {
self.userName = userName
self.workoutName = workoutName
self.plannedTimes = plannedTimes
}
func addRestTime(val:Double) -> Double {
self.actualTimes.append(val)
return self.actualTimes.last!
}
func returnDictInfo() -> [String:String]{
return ["userName": self.userName,
"workoutName": self.workoutName,
"times": "\(self.actualTimes)",
"finalTime" : "\(self.finalTime)",
"missedReps" : "\(self.missedReps)"]
}
}
|
5bafcb397513592130c89723c569c125
| 19.041667 | 67 | 0.557173 | false | false | false | false |
CNKCQ/oschina
|
refs/heads/master
|
Pods/Foundation+/Foundation+/String+.swift
|
mit
|
1
|
//
// String+.swift
// Elegant
//
// Created by Steve on 2017/5/18.
// Copyright © 2017年 KingCQ. All rights reserved.
//
import Foundation
public extension String {
/// Returns floatValue
var float: Float? {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.floatValue
}
/// Returns doubleValue
var double: Double? {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.doubleValue
}
/// The string length property returns the count of character in the string.
var length: Int {
return characters.count
}
/// Returns a localized string, using the main bundle.
var locale: String {
return NSLocalizedString(self, tableName: "Default", bundle: Bundle.main, value: "", comment: "")
}
/// Returns a lowercase version of the string.
var lowercased: String {
return lowercased()
}
/// Returns an uppercase version of the string.
var uppercased: String {
return uppercased()
}
/// Returns a new string made from the receiver by replacing all characters not in the unreservedCharset with percent-encoded characters.
var encoding: String? {
let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
let unreservedCharset = CharacterSet(charactersIn: unreservedChars)
return addingPercentEncoding(withAllowedCharacters: unreservedCharset)
}
/// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
var decoding: String? {
return removingPercentEncoding
}
}
public extension String {
/// Accesses the element at the specified position. Support "abc"[-1] == "c"
///
/// - Parameter index: The position of the element to access.
subscript(index: Int) -> Character {
let idx = index < 0 ? (length - abs(index)) : index
return self[self.index(startIndex, offsetBy: idx)]
}
/// Accesses a contiguous subrange of the string's characters.
///
/// - Parameter range: A range of integers.
subscript(range: Range<Int>) -> String {
return substring(with: index(startIndex, offsetBy: range.lowerBound) ..< index(startIndex, offsetBy: range.upperBound))
}
/// Returns a new string made by removing from both ends of the String characters contained in a given character set.
///
/// - Parameter set: Character set, default is .whitespaces.
/// - Returns: A new string
func trimmed(set: CharacterSet = .whitespaces) -> String {
return trimmingCharacters(in: set)
}
/// Returns a new camelCaseString
///
/// - Parameter separator: A specail character
/// - Returns: camelCaseString
func camelCaseString(separator: String = "_") -> String {
if isEmpty {
return self
}
let first = self[0]
var rest = capitalized.replacingOccurrences(of: separator, with: "")
rest.remove(at: startIndex)
return "\(first)\(rest)"
}
}
|
1e57a3c0b807af4846aa8d4fbf0c60f2
| 31.739583 | 141 | 0.657334 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
refs/heads/master
|
Foundation/NSDecimalNumber.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/*************** Exceptions ***********/
public struct NSExceptionName : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension NSExceptionName {
public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException")
public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException")
public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException")
public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException")
}
/*************** Rounding and Exception behavior ***********/
// Rounding policies :
// Original
// value 1.2 1.21 1.25 1.35 1.27
// Plain 1.2 1.2 1.3 1.4 1.3
// Down 1.2 1.2 1.2 1.3 1.2
// Up 1.2 1.3 1.3 1.4 1.3
// Bankers 1.2 1.2 1.2 1.4 1.3
/*************** Type definitions ***********/
extension NSDecimalNumber {
public enum RoundingMode : UInt {
case plain // Round up on a tie
case down // Always down == truncate
case up // Always up
case bankers // on a tie round so last digit is even
}
public enum CalculationError : UInt {
case noError
case lossOfPrecision // Result lost precision
case underflow // Result became 0
case overflow // Result exceeds possible representation
case divideByZero
}
}
public protocol NSDecimalNumberBehaviors {
func roundingMode() -> NSDecimalNumber.RoundingMode
func scale() -> Int16
}
// Receiver can raise, return a new value, or return nil to ignore the exception.
fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) {
// handle the error condition, such as throwing an error for over/underflow
}
/*************** NSDecimalNumber: the class ***********/
open class NSDecimalNumber : NSNumber {
fileprivate let decimal: Decimal
public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) {
var d = Decimal(mantissa)
d._exponent += Int32(exponent)
d._isNegative = isNegative ? 1 : 0
self.init(decimal: d)
}
public init(decimal dcm: Decimal) {
self.decimal = dcm
super.init()
}
public convenience init(string numberValue: String?) {
self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan)
}
public convenience init(string numberValue: String?, locale: Any?) {
self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan)
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent")
let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length"))
let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0)
let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0)
// let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo"))
guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else {
return nil // raise "Critical NSDecimalNumber archived data is missing"
}
guard mantissaData.count == Int(NSDecimalMaxSize * 2) else {
return nil // raise "Critical NSDecimalNumber archived data is wrong size"
}
// Byte order?
let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = (
UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]),
UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]),
UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]),
UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]),
UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]),
UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]),
UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]),
UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15])
)
self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa)
super.init()
}
public init(value: Int) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt) {
decimal = Decimal(value)
super.init()
}
public init(value: Int8) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt8) {
decimal = Decimal(value)
super.init()
}
public init(value: Int16) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt16) {
decimal = Decimal(value)
super.init()
}
public init(value: Int32) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt32) {
decimal = Decimal(value)
super.init()
}
public init(value: Int64) {
decimal = Decimal(value)
super.init()
}
public init(value: UInt64) {
decimal = Decimal(value)
super.init()
}
public init(value: Bool) {
decimal = Decimal(value ? 1 : 0)
super.init()
}
public init(value: Float) {
decimal = Decimal(Double(value))
super.init()
}
public init(value: Double) {
decimal = Decimal(value)
super.init()
}
public required convenience init(floatLiteral value: Double) {
self.init(decimal:Decimal(value))
}
public required convenience init(booleanLiteral value: Bool) {
if value {
self.init(integerLiteral: 1)
} else {
self.init(integerLiteral: 0)
}
}
public required convenience init(integerLiteral value: Int) {
self.init(decimal:Decimal(value))
}
public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) {
NSRequiresConcreteImplementation()
}
open override var description: String {
return self.decimal.description
}
open override func description(withLocale locale: Locale?) -> String {
guard locale == nil else {
fatalError("Locale not supported: \(locale!)")
}
return self.decimal.description
}
open class var zero: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 0)
}
open class var one: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 1)
}
open class var minimum: NSDecimalNumber {
return NSDecimalNumber(decimal:Decimal.leastFiniteMagnitude)
}
open class var maximum: NSDecimalNumber {
return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude)
}
open class var notANumber: NSDecimalNumber {
return NSDecimalNumber(decimal: Decimal.nan)
}
open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber {
return adding(other, withBehavior: nil)
}
open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalAdd(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber {
return subtracting(other, withBehavior: nil)
}
open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalSubtract(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber {
return multiplying(by: other, withBehavior: nil)
}
open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalMultiply(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber {
return dividing(by: other, withBehavior: nil)
}
open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalDivide(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func raising(toPower power: Int) -> NSDecimalNumber {
return raising(toPower:power, withBehavior: nil)
}
open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalPower(&result, &input, power, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber {
return multiplying(byPowerOf10: power, withBehavior: nil)
}
open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalPower(&result, &input, Int(power), roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
// Round to the scale of the behavior.
open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let scale = behavior.scale()
NSDecimalRound(&result, &input, Int(scale), roundingMode)
return NSDecimalNumber(decimal: result)
}
// compare two NSDecimalNumbers
open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult {
if let num = decimalNumber as? NSDecimalNumber {
return decimal.compare(to:num.decimal)
} else {
return decimal.compare(to:Decimal(decimalNumber.doubleValue))
}
}
open class var defaultBehavior: NSDecimalNumberBehaviors {
return NSDecimalNumberHandler.defaultBehavior
}
// One behavior per thread - The default behavior is
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException
// raise on overflow, underflow and divide by zero.
static let OBJC_TYPE = "d".utf8CString
open override var objCType: UnsafePointer<Int8> {
return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! }
}
// return 'd' for double
open override var int8Value: Int8 {
return Int8(exactly: decimal.doubleValue) ?? 0 as Int8
}
open override var uint8Value: UInt8 {
return UInt8(exactly: decimal.doubleValue) ?? 0 as UInt8
}
open override var int16Value: Int16 {
return Int16(exactly: decimal.doubleValue) ?? 0 as Int16
}
open override var uint16Value: UInt16 {
return UInt16(exactly: decimal.doubleValue) ?? 0 as UInt16
}
open override var int32Value: Int32 {
return Int32(exactly: decimal.doubleValue) ?? 0 as Int32
}
open override var uint32Value: UInt32 {
return UInt32(exactly: decimal.doubleValue) ?? 0 as UInt32
}
open override var int64Value: Int64 {
return Int64(exactly: decimal.doubleValue) ?? 0 as Int64
}
open override var uint64Value: UInt64 {
return UInt64(exactly: decimal.doubleValue) ?? 0 as UInt64
}
open override var floatValue: Float {
return Float(decimal.doubleValue)
}
open override var doubleValue: Double {
return decimal.doubleValue
}
open override var boolValue: Bool {
return !decimal.isZero
}
open override var intValue: Int {
return Int(exactly: decimal.doubleValue) ?? 0 as Int
}
open override var uintValue: UInt {
return UInt(exactly: decimal.doubleValue) ?? 0 as UInt
}
open override func isEqual(_ value: Any?) -> Bool {
guard let other = value as? NSDecimalNumber else { return false }
return self.decimal == other.decimal
}
override var _swiftValueOfOptimalType: Any {
return decimal
}
}
// return an approximate double value
/*********** A class for defining common behaviors *******/
open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding {
static let defaultBehavior = NSDecimalNumberHandler()
let _roundingMode: NSDecimalNumber.RoundingMode
let _scale:Int16
let _raiseOnExactness: Bool
let _raiseOnOverflow: Bool
let _raiseOnUnderflow: Bool
let _raiseOnDivideByZero: Bool
public override init() {
_roundingMode = .plain
_scale = Int16(NSDecimalNoScale)
_raiseOnExactness = false
_raiseOnOverflow = true
_raiseOnUnderflow = true
_raiseOnDivideByZero = true
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
_roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))!
if coder.containsValue(forKey: "NS.scale") {
_scale = Int16(coder.decodeInteger(forKey: "NS.scale"))
} else {
_scale = Int16(NSDecimalNoScale)
}
_raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness")
_raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow")
_raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow")
_raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero")
}
open func encode(with coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if _roundingMode != .plain {
coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode")
}
if _scale != Int16(NSDecimalNoScale) {
coder.encode(_scale, forKey:"NS.scale")
}
if _raiseOnExactness {
coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness")
}
if _raiseOnOverflow {
coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow")
}
if _raiseOnUnderflow {
coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow")
}
if _raiseOnDivideByZero {
coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero")
}
}
open class var `default`: NSDecimalNumberHandler {
return defaultBehavior
}
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException (return nil)
// raise on overflow, underflow and divide by zero.
public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) {
_roundingMode = roundingMode
_scale = scale
_raiseOnExactness = exact
_raiseOnOverflow = overflow
_raiseOnUnderflow = underflow
_raiseOnDivideByZero = divideByZero
}
open func roundingMode() -> NSDecimalNumber.RoundingMode {
return _roundingMode
}
// The scale could return NoScale for no defined scale.
open func scale() -> Int16 {
return _scale
}
}
extension NSNumber {
public var decimalValue: Decimal {
if let d = self as? NSDecimalNumber {
return d.decimal
} else {
return Decimal(self.doubleValue)
}
}
}
|
775fd11cfbcf4d25ac7954cf7f3f2ca4
| 34.288499 | 211 | 0.644865 | false | false | false | false |
soapyigu/LeetCode_Swift
|
refs/heads/master
|
DFS/SubsetsII.swift
|
mit
|
1
|
/**
* Question Link: https://leetcode.com/problems/subsets-ii/
* Primary idea: Classic Depth-first Search, avoid duplicates by adopting the first occurrence
*
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/
class SubsetsII {
func subsetsWithDup(nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = nums.sorted(by: <)
_dfs(&res, &path, nums, 0)
return res
}
private func _dfs(inout res: [[Int]], inout _ path:[Int], _ nums: [Int], _ index: Int) {
res.append(Array(path))
for i in index..<nums.count {
if i > 0 && nums[i] == nums[i - 1] && i != index {
continue
}
path.append(nums[i])
_dfs(&res, &path, nums, i + 1)
path.removeLast()
}
}
}
|
7f7894dd3f1735f831764a99e26efb4d
| 25.058824 | 94 | 0.479096 | false | false | false | false |
iSapozhnik/FamilyPocket
|
refs/heads/master
|
FamilyPocket/Data/CategoryManager/CategoryManager.swift
|
mit
|
1
|
//
// CategoryManager.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/14/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import Foundation
import RealmSwift
class CategoryManager: Persistable {
typealias ObjectClass = Category
func allObjects(withCompletion completion: @escaping ([Category]?) -> ()) {
let realm = try! Realm()
let dataImporter = RealmDataImporter()
if !dataImporter.initialDataImported() {
dataImporter.importCategories()
}
let categories = realm.objects(Category.self).sorted(byKeyPath: "popularity", ascending: false)
completion(Array(categories))
}
func canAdd(object: Object) -> Bool {
if let category = object as? Category {
let realm = try! Realm()
let predicate = NSPredicate(format: "name = %@", category.name!)
let categories = realm.objects(Category.self).filter(predicate)
return categories.count == 0
} else {
return true
}
}
func add(object: Object) {
let realm = try! Realm()
try! realm.write {
realm.add(object)
}
}
func delete(object: Object) {
let realm = try! Realm()
try! realm.write {
realm.delete(object)
}
}
func update(object: Category, name: String, colorString: String) {
let realm = try! Realm()
try! realm.write {
object.name = name
object.color = colorString
realm.add(object, update: true)
}
}
}
class IncomeCategoryManager: Persistable {
typealias ObjectClass = IncomeCategory
func allObjects(withCompletion completion: @escaping ([IncomeCategory]?) -> ()) {
let realm = try! Realm()
let dataImporter = RealmDataImporter()
if !dataImporter.initialDataImported() {
dataImporter.importCategories()
}
let categories = realm.objects(IncomeCategory.self).sorted(byKeyPath: "popularity", ascending: false)
completion(Array(categories))
}
func add(object: Object) {
}
func delete(object: Object) {
}
}
|
0370e4a23a7f4e74bb13298237fe5954
| 23.947368 | 109 | 0.557384 | false | false | false | false |
remirobert/TextDrawer
|
refs/heads/master
|
Source/TextEditView.swift
|
mit
|
1
|
//
// TextEditView.swift
//
//
// Created by Remi Robert on 11/07/15.
//
//
import UIKit
import Masonry
protocol TextEditViewDelegate {
func textEditViewFinishedEditing(text: String)
}
public class TextEditView: UIView {
private var textView: UITextView!
private var textContainer: UIView!
var delegate: TextEditViewDelegate?
var textSize: Int! = 42
var textEntry: String! {
set {
textView.text = newValue
}
get {
return textView.text
}
}
var isEditing: Bool! {
didSet {
if isEditing == true {
textContainer.hidden = false;
userInteractionEnabled = true;
backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.65)
textView.becomeFirstResponder()
}
else {
backgroundColor = UIColor.clearColor()
textView.resignFirstResponder()
textContainer.hidden = true;
userInteractionEnabled = false;
delegate?.textEditViewFinishedEditing(textView.text)
}
}
}
init() {
super.init(frame: CGRectZero)
isEditing = false
textContainer = UIView()
textContainer.layer.masksToBounds = true
addSubview(textContainer)
textContainer.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in
make.edges.equalTo()(self)
}
textView = UITextView()
textView.tintColor = UIColor.whiteColor()
textView.font = UIFont.systemFontOfSize(44)
textView.textColor = UIColor.whiteColor()
textView.backgroundColor = UIColor.clearColor()
textView.returnKeyType = UIReturnKeyType.Done
textView.clipsToBounds = true
textView.delegate = self
textContainer.addSubview(textView)
textView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in
make.edges.equalTo()(self.textContainer)
}
textContainer.hidden = true
userInteractionEnabled = false
keyboardNotification()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
extension TextEditView: UITextViewDelegate {
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
isEditing = false
return false
}
if textView.text.characters.count + text.characters.count > textSize {
return false
}
return true
}
}
extension TextEditView {
func keyboardNotification() {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) { (notification: NSNotification!) -> Void in
if let userInfo = notification.userInfo {
self.textContainer.layer.removeAllAnimations()
if let keyboardRectEnd = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue(),
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.floatValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.textContainer.mas_updateConstraints({ (make: MASConstraintMaker!) -> Void in
make.bottom.offset()(-CGRectGetHeight(keyboardRectEnd))
})
UIView.animateWithDuration(NSTimeInterval(duration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
self.textContainer.layoutIfNeeded()
}, completion: nil)
})
}
}
}
}
}
|
78342ee7d8fc483635c13768814cb118
| 31.244094 | 173 | 0.582662 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/ViewRelated/Site Creation/Final Assembly/LandInTheEditorHelper.swift
|
gpl-2.0
|
1
|
typealias HomepageEditorCompletion = () -> Void
class LandInTheEditorHelper {
/// Land in the editor, or continue as usual - Used to branch on the feature flag for landing in the editor from the site creation flow
/// - Parameter blog: Blog (which was just created) for which to show the home page editor
/// - Parameter navigationController: UINavigationController used to present the home page editor
/// - Parameter completion: HomepageEditorCompletion callback to be invoked after the user finishes editing the home page, or immediately iwhen the feature flag is disabled
static func landInTheEditorOrContinue(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) {
// branch here for feature flag
if FeatureFlag.landInTheEditor.enabled {
landInTheEditor(for: blog, navigationController: navigationController, completion: completion)
} else {
completion()
}
}
private static func landInTheEditor(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) {
fetchAllPages(for: blog, success: { _ in
DispatchQueue.main.async {
if let homepage = blog.homepage {
let editorViewController = EditPageViewController(homepage: homepage, completion: completion)
navigationController.present(editorViewController, animated: false)
WPAnalytics.track(.landingEditorShown)
}
}
}, failure: { _ in
NSLog("Fetching all pages failed after site creation!")
})
}
// This seems to be necessary before casting `AbstractPost` to `Page`.
private static func fetchAllPages(for blog: Blog, success: @escaping PostServiceSyncSuccess, failure: @escaping PostServiceSyncFailure) {
let options = PostServiceSyncOptions()
options.number = 20
let context = ContextManager.sharedInstance().mainContext
let postService = PostService(managedObjectContext: context)
postService.syncPosts(ofType: .page, with: options, for: blog, success: success, failure: failure)
}
}
|
7272418a1870454783117df21e151827
| 56.461538 | 176 | 0.698349 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS
|
refs/heads/master
|
TruckMuncher/LoginViewController.swift
|
gpl-2.0
|
1
|
//
// LoginViewController.swift
// TruckMuncher
//
// Created by Josh Ault on 9/18/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Alamofire
import TwitterKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
@IBOutlet var fbLoginView: FBSDKLoginButton!
@IBOutlet weak var btnTwitterLogin: TWTRLogInButton!
var twitterKey: String = ""
var twitterSecretKey: String = ""
var twitterName: String = ""
var twitterCallback: String = ""
let authManager = AuthManager()
let truckManager = TrucksManager()
override func viewDidLoad() {
super.viewDidLoad()
btnTwitterLogin.logInCompletion = { (session: TWTRSession!, error: NSError!) in
if error == nil {
#if DEBUG
self.loginToAPI("oauth_token=tw985c9758-e11b-4d02-9b39-98aa8d00d429, oauth_secret=munch")
#elseif RELEASE
self.loginToAPI("oauth_token=\(session.authToken), oauth_secret=\(session.authTokenSecret)")
#endif
} else {
let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelTapped")
fbLoginView.delegate = self
fbLoginView.readPermissions = ["public_profile", "email", "user_friends"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginTapped(sender: AnyObject) {
MBProgressHUD.showHUDAddedTo(view, animated: true)
}
func cancelTapped() {
dismissViewControllerAnimated(true, completion: nil)
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if error == nil && !result.isCancelled {
#if DEBUG
loginToAPI("access_token=fb985c9758-e11b-4d02-9b39|FBUser")
#elseif RELEASE
loginToAPI("access_token=\(FBSDKAccessToken.currentAccessToken().tokenString)")
#endif
} else {
let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
MBProgressHUD.hideHUDForView(view, animated: true)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
println("User logged out from Facebook")
MBProgressHUD.hideHUDForView(view, animated: true)
}
func successfullyLoggedInAsTruck() {
MBProgressHUD.hideHUDForView(view, animated: true)
navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("loggedInNotification", object: self, userInfo: nil)
})
}
func attemptSessionTokenRefresh(error: (Error?) -> ()) {
truckManager.getTrucksForVendor(success: { (response) -> () in
self.successfullyLoggedInAsTruck()
}, error: error)
}
func loginToAPI(authorizationHeader: String) {
authManager.signIn(authorization: authorizationHeader, success: { (response) -> () in
NSUserDefaults.standardUserDefaults().setValue(response.sessionToken, forKey: "sessionToken")
NSUserDefaults.standardUserDefaults().synchronize()
self.attemptSessionTokenRefresh({ (error) -> () in
MBProgressHUD.hideHUDForView(self.view, animated: true)
let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
println("error \(error)")
println("error message \(error?.userMessage)")
})
}) { (error) -> () in
println("error \(error)")
println("error message \(error?.userMessage)")
let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
NSUserDefaults.standardUserDefaults().removeObjectForKey("sessionToken")
NSUserDefaults.standardUserDefaults().synchronize()
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
}
|
f99062578f9d7ebd2aea80587fb722fb
| 43.806723 | 148 | 0.64066 | false | false | false | false |
SwiftyVK/SwiftyVK
|
refs/heads/master
|
Library/Sources/Networking/Attempt/Attempt.swift
|
mit
|
2
|
import Foundation
protocol Attempt: class, OperationConvertible {
init(
request: URLRequest,
session: VKURLSession,
callbacks: AttemptCallbacks
)
}
final class AttemptImpl: Operation, Attempt {
private let request: URLRequest
private var task: VKURLSessionTask?
private let urlSession: VKURLSession
private let callbacks: AttemptCallbacks
init(
request: URLRequest,
session: VKURLSession,
callbacks: AttemptCallbacks
) {
self.request = request
self.urlSession = session
self.callbacks = callbacks
super.init()
}
override func main() {
let semaphore = DispatchSemaphore(value: 0)
let completion: (Data?, URLResponse?, Error?) -> () = { [weak self] data, response, error in
/// Because URLSession executes completions in their own serial queue
DispatchQueue.global(qos: .utility).async {
defer {
semaphore.signal()
}
guard let strongSelf = self, !strongSelf.isCancelled else { return }
if let error = error as NSError?, error.code != NSURLErrorCancelled {
strongSelf.callbacks.onFinish(.error(.urlRequestError(error)))
}
else if let data = data {
strongSelf.callbacks.onFinish(Response(data))
}
else {
strongSelf.callbacks.onFinish(.error(.unexpectedResponse))
}
}
}
task = urlSession.dataTask(with: request, completionHandler: completion)
task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived), options: .new, context: nil)
task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent), options: .new, context: nil)
task?.resume()
semaphore.wait()
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
guard let keyPath = keyPath else { return }
guard let task = task else { return }
switch keyPath {
case (#keyPath(URLSessionTask.countOfBytesSent)):
guard task.countOfBytesExpectedToSend > 0 else { return }
callbacks.onSent(task.countOfBytesSent, task.countOfBytesExpectedToSend)
case(#keyPath(URLSessionTask.countOfBytesReceived)):
guard task.countOfBytesExpectedToReceive > 0 else { return }
callbacks.onRecive(task.countOfBytesReceived, task.countOfBytesExpectedToReceive)
default:
break
}
}
override func cancel() {
super.cancel()
task?.cancel()
}
deinit {
task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived))
task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent))
}
}
struct AttemptCallbacks {
let onFinish: (Response) -> ()
let onSent: (_ total: Int64, _ of: Int64) -> ()
let onRecive: (_ total: Int64, _ of: Int64) -> ()
init(
onFinish: @escaping ((Response) -> ()) = { _ in },
onSent: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in },
onRecive: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in }
) {
self.onFinish = onFinish
self.onSent = onSent
self.onRecive = onRecive
}
static var `default`: AttemptCallbacks {
return AttemptCallbacks()
}
}
|
58b4dc1932718fa8f814a083f9404e51
| 32.603604 | 119 | 0.582842 | false | false | false | false |
BlenderSleuth/Circles
|
refs/heads/master
|
Circles/SKTUtils/SKAction+SpecialEffects.swift
|
gpl-3.0
|
1
|
/*
* Copyright (c) 2013-2014 Razeware LLC
*
* 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 SpriteKit
public extension SKAction {
/**
* Creates a screen shake animation.
*
* @param node The node to shake. You cannot apply this effect to an SKScene.
* @param amount The vector by which the node is displaced.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenShakeWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldPosition = node.position
let newPosition = oldPosition + amount
let effect = SKTMoveEffect(node: node, duration: duration, startPosition: newPosition, endPosition: oldPosition)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Creates a screen rotation animation.
*
* @param node You usually want to apply this effect to a pivot node that is
* centered in the scene. You cannot apply the effect to an SKScene.
* @param angle The angle in radians.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenRotateWithNode(_ node: SKNode, angle: CGFloat, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldAngle = node.zRotation
let newAngle = oldAngle + angle
let effect = SKTRotateEffect(node: node, duration: duration, startAngle: newAngle, endAngle: oldAngle)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Creates a screen zoom animation.
*
* @param node You usually want to apply this effect to a pivot node that is
* centered in the scene. You cannot apply the effect to an SKScene.
* @param amount How much to scale the node in the X and Y directions.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenZoomWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldScale = CGPoint(x: node.xScale, y: node.yScale)
let newScale = oldScale * amount
let effect = SKTScaleEffect(node: node, duration: duration, startScale: newScale, endScale: oldScale)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Causes the scene background to flash for duration seconds.
*/
public class func colorGlitchWithScene(_ scene: SKScene, originalColor: SKColor, duration: TimeInterval) -> SKAction {
return SKAction.customAction(withDuration: duration) {(node, elapsedTime) in
if elapsedTime < CGFloat(duration) {
let random = Int.random(0..<256)
scene.backgroundColor = SKColorWithRGB(random, g: random, b: random)
} else {
scene.backgroundColor = originalColor
}
}
}
}
|
d8b8f9ac85a71e61187887b7a33b8ee5
| 42.915789 | 129 | 0.72675 | false | false | false | false |
kaler/SmartRouter
|
refs/heads/master
|
SmartRouterTests/RouterTests.swift
|
mit
|
1
|
//
// RouterTests.swift
// RouterTests
//
// Created by Parveen Kaler on 9/7/15.
// Copyright © 2015 Smartful Studios Inc. All rights reserved.
//
import XCTest
@testable import Router
class RouterTests: XCTestCase {
var router: Router?
override func setUp() {
super.setUp()
router = Router()
}
func testBase() {
let expectation = expectationWithDescription("Plain")
router?.route("/foo") { _ in
expectation.fulfill()
}
router?.route("/bar") { _ in
XCTAssert(false, "Should not match bar")
}
let url = NSURL(string: "/foo")!
router?.match(url)
waitForExpectationsWithTimeout(0.001) { (error) -> Void in
print(error)
}
}
func testURLParameter() {
let expectation = expectationWithDescription("URL Parameters")
router?.route("/foo/:id") { (urlParams, queryParams) in
XCTAssert(urlParams.first?.name == ":id")
XCTAssert(urlParams.first?.value == "1234")
expectation.fulfill()
}
let url = NSURL(string: "/foo/1234")!
router?.match(url)
waitForExpectationsWithTimeout(0.001) { (error) -> Void in
print(error)
}
}
func testParameters() {
let e = expectationWithDescription("Parameter expectation")
router?.route("/foo") { (urlParams, queryParams) in
XCTAssert(queryParams.first?.name == "param")
XCTAssert(queryParams.first?.value == "12345")
e.fulfill()
}
let url = NSURL(string: "/foo?param=12345")!
router?.match(url)
waitForExpectationsWithTimeout(0.001) { (error) -> Void in
print(error)
}
}
}
|
e0fbab3b057b0398d60697470119c31f
| 25.5 | 70 | 0.54124 | false | true | false | false |
akaralar/siesta
|
refs/heads/master
|
Examples/GithubBrowser/Source/UI/SiestaTheme.swift
|
mit
|
1
|
import UIKit
import Siesta
enum SiestaTheme {
static let
darkColor = UIColor(red: 0.180, green: 0.235, blue: 0.266, alpha: 1),
darkerColor = UIColor(red: 0.161, green: 0.208, blue: 0.235, alpha: 1),
lightColor = UIColor(red: 0.964, green: 0.721, blue: 0.329, alpha: 1),
linkColor = UIColor(red: 0.321, green: 0.901, blue: 0.882, alpha: 1),
selectedColor = UIColor(red: 0.937, green: 0.400, blue: 0.227, alpha: 1),
textColor = UIColor(red: 0.623, green: 0.647, blue: 0.663, alpha: 1),
boldColor = UIColor(red: 0.906, green: 0.902, blue: 0.894, alpha: 1)
static func applyAppearanceDefaults() {
UITextField.appearance().keyboardAppearance = .dark
UITextField.appearance().textColor = UIColor.black
UITextField.appearance().backgroundColor = textColor
UINavigationBar.appearance().barStyle = UIBarStyle.black
UINavigationBar.appearance().barTintColor = darkColor
UINavigationBar.appearance().tintColor = linkColor
UITableView.appearance().backgroundColor = darkerColor
UITableView.appearance().separatorColor = UIColor.black
UITableViewCell.appearance().backgroundColor = darkerColor
UITableViewCell.appearance().selectedBackgroundView = emptyView(withBackground: selectedColor)
UIButton.appearance().backgroundColor = darkColor
UIButton.appearance().tintColor = linkColor
UISearchBar.appearance().backgroundColor = darkColor
UISearchBar.appearance().barTintColor = darkColor
UISearchBar.appearance().searchBarStyle = .minimal
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = lightColor
UILabel.appearance(whenContainedInInstancesOf: [ResourceStatusOverlay.self]).textColor = textColor
UIActivityIndicatorView.appearance(whenContainedInInstancesOf: [ResourceStatusOverlay.self]).activityIndicatorViewStyle = .whiteLarge
}
static private func emptyView(withBackground color: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = color
return view
}
}
|
7f99a64d20dff878e9646ea51ee2a75e
| 47.088889 | 141 | 0.694547 | false | false | false | false |
wdkk/CAIM
|
refs/heads/master
|
AR/caimar00/CAIMMetal/CAIMMetal.swift
|
mit
|
15
|
//
// CAIMMetal.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
#if os(macOS) || (os(iOS) && !arch(x86_64))
import Foundation
import Metal
open class CAIMMetal
{
public static var device:MTLDevice? = MTLCreateSystemDefaultDevice()
private static var _command_queue:MTLCommandQueue?
public static var commandQueue:MTLCommandQueue? {
if( CAIMMetal._command_queue == nil ) { CAIMMetal._command_queue = device?.makeCommandQueue() }
return CAIMMetal._command_queue
}
// セマフォ
public static let semaphore = DispatchSemaphore( value: 0 )
// コマンド実行
public static func execute( prev:( _ commandBuffer:MTLCommandBuffer )->() = { _ in },
main:( _ commandBuffer:MTLCommandBuffer )->(),
post:( _ commandBuffer:MTLCommandBuffer )->() = { _ in },
completion: (( _ commandBuffer:MTLCommandBuffer )->())? = nil ) {
// 描画コマンドエンコーダ
guard let command_buffer:MTLCommandBuffer = CAIMMetal.commandQueue?.makeCommandBuffer() else {
print("cannot get Metal command buffer.")
return
}
// 完了時の処理
command_buffer.addCompletedHandler { _ in
CAIMMetal.semaphore.signal()
completion?( command_buffer )
}
// 事前処理の実行(コンピュートシェーダなどで使える)
prev( command_buffer )
main( command_buffer )
// コマンドバッファの確定
command_buffer.commit()
// セマフォ待機のチェック
_ = CAIMMetal.semaphore.wait( timeout: DispatchTime.distantFuture )
// 事後処理の関数の実行(command_buffer.waitUntilCompletedの呼び出しなど)
post( command_buffer )
}
}
#endif
|
0f7338cbb3130011152c0bd317c79682
| 30 | 103 | 0.592092 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
refs/heads/master
|
SmartReceipts/Persistence/Helpers/RefreshTripPriceHandler.swift
|
agpl-3.0
|
2
|
//
// RefreshTripPriceHandler.swift
// SmartReceipts
//
// Created by Jaanus Siim on 01/06/16.
// Copyright © 2016 Will Baumann. All rights reserved.
//
import Foundation
import FMDB
protocol RefreshTripPriceHandler {
func refreshPriceForTrip(_ trip: WBTrip, inDatabase database: FMDatabase);
}
extension RefreshTripPriceHandler {
func refreshPriceForTrip(_ trip: WBTrip, inDatabase database: FMDatabase) {
Logger.debug("Refresh price on \(trip.name!)")
timeMeasured("Price update") {
//TODO jaanus: maybe lighter query - only price/currency/exchangeRate?
let receipts = database.fetchUnmarkedForDeletionReceiptsForTrip(trip)
let distances: [Distance]
if WBPreferences.isTheDistancePriceBeIncludedInReports() {
//lighter query also here?
distances = database.fetchAllDistancesForTrip(trip)
} else {
distances = []
}
let collection = PricesCollection()
// just so that when no receipts we would not end up with blank price
collection.addPrice(Price(amount: .zero, currency: trip.defaultCurrency))
for receipt in receipts {
collection.addPrice(receipt.targetPrice())
}
for distance in distances {
collection.addPrice(distance.totalRate())
}
trip.pricesSummary = collection
}
}
}
|
0d726195c242b592de0c3ff5f375ef1d
| 34.261905 | 85 | 0.625253 | false | false | false | false |
JasonChen2015/Paradise-Lost
|
refs/heads/master
|
Paradise Lost/Classes/DataStructures/Color.swift
|
mit
|
3
|
//
// Color.swift
// Paradise Lost
//
// Created by Jason Chen on 5/17/16.
// Copyright © 2016 Jason Chen. All rights reserved.
//
import Foundation
import UIKit
struct Color {
// refer: https://en.wikipedia.org/wiki/Beige
var FrechBeige = UIColor(hex: 0xa67b5b)
var CosmicLatte = UIColor(hex: 0xfff8e7)
// japanese tradictional color
// refer: https://en.wikipedia.org/wiki/Traditional_colors_of_Japan
var Kokiake = UIColor(hex: 0x7b3b3a)
var Kurotobi = UIColor(hex: 0x351e1c)
var Kakitsubata = UIColor(hex: 0x491e3c)
// refer: https://github.com/gabrielecirulli/2048 (under License MIT)
// for 2048 tile color
var TileBackground = UIColor(hex: 0x8F7a66)
var TileColor = UIColor(hex: 0xeee4da)
var TileGoldColor = UIColor(hex: 0xedc22e)
var DarkGrayishOrange = UIColor(hex: 0x776e65) // dark text color
var LightGrayishOrange = UIColor(hex: 0xf9f6f2) // light text color
// for 2048 special tile color
var BrightOrange = UIColor(hex: 0xf78e48) // 8
var BrightRed = UIColor(hex: 0xfc5e2e) // 16
var VividRed = UIColor(hex: 0xff3333) // 32
var PureRed = UIColor(hex: 0xff0000) // 64
//
var LightGray = UIColor(hex: 0xcccccc)
func mixColorBetween(_ colorA: UIColor, weightA: CGFloat = 0.5, colorB: UIColor, weightB: CGFloat = 0.5) -> UIColor {
let c1 = colorA.RGBComponents
let c2 = colorB.RGBComponents
let red = (c1.red * weightA + c2.red * weightB) / (weightA + weightB)
let green = (c1.green * weightA + c2.green * weightB) / (weightA + weightB)
let blue = (c1.blue * weightA + c2.blue * weightB) / (weightA + weightB)
let alpha = (c1.alpha * weightA + c2.alpha * weightB) / (weightA + weightB)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
extension UIColor {
var RGBComponents:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
// refer: https://github.com/yannickl/DynamicColor (under License MIT)
// create a color from hex number (e.g. UIColor(hex: 0xaabbcc))
convenience init(hex: UInt32) {
let mask = 0x000000FF
let r = Int(hex >> 16) & mask
let g = Int(hex >> 8) & mask
let b = Int(hex >> 0) & mask
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
|
66eb05411546a411233a05e650a1d9d6
| 34.342105 | 121 | 0.612435 | false | false | false | false |
YauheniYarotski/APOD
|
refs/heads/master
|
APOD/ApodDescriptionVC.swift
|
mit
|
1
|
//
// ApodDescriptionVC.swift
// APOD
//
// Created by Yauheni Yarotski on 25.04.16.
// Copyright © 2016 Yauheni_Yarotski. All rights reserved.
//
import UIKit
protocol ApodDescriptionVCDelegate {
func apodDescriptionVCDidFinsh(_ apodDescriptionVC: ApodDescriptionVC?)
func apodDescriptionVCDidFinshByDateBarPressed(_ apodDescriptionVC: ApodDescriptionVC)
}
class ApodDescriptionVC: UIViewController {
var apodDateString: String!
var apodTitle: String!
var apodDescription: String!
let apodDateBar = TopBar()
let titleView = ApodTitleView(frame: CGRect(x:0, y:0, width:0, height:60))
let apodDescriptionTextView = UITextView()
var delegate: ApodDescriptionVCDelegate?
var swipeDismiser = SwipeDismiser()
// MARK: - UIViewController
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
apodDateBar.translatesAutoresizingMaskIntoConstraints = false
apodDateBar.backgroundColor = UIColor.clear
view.addSubview(apodDateBar)
apodDateBar.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(20)
make.leading.trailing.equalToSuperview()
make.height.equalTo(60)
}
titleView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(titleView)
titleView.title.text = apodTitle
titleView.snp.makeConstraints { (make) in
make.height.equalTo(60)
make.leading.trailing.equalToSuperview()
make.top.equalTo(apodDateBar.snp.bottom)
}
apodDescriptionTextView.translatesAutoresizingMaskIntoConstraints = false
apodDescriptionTextView.backgroundColor = UIColor.clear
apodDescriptionTextView.textColor = UIColor.white
view.addSubview(apodDescriptionTextView)
apodDescriptionTextView.text = apodDescription
apodDescriptionTextView.isEditable = false
apodDescriptionTextView.snp.makeConstraints { (make) in
make.leading.equalToSuperview().offset(20)
make.trailing.equalToSuperview().offset(-20)
make.bottom.equalToSuperview()
make.top.equalTo(titleView.snp.bottom)
}
setupDateHandler()
setupViewHandler()
setupSwipeHandler()
}
func controllerIsDone() {
delegate?.apodDescriptionVCDidFinsh(self)
}
//MARK: - Setup
func setupViewHandler() {
let tap = UITapGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.viewPressed(_:)))
tap.numberOfTapsRequired = 1
view.addGestureRecognizer(tap)
}
func setupDateHandler() {
let tap = UITapGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.datePressed(_:)))
tap.numberOfTapsRequired = 1
apodDateBar.addGestureRecognizer(tap)
}
func setupSwipeHandler() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(ApodDescriptionVC.didPan(_:)))
view.addGestureRecognizer(pan)
}
//MARK: - ActionHandlers
func viewPressed(_ tap: UITapGestureRecognizer) {
controllerIsDone()
}
func datePressed(_ tap: UITapGestureRecognizer) {
delegate?.apodDescriptionVCDidFinshByDateBarPressed(self)
}
func didPan(_ pan: UIPanGestureRecognizer) {
switch pan.state {
case .began:
swipeDismiser.interactionInProgress = true
controllerIsDone()
default:
swipeDismiser.handlePan(pan)
}
}
}
|
a7a68778425349100686c8c1695d6e70
| 28.822034 | 108 | 0.703041 | false | false | false | false |
mercadopago/px-ios
|
refs/heads/develop
|
MercadoPagoSDK/MercadoPagoSDK/Models/PXPaymentData+Tracking.swift
|
mit
|
1
|
import Foundation
// MARK: Tracking
extension PXPaymentData {
func getPaymentDataForTracking() -> [String: Any] {
guard let paymentMethod = paymentMethod else {
return [:]
}
let cardIdsEsc = PXTrackingStore.sharedInstance.getData(forKey: PXTrackingStore.cardIdsESC) as? [String] ?? []
var properties: [String: Any] = [:]
properties["payment_method_type"] = paymentMethod.getPaymentTypeForTracking()
properties["payment_method_id"] = paymentMethod.getPaymentIdForTracking()
var extraInfo: [String: Any] = [:]
if paymentMethod.isCard {
if let cardId = token?.cardId {
extraInfo["card_id"] = cardId
extraInfo["has_esc"] = cardIdsEsc.contains(cardId)
}
extraInfo["selected_installment"] = payerCost?.getPayerCostForTracking()
if let issuerId = issuer?.id {
extraInfo["issuer_id"] = Int64(issuerId)
}
properties["extra_info"] = extraInfo
} else if paymentMethod.isAccountMoney {
// TODO: When account money becomes FCM
// var extraInfo: [String: Any] = [:]
// extraInfo["balance"] =
// properties["extra_info"] = extraInfo
} else if paymentMethod.isDigitalCurrency {
extraInfo["selected_installment"] = payerCost?.getPayerCostForTracking(isDigitalCurrency: true)
properties["extra_info"] = extraInfo
}
return properties
}
}
|
ed4093c65e61530710623acb5eb6f6fc
| 40.351351 | 118 | 0.601307 | false | false | false | false |
atrick/swift
|
refs/heads/main
|
stdlib/public/Concurrency/AsyncThrowingPrefixWhileSequence.swift
|
apache-2.0
|
3
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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 Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Returns an asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy the given error-throwing
/// predicate.
///
/// Use `prefix(while:)` to produce values while elements from the base
/// sequence meet a condition you specify. The modified sequence ends when
/// the predicate closure returns `false` or throws an error.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `prefix(_:)` method causes the modified
/// sequence to pass through values less than `8`, but throws an
/// error when it receives a value that's divisible by `5`:
///
/// do {
/// let stream = try Counter(howHigh: 10)
/// .prefix {
/// if $0 % 5 == 0 {
/// throw MyError()
/// }
/// return $0 < 8
/// }
/// for try await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// } catch {
/// print("Error: \(error)")
/// }
/// // Prints: 1 2 3 4 Error: MyError()
///
/// - Parameter predicate: A error-throwing closure that takes an element of
/// the asynchronous sequence as its argument and returns a Boolean value
/// that indicates whether to include the element in the modified sequence.
/// - Returns: An asynchronous sequence that contains, in order, the elements
/// of the base sequence that satisfy the given predicate. If the predicate
/// throws an error, the sequence contains only values produced prior to
/// the error.
@preconcurrency
@inlinable
public __consuming func prefix(
while predicate: @Sendable @escaping (Element) async throws -> Bool
) rethrows -> AsyncThrowingPrefixWhileSequence<Self> {
return AsyncThrowingPrefixWhileSequence(self, predicate: predicate)
}
}
/// An asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy the given error-throwing
/// predicate.
@available(SwiftStdlib 5.1, *)
public struct AsyncThrowingPrefixWhileSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let predicate: (Base.Element) async throws -> Bool
@usableFromInline
init(
_ base: Base,
predicate: @escaping (Base.Element) async throws -> Bool
) {
self.base = base
self.predicate = predicate
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingPrefixWhileSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The prefix-while sequence produces whatever type of element its base
/// iterator produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the prefix-while sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var predicateHasFailed = false
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let predicate: (Base.Element) async throws -> Bool
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
predicate: @escaping (Base.Element) async throws -> Bool
) {
self.baseIterator = baseIterator
self.predicate = predicate
}
/// Produces the next element in the prefix-while sequence.
///
/// If the predicate hasn't failed yet, this method gets the next element
/// from the base sequence and calls the predicate with it. If this call
/// succeeds, this method passes along the element. Otherwise, it returns
/// `nil`, ending the sequence. If calling the predicate closure throws an
/// error, the sequence ends and `next()` rethrows the error.
@inlinable
public mutating func next() async throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try await baseIterator.next() {
do {
if try await predicate(nextElement) {
return nextElement
} else {
predicateHasFailed = true
}
} catch {
predicateHasFailed = true
throw error
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), predicate: predicate)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingPrefixWhileSequence: @unchecked Sendable
where Base: Sendable,
Base.Element: Sendable { }
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingPrefixWhileSequence.Iterator: @unchecked Sendable
where Base.AsyncIterator: Sendable,
Base.Element: Sendable { }
|
db69c6741a6050c2e5e4368d8879bc68
| 34.625 | 80 | 0.646907 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/Generics/issue-51450.swift
|
apache-2.0
|
2
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module %S/Inputs/issue-51450-other.swift -emit-module-path %t/other.swiftmodule -module-name other
// RUN: %target-swift-frontend -emit-silgen %s -I%t -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/51450
import other
public class C : P {
public typealias T = Int
}
public func takesInt(_: Int) {}
// CHECK-LABEL: .foo@
// CHECK-NEXT: Generic signature: <T, S where T : C, S : Sequence, S.[Sequence]Element == Int>
public func foo<T : C, S : Sequence>(_: T, _ xs: S) where S.Element == T.T {
for x in xs {
takesInt(x)
}
}
|
361ebf1e07b54c990c8b3d88ab7a7290
| 29.619048 | 135 | 0.662519 | false | false | false | false |
Jerry0523/JWIntent
|
refs/heads/master
|
Intent/Internal/NCProxyDelegate.swift
|
mit
|
1
|
//
// NCProxyDelegate.swift
//
// Copyright (c) 2015 Jerry Wong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class NCProxyDelegate : NSObject {
weak var target: UINavigationControllerDelegate?
weak var currentTransition: Transition?
class func addProxy(forNavigationController nc: UINavigationController) {
if (nc.delegate as? NCProxyDelegate) != nil {
return
}
let proxyDelegate = NCProxyDelegate()
proxyDelegate.target = nc.delegate
nc.delegate = proxyDelegate
objc_setAssociatedObject(nc, &NCProxyDelegate.proxyDelegateKey, proxyDelegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if nc.interactivePopGestureRecognizer != nil {
objc_setAssociatedObject(nc.interactivePopGestureRecognizer!, &NCProxyDelegate.instanceNCKey, nc, .OBJC_ASSOCIATION_ASSIGN)
}
}
@objc private func handleInteractivePopGesture(recognizer: UIPanGestureRecognizer) {
currentTransition?.handle(recognizer, gestureDidBegin: {
let nc: UINavigationController = objc_getAssociatedObject(recognizer, &NCProxyDelegate.instanceNCKey) as! UINavigationController
nc.popViewController(animated: true)
})
}
open override func forwardingTarget(for aSelector: Selector!) -> Any? {
if target?.responds(to: aSelector) ?? false {
return target
}
return super.forwardingTarget(for: aSelector)
}
override func responds(to aSelector: Selector!) -> Bool {
return (target?.responds(to:aSelector) ?? false) || super.responds(to: aSelector)
}
private static var instanceNCKey: Void?
private static var proxyDelegateKey: Void?
private static var oldInteractivePopTargetKey: Void?
}
extension NCProxyDelegate : UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if viewController.pushTransition != nil {
if objc_getAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey) == nil {
let allTargets = navigationController.interactivePopGestureRecognizer?.value(forKey: "_targets") as? NSMutableArray
objc_setAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey, allTargets?.firstObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
navigationController.interactivePopGestureRecognizer?.removeTarget(nil, action: nil)
navigationController.interactivePopGestureRecognizer?.addTarget(self, action: #selector(handleInteractivePopGesture(recognizer:)))
} else {
navigationController.interactivePopGestureRecognizer?.removeTarget(nil, action: nil)
let oldInteractivePopTarget = objc_getAssociatedObject(navigationController, &NCProxyDelegate.oldInteractivePopTargetKey)
if oldInteractivePopTarget != nil {
let allTargets = navigationController.interactivePopGestureRecognizer?.value(forKey: "_targets") as? NSMutableArray
allTargets?.add(oldInteractivePopTarget!)
}
}
currentTransition = viewController.pushTransition
target?.navigationController?(navigationController, didShow: viewController, animated: animated)
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let transitionOwner = (operation == .push ? toVC : fromVC)
let transition = transitionOwner.pushTransition
if transition != nil {
return transition
}
return target?.navigationController?(navigationController, animationControllerFor:operation, from:fromVC, to:toVC)
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let transition = animationController as? Transition {
return transition.interactiveController
}
return currentTransition?.interactiveController
}
}
|
08889fd83ea78e4d46928116f81f3d4b
| 48.234234 | 247 | 0.725892 | false | false | false | false |
jbrudvik/swift-playgrounds
|
refs/heads/master
|
structs-and-classes.playground/section-1.swift
|
mit
|
1
|
// Swift has both structs and classes.
// Structs and classes are very similar. The main difference is the copy semantics (on assign or parameter passing):
// - Structs are copied by value (instance variables are copied)
// - Classes are copied by reference
// Class instances may use the === and !== operators to test reference equality (i.e., are they the same object.
// Struct instances do not respond to these operators (by default).
// Addtionally, == and != are generally used to compare class instance value equality, but these need to be defined per-object.
// Stack is probably better-suited as a class than a struct, but we'll use this for illustration
struct Stack<T> {
var items = [T]()
var isEmpty: Bool { return items.isEmpty }
// By default, struct instance methods may not modify state. Use the `mutating` keyword to force this behavior
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
// Demonstration of Stacks
var s = Stack<Int>()
for i in 0..<3 {
s.push(i)
}
s
var s2 = s // s2 is a distinct copy of s
s2
while !s.isEmpty {
println(s.pop())
}
s // no longer contains any values
s2 // still contains all added values
// Both structs and classes may adopt (multiple) protocols (similar to implementing Java interfaces),
// but only classes may inherit (and be inherited). Classes may also include deinitializers, among other details.
class Queue<T> {
var items = [T]()
var isEmpty: Bool { return items.isEmpty }
// Initializer is called when class instance is constructed
init() {
println("initializing Queue")
println("done initializing Queue")
}
// Class instance methods can mutate by default. In fact, the `mutating` keyword is not allowed in classes
func push(item: T) {
items.append(item)
}
func pop() -> T {
return items.removeAtIndex(0)
}
}
// EquatableQueue<T> inherits from Queue<T> and adopts the Equatable protocol.
// According to EquatableQueue's definition of equality (all contained elements are equal), it
// also requires elements to be Equatable
class EquatableQueue<T: Equatable>: Queue<T>, Equatable {
override init() {
println("initializing EquatableQueue")
super.init() // Call the super initializer (otherwise it will be called afterward)
println("done initializing EquatableQueue")
}
}
// Although the Equatable protocol can be adopted by in the initial class definition, the == function required to (functionally) adopt the protocol must be defined in the global scope.
func ==<T>(lhs: EquatableQueue<T>, rhs: EquatableQueue<T>) -> Bool {
let lhsItems = lhs.items
let rhsItems = rhs.items
let lhsItemCount = lhsItems.count
let rhsItemCount = rhsItems.count
if lhsItemCount != rhsItemCount {
return false
}
for i in 0..<lhsItemCount {
if lhsItems[i] != rhsItems[i] {
return false
}
}
return true
}
// Demonstration of Queues
var q = Queue<Int>()
for i in 0..<3 {
q.push(i)
}
q
var q2 = q // q2 is a new reference to the same object referenced by q
q2
q2 === q // true, because q and q2 refer to the same object instance
while !q.isEmpty {
println(q.pop())
}
q
q2
// q == q2 // Although we know q and q2 are equal, they cannot be compared using == because the function for the operator is not implemented. Most classes that implement this adopt the Equatable Protocol.
// EquatableQueue instances can be compared
var eq = EquatableQueue<Int>()
for i in 0..<3 {
eq.push(i)
}
var eq2 = eq
eq === eq2
eq == eq2 // Because EquatableQueue is Equatable, we can compare the inner values
var eq3 = EquatableQueue<Int>()
eq3 != eq // eq3 is not equal to eq, because it has different contents
for i in 0..<3 {
eq3.push(i)
}
eq3 != eq // eq3 is now equal to eq by value, even though they are different object instances
eq3 !== eq // not the same objects
while !eq.isEmpty {
println(eq.pop())
}
eq == eq2 // Still equal
// If we knew that a Queue was really constructed as an EquatableQueue, we could downcast it
var qAsEq: Queue<Int> = EquatableQueue<Int>()
var qAsEq2 = qAsEq
qAsEq as! EquatableQueue == qAsEq2 as! EquatableQueue
|
cc0051b08a5ce217db49af67c4e84fa4
| 29.06993 | 204 | 0.686744 | false | false | false | false |
rumana1411/Giphying
|
refs/heads/master
|
SwappingCollectionView/BackTableViewController.swift
|
mit
|
1
|
//
// BackTableViewController.swift
// swRevealSlidingMenu
//
// Created by Rumana Nazmul on 20/6/17.
// Copyright © 2017 ALFA. All rights reserved.
//
import UIKit
class BackTableViewController: UITableViewController {
var menuArray = ["Home","Level","Album","Score","About", "Help"]
var controllers = ["ViewController","LvlViewController","AlbumViewController","ScrViewController","AboutViewController","HelpViewController"]
var menuIcon = ["iconsHome","iconsLevel","iconsAbout","iconsScore","iconsAbout","iconsHelp"]
var frontNVC: UINavigationController?
var frontVC: ViewController?
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "Logo.png")
let logoImgView = UIImageView(image: logo)
logoImgView.frame = CGRect(x: 100, y: 10, width: 10, height: 40 )
self.navigationItem.titleView = logoImgView
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
var imgName = menuIcon[indexPath.row] + ".png"
cell.myImgView.image = UIImage(named: imgName)
cell.myLbl.text = menuArray[indexPath.row]
return cell
}
// override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//
// let revealViewController: SWRevealViewController = self.revealViewController()
//
// let cell:CustomTableViewCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
//
//
//
//
// if cell.myLbl.text == "Home"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "Level"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "LvlViewController") as! LvlViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
// if cell.myLbl.text == "Album"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AlbumViewController") as! AlbumViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "Score"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "ScrViewController") as! ScrViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
//
// }
//
// if cell.myLbl.text == "About"{
//
// let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// let destVC = mainStoryBoard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController
// let newFrontViewController = UINavigationController.init(rootViewController: destVC)
// revealViewController.pushFrontViewController(newFrontViewController, animated: true)
// }
//
// }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//tableView.deselectRow(at: indexPath, animated: true)
var controller: UIViewController? = nil
switch indexPath.row
{
case 0:
controller = frontVC
default:
// Instantiate the controller to present
let storyboard = UIStoryboard(name: "Main", bundle: nil)
controller = storyboard.instantiateViewController(withIdentifier: controllers[indexPath.row])
break
}
if controller != nil
{
// Prevent stacking the same controller multiple times
_ = frontNVC?.popViewController(animated: false)
// Prevent pushing twice FrontTableViewController
if !(controller is ViewController) {
// Show the controller with the front view controller's navigation controller
frontNVC!.pushViewController(controller!, animated: false)
}
// Set front view controller's position to left
revealViewController().setFrontViewPosition(.left, animated: true)
}
}
// override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//
// var headerTitle: String!
// headerTitle = "Giphying"
// return headerTitle
// }
// override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//
// let headerView = UIView()
//
// // headerView.backgroundColor = UIColor.white
// let viewImg = UIImage(named: "Logo.png")
// let headerImgView = UIImageView(image: viewImg)
// headerImgView.frame = CGRect(x: 60, y: 10, width: 120, height: 100)
// headerView.addSubview(headerImgView)
//
// return headerView
//
//
// }
//
// override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//
//
// return 110
// }
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 112
}
}
|
128342708edf08f934535971409faea2
| 36.271739 | 145 | 0.62438 | false | false | false | false |
abunur/quran-ios
|
refs/heads/master
|
Quran/TextRenderPreloadingOperation.swift
|
gpl-3.0
|
2
|
//
// TextRenderPreloadingOperation.swift
// Quran
//
// Created by Mohamed Afifi on 3/28/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import PromiseKit
import UIKit
class TextRenderPreloadingOperation: AbstractPreloadingOperation<UIImage> {
let layout: TranslationTextLayout
init(layout: TranslationTextLayout) {
self.layout = layout
}
override func main() {
autoreleasepool {
guard let textLayout = layout.longTextLayout else {
fatalError("Cannot use \(type(of: self)) with nil longTextLayout")
}
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(attributedString: layout.text.attributedText)
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textLayout.textContainer)
// make sure the layout and glyph generations occurred.
layoutManager.ensureLayout(for: textLayout.textContainer)
layoutManager.ensureGlyphs(forGlyphRange: NSRange(location: 0, length: textLayout.numberOfGlyphs))
let image = imageFromText(layoutManager: layoutManager,
numberOfGlyphs: textLayout.numberOfGlyphs,
size: layout.size)
fulfill(image)
}
}
private func imageFromText(layoutManager: NSLayoutManager, numberOfGlyphs: Int, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let range = NSRange(location: 0, length: numberOfGlyphs)
layoutManager.drawGlyphs(forGlyphRange: range, at: .zero)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return cast(image)
}
}
|
89170d81c0f85fbef8e6b4a352a20bab
| 35.276923 | 110 | 0.680237 | false | false | false | false |
zavsby/ProjectHelpersSwift
|
refs/heads/master
|
Classes/Categories/UIView+Extensions.swift
|
mit
|
1
|
//
// UIView+Extensions.swift
// ProjectHelpers-Swift
//
// Created by Sergey on 02.11.15.
// Copyright © 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
import UIKit
public extension UIView {
//MARK: View frame and dimensions
public var top: Float {
get {
return Float(self.frame.origin.y)
}
set(top) {
var frame = self.frame
frame.origin.y = CGFloat(top)
self.frame = frame
}
}
public var left: Float {
get {
return Float(self.frame.origin.x)
}
set(left) {
var frame = self.frame
frame.origin.x = CGFloat(left)
self.frame = frame
}
}
public var bottom: Float {
get {
return Float(self.frame.origin.y + self.frame.size.height)
}
set(bottom) {
var frame = self.frame
frame.origin.y = CGFloat(bottom) - frame.size.height
self.frame = frame
}
}
public var right: Float {
get {
return Float(self.frame.origin.x + self.frame.size.width)
}
set(right) {
var frame = self.frame
frame.origin.x = CGFloat(right) - frame.size.width
self.frame = frame
}
}
public var height: Float {
get {
return Float(self.frame.size.height)
}
set(height) {
var frame = self.frame
frame.size.height = CGFloat(height)
self.frame = frame
}
}
public var width: Float {
get {
return Float(self.frame.size.width)
}
set(width) {
var frame = self.frame
frame.size.width = CGFloat(width)
self.frame = frame;
}
}
//MARK: Addtional methods
public func screenImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let copiedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return copiedImage
}
}
|
b33794480c64fab75bf84fdba98578de
| 23.402174 | 75 | 0.528966 | false | false | false | false |
Den-Ree/InstagramAPI
|
refs/heads/master
|
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Relationship/RelationshipTableViewController.swift
|
mit
|
2
|
//
// TableViewController.swift
// InstagramAPI
//
// Created by Admin on 02.06.17.
// Copyright © 2017 ConceptOffice. All rights reserved.
//
import UIKit
import Alamofire
enum RelationshipTableControllerType {
case follows
case followedBy
case requestedBy
case unknown
}
class RelationshipTableViewController: UITableViewController {
var type: RelationshipTableControllerType = .unknown
fileprivate var dataSource: [InstagramUser] = []
override func viewDidLoad() {
super.viewDidLoad()
let relationshipTableViewModel = RelationshipTableViewModel.init(type: self.type)
let request = relationshipTableViewModel.request()
relationshipTableViewModel.getDataSource(request: request!, completion: {
(dataSource: [InstagramUser]?) in
if dataSource != nil {
self.dataSource = dataSource!
self.tableView.reloadData()
}
})
}
}
extension RelationshipTableViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RelationshipCell", for: indexPath) as!RelationshipCell
let user = dataSource[indexPath.row]
cell.fullNameLabel.text = user.fullName
cell.userNameLabel.text = user.username
cell.avatarImage.af_setImage(withURL: user.profilePictureUrl!)
return cell
}
}
|
c044cd3cb8d1c66a358c2af46590ee6f
| 28.40678 | 120 | 0.701441 | false | false | false | false |
palle-k/SyntaxKit
|
refs/heads/master
|
SyntaxKit/SKLayoutManager.swift
|
mit
|
1
|
//
// SKLayoutManager.swift
// SyntaxKit
//
// Created by Palle Klewitz on 24.04.16.
// Copyright © 2016 Palle Klewitz.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
@available(*, deprecated:1.0, renamed:"LineNumberLayoutManager")
typealias SKLayoutManager = LineNumberLayoutManager
class LineNumberLayoutManager : NSLayoutManager
{
fileprivate var lastParagraphNumber: Int = 0
fileprivate var lastParagraphLocation: Int = 0
internal let lineNumberWidth: CGFloat = 30.0
override func processEditing(for textStorage: NSTextStorage, edited editMask: NSTextStorageEditActions, range newCharRange: NSRange, changeInLength delta: Int, invalidatedRange invalidatedCharRange: NSRange)
{
super.processEditing(for: textStorage, edited: editMask, range: newCharRange, changeInLength: delta, invalidatedRange: invalidatedCharRange)
if invalidatedCharRange.location < lastParagraphLocation
{
lastParagraphLocation = 0
lastParagraphNumber = 0
}
}
override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint)
{
super.drawBackground(forGlyphRange: glyphsToShow, at: origin)
let font = UIFont(name: "Menlo", size: 10.0)!
let color = UIColor.lightGray
let attributes = [NSFontAttributeName : font, NSForegroundColorAttributeName : color]
var numberRect = CGRect.zero
var paragraphNumber = 0
let ctx = UIGraphicsGetCurrentContext()
ctx?.setFillColor(UIColor.white.withAlphaComponent(0.1).cgColor)
ctx?.fill(CGRect(x: 0, y: 0, width: lineNumberWidth, height: self.textContainers[0].size.height))
self.enumerateLineFragments(forGlyphRange: glyphsToShow)
{ (rect, usedRect, textContainer, glyphRange, stop) in
let charRange = self.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
let paragraphRange = (self.textStorage!.string as NSString).paragraphRange(for: charRange)
if charRange.location == paragraphRange.location
{
numberRect = CGRect(x: 0, y: rect.origin.y, width: self.lineNumberWidth, height: rect.size.height).offsetBy(dx: origin.x, dy: origin.y)
paragraphNumber = self.paragraphNumber(forRange: charRange)
let lineNumber = "\(paragraphNumber + 1)" as NSString
let size = lineNumber.size(attributes: attributes)
lineNumber.draw(in: numberRect.offsetBy(dx: numberRect.width - 4 - size.width, dy: (numberRect.height - size.height) * 0.5 + 1.0), withAttributes: attributes)
}
}
if NSMaxRange(glyphsToShow) > self.numberOfGlyphs
{
let lineNumber = "\(paragraphNumber + 2)" as NSString
let size = lineNumber.size(attributes: attributes)
numberRect = numberRect.offsetBy(dx: 0, dy: numberRect.height)
lineNumber.draw(in: numberRect.offsetBy(dx: numberRect.width - 4 - size.width, dy: (numberRect.height - size.height) * 0.5 + 1.0), withAttributes: attributes)
}
}
fileprivate func paragraphNumber(forRange charRange: NSRange) -> Int
{
if charRange.location == lastParagraphLocation
{
return lastParagraphNumber
}
else if charRange.location < lastParagraphLocation
{
let string = textStorage!.string as NSString
var paragraphNumber = lastParagraphNumber
string.enumerateSubstrings(
in: NSRange(
location: charRange.location,
length: lastParagraphLocation - charRange.location),
options: [.byParagraphs, .substringNotRequired, .reverse])
{ (substring, substringRange, enclosingRange, stop) in
if enclosingRange.location <= charRange.location
{
stop.pointee = true
}
paragraphNumber -= 1
}
lastParagraphNumber = paragraphNumber
lastParagraphLocation = charRange.location
return paragraphNumber
}
else
{
let string = textStorage!.string as NSString
var paragraphNumber = lastParagraphNumber
string.enumerateSubstrings(
in: NSRange(
location: lastParagraphLocation,
length: charRange.location - lastParagraphLocation),
options: [.byParagraphs, .substringNotRequired])
{ (substring, substringRange, enclosingRange, stop) in
if enclosingRange.location >= charRange.location
{
stop.pointee = true
}
paragraphNumber += 1
}
lastParagraphNumber = paragraphNumber
lastParagraphLocation = charRange.location
return paragraphNumber
}
}
}
|
5e8f4775ba09731c3116100ae76c695b
| 37.05 | 208 | 0.745823 | false | false | false | false |
FredCox3/public-jss
|
refs/heads/master
|
Swift-Groups/Just.swift
|
mit
|
1
|
//
// Just.swift
// Just
//
// Created by Daniel Duan on 4/21/15.
// Copyright (c) 2015 JustHTTP. All rights reserved.
//
import Foundation
extension Just {
public class func delete(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
URLQuery:String? = nil,
requestBody:NSData? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.DELETE,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout:timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func get(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
allowRedirects:Bool = true,
cookies:[String:String] = [:],
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.GET,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout:timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func head(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.HEAD,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout: timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func options(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.OPTIONS,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout: timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func patch(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.OPTIONS,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout: timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func post(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.POST,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout: timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
public class func put(
URLString:String,
params:[String:AnyObject] = [:],
data:[String:AnyObject] = [:],
json:[String:AnyObject]? = nil,
headers:[String:String] = [:],
files:[String:HTTPFile] = [:],
auth:(String,String)? = nil,
cookies:[String:String] = [:],
allowRedirects:Bool = true,
timeout:Double? = nil,
requestBody:NSData? = nil,
URLQuery:String? = nil,
asyncProgressHandler:((HTTPProgress!) -> Void)? = nil,
asyncCompletionHandler:((HTTPResult!) -> Void)? = nil
) -> HTTPResult {
return Just.shared.request(
.PUT,
URLString: URLString,
params: params,
data: data,
json: json,
headers: headers,
files:files,
auth: auth,
cookies: cookies,
redirects: allowRedirects,
timeout: timeout,
URLQuery: URLQuery,
requestBody: requestBody,
asyncProgressHandler: asyncProgressHandler,
asyncCompletionHandler: asyncCompletionHandler
)
}
}
public enum HTTPFile {
case URL(NSURL,String?) // URL to a file, mimetype
case Data(String,NSData,String?) // filename, data, mimetype
case Text(String,String,String?) // filename, text, mimetype
}
// Supported request types
enum HTTPMethod: String {
case DELETE = "DELETE"
case GET = "GET"
case HEAD = "HEAD"
case OPTIONS = "OPTIONS"
case PATCH = "PATCH"
case POST = "POST"
case PUT = "PUT"
}
/// The only reason this is not a struct is the requirements for
/// lazy evaluation of `headers` and `cookies`, which is mutating the
/// struct. This would make those properties unusable with `HTTPResult`s
/// declared with `let`
public final class HTTPResult : NSObject {
public final var content:NSData?
public var response:NSURLResponse?
public var error:NSError?
public var request:NSURLRequest?
public var encoding = NSUTF8StringEncoding
public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0)
public var reason:String {
if let code = self.statusCode,
let text = statusCodeDescriptions[code] {
return text
}
if let error = self.error {
return error.localizedDescription
}
return "Unkown"
}
public var isRedirect:Bool {
if let code = self.statusCode {
return code >= 300 && code < 400
}
return false
}
public var isPermanentRedirect:Bool {
return self.statusCode == 301
}
public override var description:String {
if let status = statusCode,
urlString = request?.URL?.absoluteString,
method = request?.HTTPMethod
{
return "\(method) \(urlString) \(status)"
} else {
return "<Empty>"
}
}
init(data:NSData?, response:NSURLResponse?, error:NSError?, request:NSURLRequest?) {
self.content = data
self.response = response
self.error = error
self.request = request
}
public var json:AnyObject? {
if let theData = self.content {
do {
return try NSJSONSerialization.JSONObjectWithData(theData, options: JSONReadingOptions)
} catch _ {
return nil
}
}
return nil
}
public var statusCode: Int? {
if let theResponse = self.response as? NSHTTPURLResponse {
return theResponse.statusCode
}
return nil
}
public var text:String? {
if let theData = self.content {
return NSString(data:theData, encoding:encoding) as? String
}
return nil
}
public lazy var headers:CaseInsensitiveDictionary<String,String> = {
return CaseInsensitiveDictionary<String,String>(dictionary: (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String:String] ?? [:])
}()
public lazy var cookies:[String:NSHTTPCookie] = {
let foundCookies: [NSHTTPCookie]
if let responseHeaders = (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String: String] {
foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:NSURL(string:"")!) as [NSHTTPCookie]
} else {
foundCookies = []
}
var result:[String:NSHTTPCookie] = [:]
for cookie in foundCookies {
result[cookie.name] = cookie
}
return result
}()
public var ok:Bool {
return statusCode != nil && !(statusCode! >= 400 && statusCode! < 600)
}
public var url:NSURL? {
return response?.URL
}
}
public struct CaseInsensitiveDictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible {
private var _data:[Key: Value] = [:]
private var _keyMap: [String: Key] = [:]
typealias Element = (Key, Value)
typealias Index = DictionaryIndex<Key, Value>
public var startIndex: Index
public var endIndex: Index
public var count: Int {
assert(_data.count == _keyMap.count, "internal keys out of sync")
return _data.count
}
public var isEmpty: Bool {
return _data.isEmpty
}
public init() {
startIndex = _data.startIndex
endIndex = _data.endIndex
}
public init(dictionaryLiteral elements: (Key, Value)...) {
for (key, value) in elements {
_keyMap["\(key)".lowercaseString] = key
_data[key] = value
}
startIndex = _data.startIndex
endIndex = _data.endIndex
}
public init(dictionary:[Key:Value]) {
for (key, value) in dictionary {
_keyMap["\(key)".lowercaseString] = key
_data[key] = value
}
startIndex = _data.startIndex
endIndex = _data.endIndex
}
public subscript (position: Index) -> Element {
return _data[position]
}
public subscript (key: Key) -> Value? {
get {
if let realKey = _keyMap["\(key)".lowercaseString] {
return _data[realKey]
}
return nil
}
set(newValue) {
let lowerKey = "\(key)".lowercaseString
if _keyMap[lowerKey] == nil {
_keyMap[lowerKey] = key
}
_data[_keyMap[lowerKey]!] = newValue
}
}
public func generate() -> DictionaryGenerator<Key, Value> {
return _data.generate()
}
// public var keys: LazyForwardCollection<MapCollection<[Key : Value], Key>> {
// return _data.keys
// }
// public var values: LazyForwardCollection<MapCollection<[Key : Value], Value>> {
// return _data.values
// }
}
typealias TaskID = Int
typealias Credentials = (username:String, password:String)
typealias TaskProgressHandler = (HTTPProgress!) -> Void
typealias TaskCompletionHandler = (HTTPResult) -> Void
struct TaskConfiguration {
let credential:Credentials?
let redirects:Bool
let originalRequest: NSURLRequest?
var data: NSMutableData
let progressHandler: TaskProgressHandler?
let completionHandler: TaskCompletionHandler?
}
public struct JustSessionDefaults {
public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0)
public var JSONWritingOptions = NSJSONWritingOptions(rawValue: 0)
public var headers:[String:String] = [:]
public var multipartBoundary = "Ju5tH77P15Aw350m3"
public var encoding = NSUTF8StringEncoding
}
public struct HTTPProgress {
public enum Type {
case Upload
case Download
}
public let type:Type
public let bytesProcessed:Int64
public let bytesExpectedToProcess:Int64
public var percent: Float {
return Float(bytesProcessed) / Float(bytesExpectedToProcess)
}
}
let errorDomain = "net.justhttp.Just"
public class Just: NSObject, NSURLSessionDelegate {
private struct Shared {
static let instance = Just()
}
class var shared: Just { return Shared.instance }
public init(session:NSURLSession? = nil, defaults:JustSessionDefaults? = nil) {
super.init()
if let initialSession = session {
self.session = initialSession
} else {
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:self, delegateQueue:nil)
}
if let initialDefaults = defaults {
self.defaults = initialDefaults
} else {
self.defaults = JustSessionDefaults()
}
}
var taskConfigs:[TaskID:TaskConfiguration]=[:]
var defaults:JustSessionDefaults!
var session: NSURLSession!
var invalidURLError = NSError(
domain: errorDomain,
code: 0,
userInfo: [NSLocalizedDescriptionKey:"[Just] URL is invalid"]
)
var syncResultAccessError = NSError(
domain: errorDomain,
code: 1,
userInfo: [NSLocalizedDescriptionKey:"[Just] You are accessing asynchronous result synchronously."]
)
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)", value)
}
} else {
components.extend([(percentEncodeString(key), percentEncodeString("\(value)"))])
}
return components
}
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in Array(parameters.keys).sort(<) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return "&".join(components.map{"\($0)=\($1)"} as [String])
}
func percentEncodeString(originalObject: AnyObject) -> String {
if originalObject is NSNull {
return "null"
} else {
return "\(originalObject)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? ""
}
}
func makeTask(request:NSURLRequest, configuration: TaskConfiguration) -> NSURLSessionDataTask? {
if let task = session.dataTaskWithRequest(request) {
taskConfigs[task.taskIdentifier] = configuration
return task
}
return nil
}
func synthesizeMultipartBody(data:[String:AnyObject], files:[String:HTTPFile]) -> NSData? {
let body = NSMutableData()
let boundary = "--\(self.defaults.multipartBoundary)\r\n".dataUsingEncoding(defaults.encoding)!
for (k,v) in data {
let valueToSend:AnyObject = v is NSNull ? "null" : v
body.appendData(boundary)
body.appendData("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n".dataUsingEncoding(defaults.encoding)!)
body.appendData("\(valueToSend)\r\n".dataUsingEncoding(defaults.encoding)!)
}
for (k,v) in files {
body.appendData(boundary)
var partContent: NSData? = nil
var partFilename:String? = nil
var partMimetype:String? = nil
switch v {
case let .URL(URL, mimetype):
if let component = URL.lastPathComponent {
partFilename = component
}
if let URLContent = NSData(contentsOfURL: URL) {
partContent = URLContent
}
partMimetype = mimetype
case let .Text(filename, text, mimetype):
partFilename = filename
if let textData = text.dataUsingEncoding(defaults.encoding) {
partContent = textData
}
partMimetype = mimetype
case let .Data(filename, data, mimetype):
partFilename = filename
partContent = data
partMimetype = mimetype
}
if let content = partContent, let filename = partFilename {
body.appendData(NSData(data: "Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(defaults.encoding)!))
if let type = partMimetype {
body.appendData("Content-Type: \(type)\r\n\r\n".dataUsingEncoding(defaults.encoding)!)
} else {
body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!)
}
body.appendData(content)
body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!)
}
}
if body.length > 0 {
body.appendData("--\(self.defaults.multipartBoundary)--\r\n".dataUsingEncoding(defaults.encoding)!)
}
return body
}
func synthesizeRequest(
method:HTTPMethod,
URLString:String,
params:[String:AnyObject],
data:[String:AnyObject],
json:[String:AnyObject]?,
headers:CaseInsensitiveDictionary<String,String>,
files:[String:HTTPFile],
timeout:Double?,
requestBody:NSData?,
URLQuery:String?
) -> NSURLRequest? {
if let urlComponent = NSURLComponents(string: URLString) {
let queryString = query(params)
if queryString.characters.count > 0 {
urlComponent.percentEncodedQuery = queryString
}
var finalHeaders = headers
var contentType:String? = nil
var body:NSData?
if let requestData = requestBody {
body = requestData
} else if files.count > 0 {
body = synthesizeMultipartBody(data, files:files)
contentType = "multipart/form-data; boundary=\(self.defaults.multipartBoundary)"
} else {
if let requestJSON = json {
contentType = "application/json"
do {
body = try NSJSONSerialization.dataWithJSONObject(requestJSON, options: defaults.JSONWritingOptions)
} catch _ {
body = nil
}
} else {
if data.count > 0 {
if headers["content-type"]?.lowercaseString == "application/json" { // assume user wants JSON if she is using this header
do {
body = try NSJSONSerialization.dataWithJSONObject(data, options: defaults.JSONWritingOptions)
} catch _ {
body = nil
}
} else {
contentType = "application/x-www-form-urlencoded"
body = query(data).dataUsingEncoding(defaults.encoding)
}
}
}
}
if let contentTypeValue = contentType {
finalHeaders["Content-Type"] = contentTypeValue
}
if let URL = urlComponent.URL {
let request = NSMutableURLRequest(URL: URL)
request.cachePolicy = .ReloadIgnoringLocalCacheData
request.HTTPBody = body
request.HTTPMethod = method.rawValue
if let requestTimeout = timeout {
request.timeoutInterval = requestTimeout
}
for (k,v) in defaults.headers {
request.addValue(v, forHTTPHeaderField: k)
}
for (k,v) in finalHeaders {
request.addValue(v, forHTTPHeaderField: k)
}
return request
}
}
return nil
}
func request(
method:HTTPMethod,
URLString:String,
params:[String:AnyObject],
data:[String:AnyObject],
json:[String:AnyObject]?,
headers:[String:String],
files:[String:HTTPFile],
auth:Credentials?,
cookies: [String:String],
redirects:Bool,
timeout:Double?,
URLQuery:String?,
requestBody:NSData?,
asyncProgressHandler:TaskProgressHandler?,
asyncCompletionHandler:((HTTPResult!) -> Void)?) -> HTTPResult {
let isSync = asyncCompletionHandler == nil
let semaphore = dispatch_semaphore_create(0)
var requestResult:HTTPResult = HTTPResult(data: nil, response: nil, error: syncResultAccessError, request: nil)
let caseInsensitiveHeaders = CaseInsensitiveDictionary<String,String>(dictionary:headers)
if let request = synthesizeRequest(
method,
URLString: URLString,
params: params,
data: data,
json: json,
headers: caseInsensitiveHeaders,
files: files,
timeout:timeout,
requestBody:requestBody,
URLQuery: URLQuery
) {
addCookies(request.URL!, newCookies: cookies)
let config = TaskConfiguration(
credential:auth,
redirects:redirects,
originalRequest:request,
data:NSMutableData(),
progressHandler: asyncProgressHandler
) { (result) in
if let handler = asyncCompletionHandler {
handler(result)
}
if isSync {
requestResult = result
dispatch_semaphore_signal(semaphore)
}
}
if let task = makeTask(request, configuration:config) {
task.resume()
}
if isSync {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return requestResult
}
} else {
let erronousResult = HTTPResult(data: nil, response: nil, error: invalidURLError, request: nil)
if let handler = asyncCompletionHandler {
handler(erronousResult)
} else {
return erronousResult
}
}
return requestResult
}
func addCookies(URL:NSURL, newCookies:[String:String]) {
for (k,v) in newCookies {
if let cookie = NSHTTPCookie(properties: [
NSHTTPCookieName: k,
NSHTTPCookieValue: v,
NSHTTPCookieOriginURL: URL,
NSHTTPCookiePath: "/"
]) {
session.configuration.HTTPCookieStorage?.setCookie(cookie)
}
}
}
}
extension Just: NSURLSessionTaskDelegate, NSURLSessionDataDelegate {
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void
) {
var endCredential:NSURLCredential? = nil
if let credential = taskConfigs[task.taskIdentifier]?.credential {
if !(challenge.previousFailureCount > 0) {
endCredential = NSURLCredential(user: credential.0, password: credential.1, persistence: .ForSession)
}
}
completionHandler(.UseCredential, endCredential)
}
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void
) {
if let allowRedirects = taskConfigs[task.taskIdentifier]?.redirects {
if !allowRedirects {
completionHandler(nil)
return
}
completionHandler(request)
} else {
completionHandler(request)
}
}
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64
) {
if let handler = taskConfigs[task.taskIdentifier]?.progressHandler {
handler(
HTTPProgress(
type: .Upload,
bytesProcessed: totalBytesSent,
bytesExpectedToProcess: totalBytesExpectedToSend
)
)
}
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let handler = taskConfigs[dataTask.taskIdentifier]?.progressHandler {
handler(
HTTPProgress(
type: .Download,
bytesProcessed: dataTask.countOfBytesReceived,
bytesExpectedToProcess: dataTask.countOfBytesExpectedToReceive
)
)
}
if taskConfigs[dataTask.taskIdentifier]?.data != nil {
taskConfigs[dataTask.taskIdentifier]?.data.appendData(data)
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let config = taskConfigs[task.taskIdentifier], let handler = config.completionHandler {
let result = HTTPResult(
data: config.data,
response: task.response,
error: error,
request: config.originalRequest ?? task.originalRequest
)
result.JSONReadingOptions = self.defaults.JSONReadingOptions
result.encoding = self.defaults.encoding
handler(result)
}
taskConfigs.removeValueForKey(task.taskIdentifier)
}
}
// stolen from python-requests
let statusCodeDescriptions = [
// Informational.
100: "continue" , 101: "switching protocols" , 102: "processing" ,
103: "checkpoint" , 122: "uri too long" , 200: "ok" ,
201: "created" , 202: "accepted" , 203: "non authoritative info" ,
204: "no content" , 205: "reset content" , 206: "partial content" ,
207: "multi status" , 208: "already reported" , 226: "im used" ,
// Redirection.
300: "multiple choices" , 301: "moved permanently" , 302: "found" ,
303: "see other" , 304: "not modified" , 305: "use proxy" ,
306: "switch proxy" , 307: "temporary redirect" , 308: "permanent redirect" ,
// Client Error.
400: "bad request" , 401: "unauthorized" , 402: "payment required" ,
403: "forbidden" , 404: "not found" , 405: "method not allowed" ,
406: "not acceptable" , 407: "proxy authentication required" , 408: "request timeout" ,
409: "conflict" , 410: "gone" , 411: "length required" ,
412: "precondition failed" , 413: "request entity too large" , 414: "request uri too large" ,
415: "unsupported media type" , 416: "requested range not satisfiable" , 417: "expectation failed" ,
418: "im a teapot" , 422: "unprocessable entity" , 423: "locked" ,
424: "failed dependency" , 425: "unordered collection" , 426: "upgrade required" ,
428: "precondition required" , 429: "too many requests" , 431: "header fields too large" ,
444: "no response" , 449: "retry with" , 450: "blocked by windows parental controls" ,
451: "unavailable for legal reasons" , 499: "client closed request" ,
// Server Error.
500: "internal server error" , 501: "not implemented" , 502: "bad gateway" ,
503: "service unavailable" , 504: "gateway timeout" , 505: "http version not supported" ,
506: "variant also negotiates" , 507: "insufficient storage" , 509: "bandwidth limit exceeded" ,
510: "not extended" ,
]
|
c88590ed24c28deb292d0b72f982f5f6
| 35.554098 | 162 | 0.532155 | false | false | false | false |
carlosgrossi/ExtensionKit
|
refs/heads/master
|
ExtensionKit/ExtensionKit/Foundation/NumberFormatter.swift
|
mit
|
1
|
//
// NumberFormatter.swift
// Pods
//
// Created by Carlos Grossi on 19/06/17.
//
//
public extension NumberFormatter {
/// Convenience Initializer that sets number style, minimum and maximum fraction digits and locale
///
/// - Parameters:
/// - numberStyle: The number style used by the receiver.
/// - maximumFractionDigits: The maximum number of digits after the decimal separator allowed as input and output by the receiver.
/// - minimumFractionDigits: The minimum number of digits after the decimal separator allowed as input and output by the receiver.
/// - locale: The locale of the receiver.
convenience init(numberStyle: NumberFormatter.Style, maximumFractionDigits: Int = 0, minimumFractionDigits: Int = 0, locale: Locale = Locale.current) {
self.init()
self.numberStyle = numberStyle
self.maximumFractionDigits = maximumFractionDigits
self.minimumFractionDigits = minimumFractionDigits
self.locale = Locale.current
}
}
|
644c8ce97f51fa457b3774797912fdc3
| 36.269231 | 152 | 0.747162 | false | false | false | false |
TwoRingSoft/shared-utils
|
refs/heads/master
|
Examples/Pippin/Pippin-iOS/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// PippinTestHarness
//
// Created by Andrew McKnight on 4/3/17.
//
//
import Pippin
import PippinAdapters
#if DEBUG
import PippinDebugging
#endif
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var environment: Environment = {
let environment = Environment.default(
bugReportRecipients: ["andrew@tworingsoft.com"],
touchVizRootVC: ViewController(nibName: nil, bundle: nil)
)
environment.crashReporter = CrashlyticsAdapter(debug: true)
#if !targetEnvironment(simulator)
environment.locator = CoreLocationAdapter(locatorDelegate: self)
#endif
#if DEBUG
environment.model?.debuggingDelegate = self
environment.debugging = DebugFlowController(databaseFileName: "PippinTestHarnessDatabase")
#endif
environment.connectEnvironment()
return environment
}()
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if DEBUG
environment.debugging?.installViews(appControlPanel: nil)
#endif
environment.touchVisualizer?.installViews()
return true
}
}
#if DEBUG
extension AppDelegate: ModelDebugging {
func importFixtures(coreDataController: Model) {
environment.alerter?.showAlert(title: "Import database fixtures", message: "This is where your app would imports its database from other instances of itself, like on another test device.", type: .info, dismissal: .interactive, occlusion: .weak)
}
func exported(coreDataController: Model) {
environment.alerter?.showAlert(title: "Exporting database", message: "This is where your app would export its database to transport to other instances of itself, like on another test device.", type: .info, dismissal: .interactive, occlusion: .weak)
}
func generateTestModels(coreDataController: Model) {
environment.alerter?.showAlert(title: "Generating test models", message: "This is where your app would generate some test model entities.", type: .info, dismissal: .interactive, occlusion: .strong)
}
func deleteModels(coreDataController: Model) {
environment.alerter?.showAlert(title: "Deleting models", message: "This is where your app would delete its model entities.", type: .info, dismissal: .interactive, occlusion: .strong)
}
}
#endif
#if !targetEnvironment(simulator)
extension AppDelegate: LocatorDelegate {
func locator(locator: Locator, updatedToLocation location: Location) {
environment.logger?.logInfo(message: "locator \(locator) updated to location \(location)")
}
func locator(locator: Locator, encounteredError: LocatorError) {
environment.logger?.logError(message: "Locator \(locator) encountered error \(encounteredError)", error: encounteredError)
}
}
#endif
|
2f22c6c4aa80d4a136a7f1a2be2b7c86
| 36.148148 | 256 | 0.71552 | false | true | false | false |
burhanaksendir/swift-disk-status
|
refs/heads/master
|
DiskStatus/DiskStatus.swift
|
mit
|
1
|
//
// DiskStatus.swift
// DiskStatus
//
// Created by Cuong Lam on 3/29/15.
// Copyright (c) 2015 BE Studio. All rights reserved.
//
import UIKit
class DiskStatus {
//MARK: Formatter MB only
class func MBFormatter(bytes: Int64) -> String {
var formatter = NSByteCountFormatter()
formatter.allowedUnits = NSByteCountFormatterUnits.UseMB
formatter.countStyle = NSByteCountFormatterCountStyle.Decimal
formatter.includesUnit = false
return formatter.stringFromByteCount(bytes) as String
}
//MARK: Get String Value
class var totalDiskSpace:String {
get {
return NSByteCountFormatter.stringFromByteCount(totalDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary)
}
}
class var freeDiskSpace:String {
get {
return NSByteCountFormatter.stringFromByteCount(freeDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary)
}
}
class var usedDiskSpace:String {
get {
return NSByteCountFormatter.stringFromByteCount(usedDiskSpaceInBytes, countStyle: NSByteCountFormatterCountStyle.Binary)
}
}
//MARK: Get raw value
class var totalDiskSpaceInBytes:Int64 {
get {
let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory() as String, error: nil)
let space = (systemAttributes?[NSFileSystemSize] as? NSNumber)?.longLongValue
return space!
}
}
class var freeDiskSpaceInBytes:Int64 {
get {
let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory() as String, error: nil)
let freeSpace = (systemAttributes?[NSFileSystemFreeSize] as? NSNumber)?.longLongValue
return freeSpace!
}
}
class var usedDiskSpaceInBytes:Int64 {
get {
let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes
return usedSpace
}
}
}
|
cd1dbe788e922d02786bdf76e73a1e96
| 30.681818 | 136 | 0.663797 | false | false | false | false |
JOCR10/iOS-Curso
|
refs/heads/master
|
Tareas/Tarea 4/TareaDogsWithCoreData/TareaDogsWithCoreData/AddDogViewController.swift
|
mit
|
1
|
import UIKit
class AddDogViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate
{
@IBOutlet weak var nombreTextField: UITextField!
@IBOutlet weak var colorTextField: UITextField!
@IBOutlet weak var dogImageView: UIImageView!
var imagePicker = UIImagePickerController()
var dogImage : NSData?
override func viewDidLoad()
{
super.viewDidLoad()
addSaveDogs()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func addSaveDogs()
{
let saveAction = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveDogsAction))
navigationItem.rightBarButtonItem = saveAction
}
func saveDogsAction()
{
guard let _ = dogImage else
{
mostrarAlerta(msj: "Debe seleccionar una imagen", titulo: "Alerta")
return
}
if nombreTextField.text!.characters.count > 0 && colorTextField.text!.characters.count > 0
{
CoreDataManager.createDog(name: nombreTextField.text!, color: colorTextField.text!, image: dogImage!)
navigationController?.popViewController(animated: true)
}
else
{
mostrarAlerta(msj: "Debe digitar el nombre y el color del perro", titulo: "Alerta")
}
}
func mostrarAlerta(msj: String, titulo: String){
let alertController = UIAlertController(title: titulo, message: msj, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
@IBAction func examinarButton(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum)
{
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
dogImageView.image = image
dogImage = UIImagePNGRepresentation(image) as NSData?
self.dismiss(animated: true, completion: nil);
}
}
|
f93d2d4c39b15b0a67f6258625c4373c
| 30.582278 | 117 | 0.646493 | false | false | false | false |
pkx0128/UIKit
|
refs/heads/master
|
MPickerInTextField/MPickerInTextField/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// MPickerInTextField
//
// Created by pankx on 2017/9/22.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
//定义picker的数据数组
let week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
//定义mytext
fileprivate var mytext: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//创建myicker
let mypicker = UIPickerView()
//设置代理
mypicker.delegate = self
//设置数据源
mypicker.dataSource = self
//创建mytext
mytext = UITextField(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 80))
//设置位置
mytext.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.3)
//设置内容居中
mytext.textAlignment = .center
//设置键盘为mypicker
mytext.inputView = mypicker
//设置初始值为week[0]的值
mytext.text = week[0]
//设置背景颜色
mytext.backgroundColor = UIColor.darkGray
view.addSubview(mytext)
}
//设置picker的列数
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//设置picker内容行数据
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return week.count
}
//设置picker内容
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return week[row]
}
//把picker选中的内容设置到mytext
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
mytext.text = week[row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
f1f6e772038a4359fecf42d42f0d693b
| 27.78125 | 111 | 0.631379 | false | false | false | false |
WhisperSystems/Signal-iOS
|
refs/heads/master
|
SignalServiceKit/src/Account/PreKeyRefreshOperation.swift
|
gpl-3.0
|
1
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
// We generate 100 one-time prekeys at a time. We should replenish
// whenever ~2/3 of them have been consumed.
let kEphemeralPreKeysMinimumCount: UInt = 35
@objc(SSKRefreshPreKeysOperation)
public class RefreshPreKeysOperation: OWSOperation {
private var tsAccountManager: TSAccountManager {
return TSAccountManager.sharedInstance()
}
private var accountServiceClient: AccountServiceClient {
return SSKEnvironment.shared.accountServiceClient
}
private var signedPreKeyStore: SSKSignedPreKeyStore {
return SSKEnvironment.shared.signedPreKeyStore
}
private var preKeyStore: SSKPreKeyStore {
return SSKEnvironment.shared.preKeyStore
}
private var identityKeyManager: OWSIdentityManager {
return OWSIdentityManager.shared()
}
public override func run() {
Logger.debug("")
guard tsAccountManager.isRegistered else {
Logger.debug("skipping - not registered")
return
}
firstly {
self.accountServiceClient.getPreKeysCount()
}.then(on: DispatchQueue.global()) { preKeysCount -> Promise<Void> in
Logger.debug("preKeysCount: \(preKeysCount)")
guard preKeysCount < kEphemeralPreKeysMinimumCount || self.signedPreKeyStore.currentSignedPrekeyId() == nil else {
Logger.debug("Available keys sufficient: \(preKeysCount)")
return Promise.value(())
}
let identityKey: Data = self.identityKeyManager.identityKeyPair()!.publicKey
let signedPreKeyRecord: SignedPreKeyRecord = self.signedPreKeyStore.generateRandomSignedRecord()
let preKeyRecords: [PreKeyRecord] = self.preKeyStore.generatePreKeyRecords()
self.signedPreKeyStore.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord)
self.preKeyStore.storePreKeyRecords(preKeyRecords)
return firstly {
self.accountServiceClient.setPreKeys(identityKey: identityKey, signedPreKeyRecord: signedPreKeyRecord, preKeyRecords: preKeyRecords)
}.done {
signedPreKeyRecord.markAsAcceptedByService()
self.signedPreKeyStore.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord)
self.signedPreKeyStore.setCurrentSignedPrekeyId(signedPreKeyRecord.id)
TSPreKeyManager.clearPreKeyUpdateFailureCount()
TSPreKeyManager.clearSignedPreKeyRecords()
}
}.done {
Logger.debug("done")
self.reportSuccess()
}.catch { error in
self.reportError(withUndefinedRetry: error)
}.retainUntilComplete()
}
public override func didSucceed() {
TSPreKeyManager.refreshPreKeysDidSucceed()
}
override public func didFail(error: Error) {
switch error {
case let networkManagerError as NetworkManagerError:
guard !networkManagerError.isNetworkError else {
Logger.debug("don't report SPK rotation failure w/ network error")
return
}
guard networkManagerError.statusCode >= 400 && networkManagerError.statusCode <= 599 else {
Logger.debug("don't report SPK rotation failure w/ non application error")
return
}
TSPreKeyManager.incrementPreKeyUpdateFailureCount()
default:
Logger.debug("don't report SPK rotation failure w/ non NetworkManager error: \(error)")
}
}
}
|
3c6a8e09da8e2f2176dd99ce57bf309f
| 36.434343 | 148 | 0.670264 | false | false | false | false |
caiodias/CleanerSkeeker
|
refs/heads/master
|
CleanerSeeker/CleanerSeeker/ResetPasswordViewController.swift
|
mit
|
1
|
//
// ResetPasswordViewController.swift
// CleanerSeeker
//
// Created by Orest Hazda on 03/04/17.
// Copyright © 2017 Caio Dias. All rights reserved.
//
import UIKit
class ResetPasswordViewController: BasicVC {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var resetBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//Disable resetBtn
resetBtn.isEnabled = false
// Do any additional setup after loading the view.
email.addTarget(self, action: #selector(emailFieldDidChanged), for: .editingChanged)
self.baseScrollView = self.scrollView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func resetPassword(_ sender: UIButton) {
if let userEmail = email.text {
Utilities.showLoading()
Facade.shared.resetPassword(email: userEmail, onSuccess: showSuccessAlert, onFail: showFailAlert)
}
}
func emailFieldDidChanged(_ email: UITextField) {
resetBtn.isEnabled = email.text != nil
}
private func showSuccessAlert(success:Any) {
Utilities.dismissLoading()
let action = UIAlertAction(title: "Return to Login screen", style: .default) { (_) in
self.dismiss(animated: true, completion: nil)
_ = self.navigationController?.popToRootViewController(animated: true)
}
Utilities.displayAlert(title: "Password Reset", message: "Check your email to proceed the progress.", okAction: action)
}
private func showFailAlert(error: Error) {
Utilities.dismissLoading()
Utilities.displayAlert(error)
}
}
|
8a185afb6b48bf055e0b3a9f469bd849
| 30.508772 | 127 | 0.669822 | false | false | false | false |
huonw/swift
|
refs/heads/master
|
test/SwiftSyntax/DeserializeFile.swift
|
apache-2.0
|
3
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: OS=macosx
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
import SwiftSyntax
import SwiftLang
func getInput(_ file: String) -> URL {
var result = URL(fileURLWithPath: #file)
result.deleteLastPathComponent()
result.appendPathComponent("Inputs")
result.appendPathComponent(file)
return result
}
var DecodeTests = TestSuite("DecodeSyntax")
DecodeTests.test("Basic") {
expectDoesNotThrow({
let content = try SwiftLang.parse(getInput("visitor.swift"))
let source = try String(contentsOf: getInput("visitor.swift"))
let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content)
expectEqual("\(parsed)", source)
})
}
runAllTests()
|
8f5b173c0fad1952372560c10d115242
| 24.2 | 69 | 0.746032 | false | true | false | false |
Jnosh/swift
|
refs/heads/master
|
test/IRGen/objc.swift
|
apache-2.0
|
2
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[BLAMMO:%T4objc6BlammoC]] = type
// CHECK: [[MYBLAMMO:%T4objc8MyBlammoC]] = type
// CHECK: [[TEST2:%T4objc5Test2C]] = type
// CHECK: [[OBJC:%objc_object]] = type
// CHECK: [[ID:%T4objc2idV]] = type <{ %AnyObject }>
// CHECK: [[GIZMO:%TSo5GizmoC]] = type
// CHECK: [[RECT:%TSC4RectV]] = type
// CHECK: [[FLOAT:%TSf]] = type
// CHECK: @"\01L_selector_data(bar)" = private global [4 x i8] c"bar\00", section "__TEXT,__objc_methname,cstring_literals", align 1
// CHECK: @"\01L_selector(bar)" = private externally_initialized global i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(bar)", i64 0, i64 0), section "__DATA,__objc_selrefs,literal_pointers,no_dead_strip", align 8
// CHECK: @_T0SC4RectVMn = linkonce_odr hidden constant
// CHECK: @_T0SC4RectVN = linkonce_odr hidden global
// CHECK: @"\01L_selector_data(acquiesce)"
// CHECK-NOT: @"\01L_selector_data(disharmonize)"
// CHECK: @"\01L_selector_data(eviscerate)"
struct id {
var data : AnyObject
}
// Exporting something as [objc] doesn't make it an ObjC class.
@objc class Blammo {
}
// Class and methods are [objc] by inheritance.
class MyBlammo : Blammo {
func foo() {}
// CHECK: define hidden swiftcc void @_T04objc8MyBlammoC3fooyyF([[MYBLAMMO]]* swiftself) {{.*}} {
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: ret void
}
// Class and methods are [objc] by inheritance.
class Test2 : Gizmo {
func foo() {}
// CHECK: define hidden swiftcc void @_T04objc5Test2C3fooyyF([[TEST2]]* swiftself) {{.*}} {
// CHECK: call {{.*}} @objc_release
// CHECK: ret void
dynamic func bar() {}
}
// Test @nonobjc.
class Contrarian : Blammo {
func acquiesce() {}
@nonobjc func disharmonize() {}
@nonobjc func eviscerate() {}
}
class Octogenarian : Contrarian {
// Override of @nonobjc is @objc again unless made @nonobjc.
@nonobjc override func disharmonize() {}
// Override of @nonobjc can be @objc.
@objc override func eviscerate() {}
}
@_silgen_name("unknown")
func unknown(_ x: id) -> id
// CHECK: define hidden swiftcc %objc_object* @_T04objc5test0{{[_0-9a-zA-Z]*}}F(%objc_object*)
// CHECK-NOT: call {{.*}} @swift_unknownRetain
// CHECK: call {{.*}} @swift_unknownRetain
// CHECK-NOT: call {{.*}} @swift_unknownRelease
// CHECK: call {{.*}} @swift_unknownRelease
// CHECK: ret %objc_object*
func test0(_ arg: id) -> id {
var x : id
x = arg
unknown(x)
var y = x
return y
}
func test1(_ cell: Blammo) {}
// CHECK: define hidden swiftcc void @_T04objc5test1{{[_0-9a-zA-Z]*}}F([[BLAMMO]]*) {{.*}} {
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: ret void
// FIXME: These ownership convention tests should become SILGen tests.
func test2(_ v: Test2) { v.bar() }
func test3() -> NSObject {
return Gizmo()
}
// Normal message send with argument, no transfers.
func test5(_ g: Gizmo) {
Gizmo.inspect(g)
}
// The argument to consume: is __attribute__((ns_consumed)).
func test6(_ g: Gizmo) {
Gizmo.consume(g)
}
// fork is __attribute__((ns_consumes_self)).
func test7(_ g: Gizmo) {
g.fork()
}
// clone is __attribute__((ns_returns_retained)).
func test8(_ g: Gizmo) {
g.clone()
}
// duplicate has an object returned at +0.
func test9(_ g: Gizmo) {
g.duplicate()
}
func test10(_ g: Gizmo, r: Rect) {
Gizmo.run(with: r, andGizmo:g);
}
// Force the emission of the Rect metadata.
func test11_helper<T>(_ t: T) {}
// NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata.
// CHECK-LABEL: define hidden swiftcc void @_T04objc6test11ySC4RectVF
// CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_T0SC4RectVN
func test11(_ r: Rect) { test11_helper(r) }
class WeakObjC {
weak var obj: NSObject?
weak var id: AnyObject?
init() {
var foo = obj
var bar: AnyObject? = id
}
}
// rdar://17528908
// CHECK: i32 1, !"Objective-C Version", i32 2}
// CHECK: i32 1, !"Objective-C Image Info Version", i32 0}
// CHECK: i32 1, !"Objective-C Image Info Section", !"__DATA, __objc_imageinfo, regular, no_dead_strip"}
// 1280 == (5 << 8). 5 is the Swift ABI version.
// CHECK: i32 4, !"Objective-C Garbage Collection", i32 1280}
// CHECK: i32 1, !"Swift Version", i32 5}
|
a4285f9dda9170ef563eac6f83f5d632
| 29.972789 | 234 | 0.647924 | false | true | false | false |
ryanherman/intro
|
refs/heads/master
|
intro/LeftViewController.swift
|
mit
|
1
|
//
// LeftViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 12/3/14.
//
import UIKit
enum LeftMenu: Int {
case Main = 0
case Introduction
case Ask
case About
}
protocol LeftMenuProtocol : class {
func changeViewController(menu: LeftMenu)
}
class LeftViewController : UIViewController, LeftMenuProtocol {
@IBOutlet weak var tableView: UITableView!
var menus = ["Main", "Introduction", "Ask your Rabbi","About"]
var mainViewController: UIViewController!
var swiftViewController: UIViewController!
var aboutViewController: UIViewController!
var introductionViewController: UIViewController!
var askViewController: UIViewController!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1.0)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController
self.mainViewController = UINavigationController(rootViewController: mainViewController)
let introductionViewController = storyboard.instantiateViewControllerWithIdentifier("IntroductionViewController") as! IntroductionViewController
self.introductionViewController = UINavigationController(rootViewController: introductionViewController)
let aboutViewController = storyboard.instantiateViewControllerWithIdentifier("AboutViewController") as! AboutViewController
self.aboutViewController = UINavigationController(rootViewController: aboutViewController)
let askViewController = storyboard.instantiateViewControllerWithIdentifier("AskViewController") as! AskViewController
self.askViewController = UINavigationController(rootViewController: askViewController)
self.tableView.registerCellClass(BaseTableViewCell.self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: BaseTableViewCell = BaseTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: BaseTableViewCell.identifier)
cell.backgroundColor = UIColor(red: 64/255, green: 170/255, blue: 239/255, alpha: 1.0)
cell.textLabel?.font = UIFont.italicSystemFontOfSize(18)
cell.textLabel?.textColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
cell.textLabel?.text = menus[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let menu = LeftMenu(rawValue: indexPath.item) {
self.changeViewController(menu)
}
}
func changeViewController(menu: LeftMenu) {
switch menu {
case .Main:
self.slideMenuController()?.changeMainViewController(self.mainViewController, close: true)
case .Introduction:
self.slideMenuController()?.changeMainViewController(self.introductionViewController, close: true)
break
case .About:
self.slideMenuController()?.changeMainViewController(self.aboutViewController, close: true)
break
case .Ask:
self.slideMenuController()?.changeMainViewController(self.askViewController, close: true)
break
default:
break
}
}
}
|
b2f004efc7ff79f5fd787635c69feabe
| 37.979798 | 152 | 0.705547 | false | false | false | false |
criticalmaps/criticalmaps-ios
|
refs/heads/main
|
CriticalMapsKit/Sources/AppFeature/NetworkConnectionObserver.swift
|
mit
|
1
|
import ComposableArchitecture
import Foundation
import Logger
import PathMonitorClient
import SharedDependencies
public struct NetworkConnectionObserver: ReducerProtocol {
public init() {}
@Dependency(\.pathMonitorClient) public var pathMonitorClient
public struct State: Equatable {
var isNetworkAvailable = true
}
public enum Action: Equatable {
case observeConnection
case observeConnectionResponse(NetworkPath)
}
public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> {
switch action {
case .observeConnection:
return .run { send in
for await path in await pathMonitorClient.networkPathPublisher() {
await send(.observeConnectionResponse(path))
}
}
.cancellable(id: ObserveConnectionIdentifier())
case let .observeConnectionResponse(networkPath):
state.isNetworkAvailable = networkPath.status == .satisfied
SharedDependencies._isNetworkAvailable = state.isNetworkAvailable
logger.info("Is network available: \(state.isNetworkAvailable)")
return .none
}
}
}
struct ObserveConnectionIdentifier: Hashable {}
|
869c24c6c1f6c4391257f2a1ef212e71
| 27.756098 | 88 | 0.724343 | false | false | false | false |
behoernchen/Iconizer
|
refs/heads/master
|
Iconizer/Models/ContentsJSON.swift
|
mit
|
1
|
//
// JSONFile.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Raphael Hanneken
//
// 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 Cocoa
/// Reads and writes the Contents JSON files.
struct ContentsJSON {
/// Holds the image data from <AssetType>.json
var images: Array<[String : String]>
/// Holds the complete information required for Contents.json
var contents: [String : AnyObject] = [:]
// MARK: Initializers
/// Initializes the JSONData struct.
///
/// - returns: The initialized JSONData struct.
init() {
// Init the images array.
self.images = []
// Init the contents array, with general information.
self.contents["author"] = "Iconizer"
self.contents["version"] = "1.0"
self.contents["images"] = []
}
/// Initializes the JSONData struct with a specified AssetType and
/// selected platforms.
///
/// - parameter type: The AssetType for the required JSON data
/// - parameter platforms: Selected platforms
///
/// - returns: The initialized JSONData specified for an AssetType and platforms.
init(forType type: AssetType, andPlatforms platforms: [String]) {
// Basic initialization.
self.init()
// Initialize the data object.
for platform in platforms {
// Add the image information for each platform to our images array.
do {
images += try JSONObjectForType(type, andPlatform: platform)
} catch {
print(error)
}
}
}
// MARK: Methods
/// Gets the JSON data for the given AssetType.
///
/// - parameter type: AssetType to get the json file for.
///
/// - returns: The JSON data for the given AssetType.
func JSONObjectForType(type: AssetType, andPlatform platform: String) throws -> Array<[String : String]> {
// Holds the path to the required JSON file.
let resourcePath : String?
// Get the correct JSON file for the given AssetType.
switch (type) {
case .AppIcon:
resourcePath = NSBundle.mainBundle().pathForResource("AppIcon_" + platform, ofType: "json")
case .ImageSet:
resourcePath = NSBundle.mainBundle().pathForResource("ImageSet", ofType: "json")
case .LaunchImage:
resourcePath = NSBundle.mainBundle().pathForResource("LaunchImage_" + platform, ofType: "json")
}
// Unwrap the JSON file path.
guard let path = resourcePath else {
throw ContentsJSONError.FileNotFound
}
// Create a new NSData object from the contents of the selected JSON file.
let JSONData = try NSData(contentsOfFile: path, options: .DataReadingMappedAlways)
// Create a new JSON object from the given data.
let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .AllowFragments)
// Convert the JSON object into a Dictionary.
guard let contentsDict = JSONObject as? Dictionary<String, AnyObject> else {
throw ContentsJSONError.CastingJSONToDictionaryFailed
}
// Get the image information from the JSON dictionary.
guard let images = contentsDict["images"] as? Array<[String : String]> else {
throw ContentsJSONError.GettingImagesArrayFailed
}
// Return image information.
return images
}
/// Saves the Contents.json to the appropriate folder.
///
/// - parameter url: File url to save the Contents.json to.
mutating func saveToURL(url: NSURL) throws {
// Add the image information to the contents dictionary.
contents["images"] = images
// Serialize the contents as JSON object.
let data = try NSJSONSerialization.dataWithJSONObject(self.contents, options: .PrettyPrinted)
// Write the JSON object to the HD.
try data.writeToURL(url.URLByAppendingPathComponent("Contents.json", isDirectory: false), options: .DataWritingAtomic)
}
}
|
a70249b26924b50b1ab81c5cb43afeaf
| 34.122302 | 122 | 0.703195 | false | false | false | false |
shlyren/ONE-Swift
|
refs/heads/master
|
ONE_Swift/Classes/Main-主要/Controller/JENPastListViewController.swift
|
mit
|
1
|
//
// JENPastListViewController.swift
// ONE_Swift
//
// Created by 任玉祥 on 16/4/28.
// Copyright © 2016年 任玉祥. All rights reserved.
//
import UIKit
class JENPastListViewController: UITableViewController {
var endMonth = ""
var pastLists: [String] {
get {
return arrayFromStr(endMonth)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "往期列表"
}
private func arrayFromStr(endDate: String) -> [String] {
if !endDate.containsString("-") {return []}
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM"
var currentDate = formatter.stringFromDate(NSDate()) as NSString
let currentYear = currentDate.integerValue
let range = currentDate.rangeOfString("-")
if range.location != NSNotFound {
currentDate = currentDate.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "")
}
let currentMonth = currentDate.integerValue
var endDataStr = endDate as NSString
let endYear = endDataStr.integerValue
if range.location != NSNotFound {
endDataStr = endDataStr.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "")
}
let endMonth = endDataStr.integerValue
var maxMonth = 0
var minMonth = 0
var monthArr = [String]()
var resYear = currentYear
while resYear >= endYear {
maxMonth = resYear == currentYear ? currentMonth: 12;
minMonth = resYear == endYear ? endMonth: 1;
var resMonth = maxMonth
while resMonth >= minMonth {
monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth]))
resMonth -= 1
}
resYear -= 1
}
// for var resYear = currentYear; resYear >= endYear; resYear -= 1 {
// maxMonth = resYear == currentYear ? currentMonth: 12;
// minMonth = resYear == endYear ? endMonth: 1;
//
// for var resMonth = maxMonth; resMonth >= minMonth; resMonth -= 1 {
// monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth]))
// }
// }
return monthArr
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.tableViewWithNoData(nil, rowCount: pastLists.count)
return pastLists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
tableView.tableViewSetExtraCellLineHidden()
var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "reuseIdentifier")
}
if indexPath.row == 0 {
cell?.textLabel?.text = "本月"
} else {
cell?.textLabel?.text = pastLists[indexPath.row]
}
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
4654559f01cde6eb96e38cb93393226c
| 31.877358 | 135 | 0.588235 | false | false | false | false |
jonnguy/HSTracker
|
refs/heads/master
|
HSTracker/Logging/Parsers/TagChangeActions.swift
|
mit
|
1
|
//
// TagChanceActions.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
struct TagChangeActions {
func findAction(eventHandler: PowerEventHandler, tag: GameTag, id: Int, value: Int, prevValue: Int) -> (() -> Void)? {
switch tag {
case .zone: return { self.zoneChange(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue) }
case .playstate: return { self.playstateChange(eventHandler: eventHandler, id: id, value: value) }
case .cardtype: return { self.cardTypeChange(eventHandler: eventHandler, id: id, value: value) }
case .last_card_played: return { self.lastCardPlayedChange(eventHandler: eventHandler, value: value) }
case .defending: return { self.defendingChange(eventHandler: eventHandler, id: id, value: value) }
case .attacking: return { self.attackingChange(eventHandler: eventHandler, id: id, value: value) }
case .proposed_defender: return { self.proposedDefenderChange(eventHandler: eventHandler, value: value) }
case .proposed_attacker: return { self.proposedAttackerChange(eventHandler: eventHandler, value: value) }
case .predamage: return { self.predamageChange(eventHandler: eventHandler, id: id, value: value) }
case .num_turns_in_play: return { self.numTurnsInPlayChange(eventHandler: eventHandler, id: id, value: value) }
case .num_attacks_this_turn: return { self.numAttacksThisTurnChange(eventHandler: eventHandler, id: id, value: value) }
case .zone_position: return { self.zonePositionChange(eventHandler: eventHandler, id: id) }
case .card_target: return { self.cardTargetChange(eventHandler: eventHandler, id: id, value: value) }
//case .equipped_weapon: return { self.equippedWeaponChange(eventHandler: eventHandler, id: id, value: value) }
case .exhausted: return { self.exhaustedChange(eventHandler: eventHandler, id: id, value: value) }
case .controller:
return {
self.controllerChange(eventHandler: eventHandler, id: id, prevValue: prevValue, value: value)
}
case .fatigue: return { self.fatigueChange(eventHandler: eventHandler, value: value, id: id) }
case .step: return { self.stepChange(eventHandler: eventHandler) }
case .turn: return { self.turnChange(eventHandler: eventHandler) }
case .state: return { self.stateChange(eventHandler: eventHandler, value: value) }
case .transformed_from_card:
return {
self.transformedFromCardChange(eventHandler: eventHandler,
id: id,
value: value)
}
default: return nil
}
}
private func transformedFromCardChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == 0 { return }
guard let entity = eventHandler.entities[id] else { return }
entity.info.set(originalCardId: value)
}
private func lastCardPlayedChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.lastCardPlayed = value
guard let playerEntity = eventHandler.playerEntity else { return }
guard playerEntity.isCurrentPlayer else { return }
if let entity = eventHandler.entities[value] {
if !entity.isMinion {
return
}
// check if it is a magnet buff, rather than a minion
if entity.has(tag: GameTag.modular) {
let pos = entity.tags[GameTag.zone_position]!
let neighbor = eventHandler.player.board.first(where: { $0.tags[GameTag.zone_position] == pos + 1 })
if neighbor?.card.race == Race.mechanical {
return
}
}
eventHandler.playerMinionPlayed(entity: entity)
}
}
private func defendingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.defending(entity: value == 1 ? entity : nil)
}
private func attackingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.attacking(entity: value == 1 ? entity : nil)
}
private func proposedDefenderChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.proposedDefenderEntityId = value
}
private func proposedAttackerChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.proposedAttackerEntityId = value
}
private func predamageChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let playerEntity = eventHandler.playerEntity, let entity = eventHandler.entities[id] else { return }
if playerEntity.isCurrentPlayer {
eventHandler.opponentDamage(entity: entity)
}
}
private func numTurnsInPlayChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
eventHandler.turnsInPlayChange(entity: entity, turn: eventHandler.turnNumber())
}
private func fatigueChange(eventHandler: PowerEventHandler, value: Int, id: Int) {
guard let entity = eventHandler.entities[id] else { return }
let controller = entity[.controller]
if controller == eventHandler.player.id {
eventHandler.playerFatigue(value: value)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentFatigue(value: value)
}
}
private func controllerChange(eventHandler: PowerEventHandler, id: Int, prevValue: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
if prevValue <= 0 {
entity.info.originalController = value
return
}
guard !entity.has(tag: .player_id) else { return }
if value == eventHandler.player.id {
if entity.isInZone(zone: .secret) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
} else if value == eventHandler.opponent.id && prevValue != value {
if entity.isInZone(zone: .secret) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
}
}
private func exhaustedChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
guard entity[.cardtype] == CardType.hero_power.rawValue else { return }
}
private func equippedWeaponChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func cardTargetChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func zonePositionChange(eventHandler: PowerEventHandler, id: Int) {
}
private func numAttacksThisTurnChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func stateChange(eventHandler: PowerEventHandler, value: Int) {
if value != State.complete.rawValue {
return
}
eventHandler.gameEnd()
eventHandler.gameEnded = true
}
private func turnChange(eventHandler: PowerEventHandler) {
guard eventHandler.setupDone && eventHandler.playerEntity != nil else { return }
guard let playerEntity = eventHandler.playerEntity else { return }
let activePlayer: PlayerType = playerEntity.has(tag: .current_player) ? .player : .opponent
if activePlayer == .player {
eventHandler.playerUsedHeroPower = false
} else {
eventHandler.opponentUsedHeroPower = false
}
}
private func stepChange(eventHandler: PowerEventHandler) {
guard !eventHandler.setupDone && eventHandler.entities.first?.1.name == "GameEntity" else { return }
logger.info("Game was already in progress.")
eventHandler.wasInProgress = true
}
private func cardTypeChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == CardType.hero.rawValue {
setHeroAsync(eventHandler: eventHandler, id: id)
}
}
private func playstateChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == PlayState.conceded.rawValue {
eventHandler.concede()
}
guard !eventHandler.gameEnded else { return }
if let entity = eventHandler.entities[id], !entity.isPlayer(eventHandler: eventHandler) {
return
}
if let value = PlayState(rawValue: value) {
switch value {
case .won:
eventHandler.win()
case .lost:
eventHandler.loss()
case .tied:
eventHandler.tied()
default: break
}
}
}
private func zoneChange(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int) {
guard id > 3 else { return }
guard let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == nil {
if prevValue != Zone.invalid.rawValue && prevValue != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: prevValue)
} else if value != Zone.invalid.rawValue && value != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: value)
}
}
let controller = entity[.controller]
guard let zoneValue = Zone(rawValue: prevValue) else { return }
switch zoneValue {
case .deck:
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue,
controller: controller,
cardId: entity.cardId)
case .hand:
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .play:
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .secret:
zoneChangeFromSecret(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .invalid:
let maxId = getMaxHeroPowerId(eventHandler: eventHandler)
if !eventHandler.setupDone
&& (id <= maxId || eventHandler.gameEntity?[.step] == Step.invalid.rawValue
&& entity[.zone_position] < 5) {
entity.info.originalZone = .deck
simulateZoneChangesFromDeck(eventHandler: eventHandler, id: id, value: value,
cardId: entity.cardId, maxId: maxId)
} else {
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
}
case .graveyard, .setaside, .removedfromgame:
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value, prevValue: prevValue,
controller: controller, cardId: entity.cardId)
}
}
// The last heropower is created after the last hero, therefore +1
private func getMaxHeroPowerId(eventHandler: PowerEventHandler) -> Int {
return max(eventHandler.playerEntity?[.hero_entity] ?? 66,
eventHandler.opponentEntity?[.hero_entity] ?? 66) + 1
}
private func simulateZoneChangesFromDeck(eventHandler: PowerEventHandler, id: Int,
value: Int, cardId: String?, maxId: Int) {
if value == Zone.deck.rawValue {
return
}
guard let entity = eventHandler.entities[id] else { return }
if value == Zone.setaside.rawValue {
entity.info.created = true
return
}
if entity.isHero && !entity.isPlayableHero || entity.isHeroPower
|| entity.has(tag: .player_id) || entity[.cardtype] == CardType.game.rawValue
|| entity.has(tag: .creator) {
return
}
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: Zone.hand.rawValue,
prevValue: Zone.deck.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.hand.rawValue {
return
}
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: Zone.play.rawValue,
prevValue: Zone.hand.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.play.rawValue {
return
}
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value, prevValue: Zone.play.rawValue,
controller: entity[.controller], cardId: cardId)
}
private func zoneChangeFromOther(eventHandler: PowerEventHandler, id: Int, rawValue: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let value = Zone(rawValue: rawValue), let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == .deck && rawValue != Zone.deck.rawValue {
// This entity was moved from DECK to SETASIDE to HAND, e.g. by Tracking
entity.info.discarded = false
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: rawValue, prevValue: prevValue,
controller: controller, cardId: cardId)
return
}
entity.info.created = true
switch value {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .deck:
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.playerGetToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.opponentGetToDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerGet(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentGet(entity: entity, turn: eventHandler.turnNumber(), id: id)
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: -1,
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .setaside:
if controller == eventHandler.player.id {
eventHandler.playerCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
}
default:
break
}
}
private func zoneChangeFromSecret(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .secret, .graveyard:
if controller == eventHandler.opponent.id {
eventHandler.opponentSecretTrigger(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), otherId: id)
}
default:
break
}
}
private func zoneChangeFromPlay(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerBackToHand(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToHand(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), id: id)
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerPlayToGraveyard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber(), playersTurn: eventHandler.playerEntity?.isCurrentPlayer ?? false)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToGraveyard(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(),
playersTurn: eventHandler.playerEntity?.isCurrentPlayer ?? false)
}
case .removedfromgame, .setaside:
if controller == eventHandler.player.id {
eventHandler.playerRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
}
case .play:
break
default:
break
}
}
private func zoneChangeFromHand(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlay(entity: entity, cardId: cardId, from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .removedfromgame, .setaside, .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerHandDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentHandDiscard(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerMulligan(entity: entity, cardId: cardId)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentMulligan(entity: entity, from: entity[.zone_position])
}
default:
break
}
}
private func zoneChangeFromDeck(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerDraw(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDraw(entity: entity, turn: eventHandler.turnNumber())
}
case .setaside, .removedfromgame:
if !eventHandler.setupDone {
entity.info.created = true
return
}
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.playerRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.opponentRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .play:
if controller == eventHandler.player.id {
eventHandler.playerDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: -1, turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
default:
break
}
}
// TODO: this is essentially blocking the global queue!
private func setHeroAsync(eventHandler: PowerEventHandler, id: Int) {
logger.info("Found hero with id \(id) ")
DispatchQueue.global().async {
if eventHandler.playerEntity == nil {
logger.info("Waiting for playerEntity")
while eventHandler.playerEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let playerEntity = eventHandler.playerEntity,
let entity = eventHandler.entities[id] {
logger.info("playerEntity found playerClass : "
+ "\(String(describing: eventHandler.player.playerClass)), "
+ "\(id) -> \(playerEntity[.hero_entity]) -> \(entity) ")
if id == playerEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(playerHero: cardId)
}
return
}
}
if eventHandler.opponentEntity == nil {
logger.info("Waiting for opponentEntity")
while eventHandler.opponentEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let opponentEntity = eventHandler.opponentEntity,
let entity = eventHandler.entities[id] {
logger.info("opponentEntity found playerClass : "
+ "\(String(describing: eventHandler.opponent.playerClass)),"
+ " \(id) -> \(opponentEntity[.hero_entity]) -> \(entity) ")
if id == opponentEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(opponentHero: cardId)
}
return
}
}
}
}
}
|
9f237f2607fb1a19946f758d8a48e9aa
| 44.897227 | 181 | 0.571104 | false | false | false | false |
featherweightlabs/FeatherweightRouter
|
refs/heads/master
|
Tests/CachedPresenterTests.swift
|
apache-2.0
|
1
|
import XCTest
@testable import FeatherweightRouter
class CachedPresenterTests: XCTestCase {
typealias TestPresenter = Presenter<ViewController>
class ViewController {
init() {}
}
func testCreation() {
var callCount = 0
let presenter: TestPresenter = cachedPresenter { () -> ViewController in
callCount += 1
return ViewController()
}
XCTAssertEqual(callCount, 0)
var x: ViewController! = presenter.presentable
XCTAssertEqual(callCount, 1)
var y: ViewController! = presenter.presentable
XCTAssertEqual(callCount, 1)
XCTAssert(x === y)
x = nil
y = nil
x = presenter.presentable
XCTAssertEqual(callCount, 2)
y = presenter.presentable
XCTAssertEqual(callCount, 2)
XCTAssert(x === y)
}
}
|
55a2810ad8a05a83328108178e564806
| 23.166667 | 80 | 0.610345 | false | true | false | false |
hooman/swift
|
refs/heads/main
|
stdlib/public/core/Sequence.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that supplies the values of a sequence one at a time.
///
/// The `IteratorProtocol` protocol is tightly linked with the `Sequence`
/// protocol. Sequences provide access to their elements by creating an
/// iterator, which keeps track of its iteration process and returns one
/// element at a time as it advances through the sequence.
///
/// Whenever you use a `for`-`in` loop with an array, set, or any other
/// collection or sequence, you're using that type's iterator. Swift uses a
/// sequence's or collection's iterator internally to enable the `for`-`in`
/// loop language construct.
///
/// Using a sequence's iterator directly gives you access to the same elements
/// in the same order as iterating over that sequence using a `for`-`in` loop.
/// For example, you might typically use a `for`-`in` loop to print each of
/// the elements in an array.
///
/// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
/// for animal in animals {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// Behind the scenes, Swift uses the `animals` array's iterator to loop over
/// the contents of the array.
///
/// var animalIterator = animals.makeIterator()
/// while let animal = animalIterator.next() {
/// print(animal)
/// }
/// // Prints "Antelope"
/// // Prints "Butterfly"
/// // Prints "Camel"
/// // Prints "Dolphin"
///
/// The call to `animals.makeIterator()` returns an instance of the array's
/// iterator. Next, the `while` loop calls the iterator's `next()` method
/// repeatedly, binding each element that is returned to `animal` and exiting
/// when the `next()` method returns `nil`.
///
/// Using Iterators Directly
/// ========================
///
/// You rarely need to use iterators directly, because a `for`-`in` loop is the
/// more idiomatic approach to traversing a sequence in Swift. Some
/// algorithms, however, may call for direct iterator use.
///
/// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)`
/// method defined in the standard library, which takes an initial value and a
/// combining closure, `reduce1(_:)` uses the first element of the sequence as
/// the initial value.
///
/// Here's an implementation of the `reduce1(_:)` method. The sequence's
/// iterator is used directly to retrieve the initial value before looping
/// over the rest of the sequence.
///
/// extension Sequence {
/// func reduce1(
/// _ nextPartialResult: (Element, Element) -> Element
/// ) -> Element?
/// {
/// var i = makeIterator()
/// guard var accumulated = i.next() else {
/// return nil
/// }
///
/// while let element = i.next() {
/// accumulated = nextPartialResult(accumulated, element)
/// }
/// return accumulated
/// }
/// }
///
/// The `reduce1(_:)` method makes certain kinds of sequence operations
/// simpler. Here's how to find the longest string in a sequence, using the
/// `animals` array introduced earlier as an example:
///
/// let longestAnimal = animals.reduce1 { current, element in
/// if current.count > element.count {
/// return current
/// } else {
/// return element
/// }
/// }
/// print(longestAnimal)
/// // Prints Optional("Butterfly")
///
/// Using Multiple Iterators
/// ========================
///
/// Whenever you use multiple iterators (or `for`-`in` loops) over a single
/// sequence, be sure you know that the specific sequence supports repeated
/// iteration, either because you know its concrete type or because the
/// sequence is also constrained to the `Collection` protocol.
///
/// Obtain each separate iterator from separate calls to the sequence's
/// `makeIterator()` method rather than by copying. Copying an iterator is
/// safe, but advancing one copy of an iterator by calling its `next()` method
/// may invalidate other copies of that iterator. `for`-`in` loops are safe in
/// this regard.
///
/// Adding IteratorProtocol Conformance to Your Type
/// ================================================
///
/// Implementing an iterator that conforms to `IteratorProtocol` is simple.
/// Declare a `next()` method that advances one step in the related sequence
/// and returns the current element. When the sequence has been exhausted, the
/// `next()` method returns `nil`.
///
/// For example, consider a custom `Countdown` sequence. You can initialize the
/// `Countdown` sequence with a starting integer and then iterate over the
/// count down to zero. The `Countdown` structure's definition is short: It
/// contains only the starting count and the `makeIterator()` method required
/// by the `Sequence` protocol.
///
/// struct Countdown: Sequence {
/// let start: Int
///
/// func makeIterator() -> CountdownIterator {
/// return CountdownIterator(self)
/// }
/// }
///
/// The `makeIterator()` method returns another custom type, an iterator named
/// `CountdownIterator`. The `CountdownIterator` type keeps track of both the
/// `Countdown` sequence that it's iterating and the number of times it has
/// returned a value.
///
/// struct CountdownIterator: IteratorProtocol {
/// let countdown: Countdown
/// var times = 0
///
/// init(_ countdown: Countdown) {
/// self.countdown = countdown
/// }
///
/// mutating func next() -> Int? {
/// let nextNumber = countdown.start - times
/// guard nextNumber > 0
/// else { return nil }
///
/// times += 1
/// return nextNumber
/// }
/// }
///
/// Each time the `next()` method is called on a `CountdownIterator` instance,
/// it calculates the new next value, checks to see whether it has reached
/// zero, and then returns either the number, or `nil` if the iterator is
/// finished returning elements of the sequence.
///
/// Creating and iterating over a `Countdown` sequence uses a
/// `CountdownIterator` to handle the iteration.
///
/// let threeTwoOne = Countdown(start: 3)
/// for count in threeTwoOne {
/// print("\(count)...")
/// }
/// // Prints "3..."
/// // Prints "2..."
/// // Prints "1..."
public protocol IteratorProtocol {
/// The type of element traversed by the iterator.
associatedtype Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying sequence. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// You must not call this method if any other copy of this iterator has been
/// advanced with a call to its `next()` method.
///
/// The following example shows how an iterator can be used explicitly to
/// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and
/// then call the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
mutating func next() -> Element?
}
/// A type that provides sequential, iterated access to its elements.
///
/// A sequence is a list of values that you can step through one at a time. The
/// most common way to iterate over the elements of a sequence is to use a
/// `for`-`in` loop:
///
/// let oneTwoThree = 1...3
/// for number in oneTwoThree {
/// print(number)
/// }
/// // Prints "1"
/// // Prints "2"
/// // Prints "3"
///
/// While seemingly simple, this capability gives you access to a large number
/// of operations that you can perform on any sequence. As an example, to
/// check whether a sequence includes a particular value, you can test each
/// value sequentially until you've found a match or reached the end of the
/// sequence. This example checks to see whether a particular insect is in an
/// array.
///
/// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// var hasMosquito = false
/// for bug in bugs {
/// if bug == "Mosquito" {
/// hasMosquito = true
/// break
/// }
/// }
/// print("'bugs' has a mosquito: \(hasMosquito)")
/// // Prints "'bugs' has a mosquito: false"
///
/// The `Sequence` protocol provides default implementations for many common
/// operations that depend on sequential access to a sequence's values. For
/// clearer, more concise code, the example above could use the array's
/// `contains(_:)` method, which every sequence inherits from `Sequence`,
/// instead of iterating manually:
///
/// if bugs.contains("Mosquito") {
/// print("Break out the bug spray.")
/// } else {
/// print("Whew, no mosquitos!")
/// }
/// // Prints "Whew, no mosquitos!"
///
/// Repeated Access
/// ===============
///
/// The `Sequence` protocol makes no requirement on conforming types regarding
/// whether they will be destructively consumed by iteration. As a
/// consequence, don't assume that multiple `for`-`in` loops on a sequence
/// will either resume iteration or restart from the beginning:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // No defined behavior
/// }
///
/// In this case, you cannot assume either that a sequence will be consumable
/// and will resume iteration, or that a sequence is a collection and will
/// restart iteration from the first element. A conforming sequence that is
/// not a collection is allowed to produce an arbitrary sequence of elements
/// in the second `for`-`in` loop.
///
/// To establish that a type you've created supports nondestructive iteration,
/// add conformance to the `Collection` protocol.
///
/// Conforming to the Sequence Protocol
/// ===================================
///
/// Making your own custom types conform to `Sequence` enables many useful
/// operations, like `for`-`in` looping and the `contains` method, without
/// much effort. To add `Sequence` conformance to your own custom type, add a
/// `makeIterator()` method that returns an iterator.
///
/// Alternatively, if your type can act as its own iterator, implementing the
/// requirements of the `IteratorProtocol` protocol and declaring conformance
/// to both `Sequence` and `IteratorProtocol` are sufficient.
///
/// Here's a definition of a `Countdown` sequence that serves as its own
/// iterator. The `makeIterator()` method is provided as a default
/// implementation.
///
/// struct Countdown: Sequence, IteratorProtocol {
/// var count: Int
///
/// mutating func next() -> Int? {
/// if count == 0 {
/// return nil
/// } else {
/// defer { count -= 1 }
/// return count
/// }
/// }
/// }
///
/// let threeToGo = Countdown(count: 3)
/// for i in threeToGo {
/// print(i)
/// }
/// // Prints "3"
/// // Prints "2"
/// // Prints "1"
///
/// Expected Performance
/// ====================
///
/// A sequence should provide its iterator in O(1). The `Sequence` protocol
/// makes no other requirements about element access, so routines that
/// traverse a sequence should be considered O(*n*) unless documented
/// otherwise.
public protocol Sequence {
/// A type representing the sequence's elements.
associatedtype Element
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator: IteratorProtocol where Iterator.Element == Element
/// A type that represents a subsequence of some of the sequence's elements.
// associatedtype SubSequence: Sequence = AnySequence<Element>
// where Element == SubSequence.Element,
// SubSequence.SubSequence == SubSequence
// typealias SubSequence = AnySequence<Element>
/// Returns an iterator over the elements of this sequence.
__consuming func makeIterator() -> Iterator
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
var underestimatedCount: Int { get }
func _customContainsEquatableElement(
_ element: Element
) -> Bool?
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
__consuming func _copyToContiguousArray() -> ContiguousArray<Element>
/// Copy `self` into an unsafe buffer, initializing its memory.
///
/// The default implementation simply iterates over the elements of the
/// sequence, initializing the buffer one item at a time.
///
/// For sequences whose elements are stored in contiguous chunks of memory,
/// it may be more efficient to copy them in bulk, using the
/// `UnsafeMutablePointer.initialize(from:count:)` method.
///
/// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The
/// buffer must be of sufficient size to accommodate
/// `source.underestimatedCount` elements. (Some implementations trap
/// if given a buffer that's smaller than this.)
///
/// - Returns: `(it, c)`, where `c` is the number of elements copied into the
/// buffer, and `it` is a partially consumed iterator that can be used to
/// retrieve elements that did not fit into the buffer (if any). (This can
/// only happen if `underestimatedCount` turned out to be an actual
/// underestimate, and the buffer did not contain enough space to hold the
/// entire sequence.)
///
/// On return, the memory region in `buffer[0 ..< c]` is initialized to
/// the first `c` elements in the sequence.
__consuming func _copyContents(
initializing ptr: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)
/// Call `body(p)`, where `p` is a pointer to the collection's
/// contiguous storage. If no such storage exists, it is
/// first created. If the collection does not support an internal
/// representation in a form of contiguous storage, `body` is not
/// called and `nil` is returned.
///
/// A `Collection` that provides its own implementation of this method
/// must also guarantee that an equivalent buffer of its `SubSequence`
/// can be generated by advancing the pointer by the distance to the
/// slice's `startIndex`.
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R?
}
// Provides a default associated type witness for Iterator when the
// Self type is both a Sequence and an Iterator.
extension Sequence where Self: IteratorProtocol {
// @_implements(Sequence, Iterator)
public typealias _Default_Iterator = Self
}
/// A default makeIterator() function for `IteratorProtocol` instances that
/// are declared to conform to `Sequence`
extension Sequence where Self.Iterator == Self {
/// Returns an iterator over the elements of this sequence.
@inlinable
public __consuming func makeIterator() -> Self {
return self
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropFirstSequence<Base: Sequence> {
@usableFromInline
internal let _base: Base
@usableFromInline
internal let _limit: Int
@inlinable
public init(_ base: Base, dropping limit: Int) {
_precondition(limit >= 0,
"Can't drop a negative number of elements from a sequence")
_base = base
_limit = limit
}
}
extension DropFirstSequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = Base.Iterator
public typealias SubSequence = AnySequence<Element>
@inlinable
public __consuming func makeIterator() -> Iterator {
var it = _base.makeIterator()
var dropped = 0
while dropped < _limit, it.next() != nil { dropped &+= 1 }
return it
}
@inlinable
public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
return DropFirstSequence(_base, dropping: _limit + k)
}
}
/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` iterator.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct PrefixSequence<Base: Sequence> {
@usableFromInline
internal var _base: Base
@usableFromInline
internal let _maxLength: Int
@inlinable
public init(_ base: Base, maxLength: Int) {
_precondition(maxLength >= 0, "Can't take a prefix of negative length")
_base = base
_maxLength = maxLength
}
}
extension PrefixSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal var _remaining: Int
@inlinable
internal init(_ base: Base.Iterator, maxLength: Int) {
_base = base
_remaining = maxLength
}
}
}
extension PrefixSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element
@inlinable
public mutating func next() -> Element? {
if _remaining != 0 {
_remaining &-= 1
return _base.next()
} else {
return nil
}
}
}
extension PrefixSequence: Sequence {
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base.makeIterator(), maxLength: _maxLength)
}
@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> {
let length = Swift.min(maxLength, self._maxLength)
return PrefixSequence(_base, maxLength: length)
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
@frozen
public struct DropWhileSequence<Base: Sequence> {
public typealias Element = Base.Element
@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?
@inlinable
internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows {
_iterator = iterator
_nextElement = _iterator.next()
while let x = _nextElement, try predicate(x) {
_nextElement = _iterator.next()
}
}
@inlinable
internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows {
self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate)
}
}
extension DropWhileSequence {
@frozen
public struct Iterator {
@usableFromInline
internal var _iterator: Base.Iterator
@usableFromInline
internal var _nextElement: Element?
@inlinable
internal init(_ iterator: Base.Iterator, nextElement: Element?) {
_iterator = iterator
_nextElement = nextElement
}
}
}
extension DropWhileSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element
@inlinable
public mutating func next() -> Element? {
guard let next = _nextElement else { return nil }
_nextElement = _iterator.next()
return next
}
}
extension DropWhileSequence: Sequence {
@inlinable
public func makeIterator() -> Iterator {
return Iterator(_iterator, nextElement: _nextElement)
}
@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Base> {
guard let x = _nextElement, try predicate(x) else { return self }
return try DropWhileSequence(iterator: _iterator, predicate: predicate)
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Sequence
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)
var iterator = self.makeIterator()
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `isIncluded` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try isIncluded(element) {
result.append(element)
}
}
return Array(result)
}
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
@inlinable
public var underestimatedCount: Int {
return 0
}
@inlinable
@inline(__always)
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}
/// Calls the given closure on each element in the sequence in the same order
/// as a `for`-`in` loop.
///
/// The two loops in the following example produce the same output:
///
/// let numberWords = ["one", "two", "three"]
/// for word in numberWords {
/// print(word)
/// }
/// // Prints "one"
/// // Prints "two"
/// // Prints "three"
///
/// numberWords.forEach { word in
/// print(word)
/// }
/// // Same as above
///
/// Using the `forEach` method is distinct from a `for`-`in` loop in two
/// important ways:
///
/// 1. You cannot use a `break` or `continue` statement to exit the current
/// call of the `body` closure or skip subsequent calls.
/// 2. Using the `return` statement in the `body` closure will exit only from
/// the current call to `body`, not from any outer scope, and won't skip
/// subsequent calls.
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
@_semantics("sequence.forEach")
@inlinable
public func forEach(
_ body: (Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}
extension Sequence {
/// Returns the first element of the sequence that satisfies the given
/// predicate.
///
/// The following example uses the `first(where:)` method to find the first
/// negative number in an array of integers:
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// if let firstNegative = numbers.first(where: { $0 < 0 }) {
/// print("The first negative number is \(firstNegative).")
/// }
/// // Prints "The first negative number is -2."
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element is a match.
/// - Returns: The first element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func first(
where predicate: (Element) throws -> Bool
) rethrows -> Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
extension Sequence where Element: Equatable {
/// Returns the longest possible subsequences of the sequence, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the sequence and for each instance of `separator` at the
/// start or end of the sequence. If `true`, only nonempty subsequences
/// are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [ArraySlice<Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Sequence {
/// Returns the longest possible subsequences of the sequence, in order, that
/// don't contain elements satisfying the given predicate. Elements that are
/// used to split the sequence are not returned as part of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(
/// line.split(maxSplits: 1, whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `true` for the `allowEmptySlices` parameter, so
/// the returned array contains empty strings where spaces were repeated.
///
/// print(
/// line.split(
/// omittingEmptySubsequences: false,
/// whereSeparator: { $0 == " " }
/// ).map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the sequence, or one
/// less than the number of subsequences to return. If `maxSplits + 1`
/// subsequences are returned, the last one is a suffix of the original
/// sequence containing the remaining elements. `maxSplits` must be
/// greater than or equal to zero. The default value is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` predicate.
/// If `true`, only nonempty subsequences are returned. The default
/// value is `true`.
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [ArraySlice<Element>] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
let whole = Array(self)
return try whole.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator)
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the sequence.
///
/// The sequence must be finite. If the maximum length exceeds the number of
/// elements in the sequence, the result contains all the elements in the
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func suffix(_ maxLength: Int) -> [Element] {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
guard maxLength != 0 else { return [] }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into a copy and return it.
// This saves memory for sequences particularly longer than `maxLength`.
var ringBuffer = ContiguousArray<Element>()
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
var i = 0
for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = (i + 1) % maxLength
}
}
if i != ringBuffer.startIndex {
var rotated = ContiguousArray<Element>()
rotated.reserveCapacity(ringBuffer.count)
rotated += ringBuffer[i..<ringBuffer.endIndex]
rotated += ringBuffer[0..<i]
return Array(rotated)
} else {
return Array(ringBuffer)
}
}
/// Returns a sequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the sequence, the result is an empty sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter k: The number of elements to drop from the beginning of
/// the sequence. `k` must be greater than or equal to zero.
/// - Returns: A sequence starting after the specified number of
/// elements.
///
/// - Complexity: O(1), with O(*k*) deferred to each iteration of the result,
/// where *k* is the number of elements to drop from the beginning of
/// the sequence.
@inlinable
public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> {
return DropFirstSequence(self, dropping: k)
}
/// Returns a sequence containing all but the given number of final
/// elements.
///
/// The sequence must be finite. If the number of elements to drop exceeds
/// the number of elements in the sequence, the result is an empty
/// sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// sequence. `n` must be greater than or equal to zero.
/// - Returns: A sequence leaving off the specified number of elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func dropLast(_ k: Int = 1) -> [Element] {
_precondition(k >= 0, "Can't drop a negative number of elements from a sequence")
guard k != 0 else { return Array(self) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= k. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `k` * sizeof(Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result = ContiguousArray<Element>()
var ringBuffer = ContiguousArray<Element>()
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < k {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = (i + 1) % k
}
}
return Array(result)
}
/// Returns a sequence by skipping the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `drop(while:)` method to skip over the
/// positive numbers at the beginning of the `numbers` array. The result
/// begins with the first element of `numbers` that does not satisfy
/// `predicate`.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let startingWithNegative = numbers.drop(while: { $0 > 0 })
/// // startingWithNegative == [-2, 9, -6, 10, 1]
///
/// If `predicate` matches every element in the sequence, the result is an
/// empty sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence starting after the initial, consecutive elements
/// that satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the number of elements to drop from
/// the beginning of the sequence.
@inlinable
public __consuming func drop(
while predicate: (Element) throws -> Bool
) rethrows -> DropWhileSequence<Self> {
return try DropWhileSequence(self, predicate: predicate)
}
/// Returns a sequence, up to the specified maximum length, containing the
/// initial elements of the sequence.
///
/// If the maximum length exceeds the number of elements in the sequence,
/// the result contains all the elements in the sequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A sequence starting at the beginning of this sequence
/// with at most `maxLength` elements.
///
/// - Complexity: O(1)
@inlinable
public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> {
return PrefixSequence(self, maxLength: maxLength)
}
/// Returns a sequence containing the initial, consecutive elements that
/// satisfy the given predicate.
///
/// The following example uses the `prefix(while:)` method to find the
/// positive numbers at the beginning of the `numbers` array. Every element
/// of `numbers` up to, but not including, the first negative value is
/// included in the result.
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// let positivePrefix = numbers.prefix(while: { $0 > 0 })
/// // positivePrefix == [3, 7, 4]
///
/// If `predicate` matches every element in the sequence, the resulting
/// sequence contains every element of the sequence.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element should be included in the result.
/// - Returns: A sequence of the initial, consecutive elements that
/// satisfy `predicate`.
///
/// - Complexity: O(*k*), where *k* is the length of the result.
@inlinable
public __consuming func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
for element in self {
guard try predicate(element) else {
break
}
result.append(element)
}
return Array(result)
}
}
extension Sequence {
/// Copy `self` into an unsafe buffer, initializing its memory.
///
/// The default implementation simply iterates over the elements of the
/// sequence, initializing the buffer one item at a time.
///
/// For sequences whose elements are stored in contiguous chunks of memory,
/// it may be more efficient to copy them in bulk, using the
/// `UnsafeMutablePointer.initialize(from:count:)` method.
///
/// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The
/// buffer must be of sufficient size to accommodate
/// `source.underestimatedCount` elements. (Some implementations trap
/// if given a buffer that's smaller than this.)
///
/// - Returns: `(it, c)`, where `c` is the number of elements copied into the
/// buffer, and `it` is a partially consumed iterator that can be used to
/// retrieve elements that did not fit into the buffer (if any). (This can
/// only happen if `underestimatedCount` turned out to be an actual
/// underestimate, and the buffer did not contain enough space to hold the
/// entire sequence.)
///
/// On return, the memory region in `buffer[0 ..< c]` is initialized to
/// the first `c` elements in the sequence.
@inlinable
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
return _copySequenceContents(initializing: buffer)
}
@_alwaysEmitIntoClient
internal __consuming func _copySequenceContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
var it = self.makeIterator()
guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) }
for idx in buffer.startIndex..<buffer.count {
guard let x = it.next() else {
return (it, idx)
}
ptr.initialize(to: x)
ptr += 1
}
return (it,buffer.endIndex)
}
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
}
// FIXME(ABI)#182
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness"
/// A sequence built around an iterator of type `Base`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
@frozen
public struct IteratorSequence<Base: IteratorProtocol> {
@usableFromInline
internal var _base: Base
/// Creates an instance whose iterator is a copy of `base`.
@inlinable
public init(_ base: Base) {
_base = base
}
}
extension IteratorSequence: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable
public mutating func next() -> Base.Element? {
return _base.next()
}
}
extension IteratorSequence: Sendable where Base: Sendable { }
/* FIXME: ideally for compatibility we would declare
extension Sequence {
@available(swift, deprecated: 5, message: "")
public typealias SubSequence = AnySequence<Element>
}
*/
|
17943a0da206d1d4997d31825582cae0
| 36.060181 | 100 | 0.6409 | false | false | false | false |
nodes-ios/Blobfish
|
refs/heads/master
|
Blobfish/Classes/Reachability.swift
|
mit
|
1
|
/*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Reachability.swift version 2.2beta2
import SystemConfiguration
import Foundation
public enum ReachabilityError: ErrorProtocol {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
public let ReachabilityChangedNotification = "ReachabilityChangedNotification" as NSNotification.Name
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(OpaquePointer(info)).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged(flags:flags)
}
}
public class Reachability: NSObject {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
public var description: String {
switch self {
case .ReachableViaWWAN:
return "Cellular"
case .ReachableViaWiFi:
return "WiFi"
case .NotReachable:
return "No Connection"
}
}
}
// MARK: - *** Public properties ***
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
public var notificationCenter = NotificationCenter.default
public var currentReachabilityStatus: NetworkStatus {
if isReachable() {
if isReachableViaWiFi() {
return .ReachableViaWiFi
}
if isRunningOnDevice {
return .ReachableViaWWAN
}
}
return .NotReachable
}
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
private var previousFlags: SCNetworkReachabilityFlags?
// MARK: - *** Initialisation methods ***
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init(hostname: String) throws {
guard let nodename = (hostname as NSString).utf8String,
ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) }
self.init(reachabilityRef: ref)
}
public class func reachabilityForInternetConnection() throws -> Reachability {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let ref = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { throw ReachabilityError.FailedToCreateWithAddress(zeroAddress) }
return Reachability(reachabilityRef: ref)
}
public class func reachabilityForLocalWiFi() throws -> Reachability {
var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
let address: UInt32 = 0xA9FE0000
localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian)
guard let ref = withUnsafePointer(&localWifiAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { throw ReachabilityError.FailedToCreateWithAddress(localWifiAddress) }
return Reachability(reachabilityRef: ref)
}
// MARK: - *** Notifier methods ***
public func startNotifier() throws {
guard let reachabilityRef = reachabilityRef where !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer<Void>(OpaquePointer(bitPattern: Unmanaged<Reachability>.passUnretained(self)))
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an intial check
reachabilitySerialQueue.async {
let flags = self.reachabilityFlags
self.reachabilityChanged(flags: flags)
}
notifierRunning = true
}
public func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
public func isReachable() -> Bool {
let flags = reachabilityFlags
return isReachableWithFlags(flags:flags)
}
public func isReachableViaWWAN() -> Bool {
let flags = reachabilityFlags
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachable(flags:flags) && isOnWWAN(flags:flags)
}
public func isReachableViaWiFi() -> Bool {
let flags = reachabilityFlags
// Check we're reachable
if !isReachable(flags:flags) {
return false
}
// Must be on WiFi if reachable but not on an iOS device (i.e. simulator)
if !isRunningOnDevice {
return true
}
// Check we're NOT on WWAN
return !isOnWWAN(flags:flags)
}
// MARK: - *** Private methods ***
private var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
private var notifierRunning = false
private var reachabilityRef: SCNetworkReachability?
private let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", attributes: .serial, target: nil)
private func reachabilityChanged(flags:SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
if isReachableWithFlags(flags:flags) {
if let block = whenReachable {
block(self)
}
} else {
if let block = whenUnreachable {
block(self)
}
}
notificationCenter.post(name: ReachabilityChangedNotification, object:self)
previousFlags = flags
}
private func isReachableWithFlags(flags:SCNetworkReachabilityFlags) -> Bool {
if !isReachable(flags: flags) {
return false
}
if isConnectionRequiredOrTransient(flags: flags) {
return false
}
if isRunningOnDevice {
if isOnWWAN(flags: flags) && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
private func isConnectionRequired() -> Bool {
return connectionRequired()
}
private func connectionRequired() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags: flags)
}
// Dynamic, on demand connection?
private func isConnectionOnDemand() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags: flags) && isConnectionOnTrafficOrDemand(flags: flags)
}
// Is user intervention required?
private func isInterventionRequired() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags: flags) && isInterventionRequired(flags: flags)
}
private func isOnWWAN(flags:SCNetworkReachabilityFlags) -> Bool {
#if os(iOS)
return flags.contains(.iswwan)
#else
return false
#endif
}
private func isReachable(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.reachable)
}
private func isConnectionRequired(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.connectionRequired)
}
private func isInterventionRequired(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.interventionRequired)
}
private func isConnectionOnTraffic(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.connectionOnTraffic)
}
private func isConnectionOnDemand(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.connectionOnDemand)
}
func isConnectionOnTrafficOrDemand(flags:SCNetworkReachabilityFlags) -> Bool {
return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
private func isTransientConnection(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.transientConnection)
}
private func isLocalAddress(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.isLocalAddress)
}
private func isDirect(flags:SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.isDirect)
}
private func isConnectionRequiredOrTransient(flags:SCNetworkReachabilityFlags) -> Bool {
let testcase:SCNetworkReachabilityFlags = [.connectionRequired, .transientConnection]
return flags.intersection(testcase) == testcase
}
private var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(&flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
override public var description: String {
var W: String
if isRunningOnDevice {
W = isOnWWAN(flags: reachabilityFlags) ? "W" : "-"
} else {
W = "X"
}
let R = isReachable(flags: reachabilityFlags) ? "R" : "-"
let c = isConnectionRequired(flags: reachabilityFlags) ? "c" : "-"
let t = isTransientConnection(flags: reachabilityFlags) ? "t" : "-"
let i = isInterventionRequired(flags: reachabilityFlags) ? "i" : "-"
let C = isConnectionOnTraffic(flags: reachabilityFlags) ? "C" : "-"
let D = isConnectionOnDemand(flags: reachabilityFlags) ? "D" : "-"
let l = isLocalAddress(flags: reachabilityFlags) ? "l" : "-"
let d = isDirect(flags: reachabilityFlags) ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
|
b1fe81159b46f58f0512df5072a1bc0d
| 34.420054 | 196 | 0.661821 | false | false | false | false |
CosmicMind/Motion
|
refs/heads/develop
|
Pods/Motion/Sources/Extensions/Motion+CALayer.swift
|
gpl-3.0
|
3
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
internal extension CALayer {
/// Swizzle the `add(_:forKey:) selector.
static var motionAddedAnimations: [(CALayer, String, CAAnimation)]? = {
let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in
if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
swizzling(CALayer.self, #selector(add(_:forKey:)), #selector(motionAdd(anim:forKey:)))
return nil
}()
@objc
dynamic func motionAdd(anim: CAAnimation, forKey: String?) {
if nil == CALayer.motionAddedAnimations {
motionAdd(anim: anim, forKey: forKey)
} else {
let copiedAnim = anim.copy() as! CAAnimation
copiedAnim.delegate = nil // having delegate resulted some weird animation behavior
CALayer.motionAddedAnimations?.append((self, forKey!, copiedAnim))
}
}
/// Retrieves all currently running animations for the layer.
var animations: [(String, CAAnimation)] {
guard let keys = animationKeys() else {
return []
}
return keys.map {
return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation)
}
}
/**
Concats transforms and returns the result.
- Parameters layer: A CALayer.
- Returns: A CATransform3D.
*/
func flatTransformTo(layer: CALayer) -> CATransform3D {
var l = layer
var t = l.transform
while let sl = l.superlayer, self != sl {
t = CATransform3DConcat(sl.transform, t)
l = sl
}
return t
}
/// Removes all Motion animations.
func removeAllMotionAnimations() {
guard let keys = animationKeys() else {
return
}
for animationKey in keys where animationKey.hasPrefix("motion.") {
removeAnimation(forKey: animationKey)
}
}
}
public extension CALayer {
/**
A function that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
func animate(_ animations: CAAnimation...) {
animate(animations)
}
/**
A function that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
func animate(_ animations: [CAAnimation]) {
for animation in animations {
if let a = animation as? CABasicAnimation {
a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!)
}
updateModel(animation)
if let a = animation as? CAPropertyAnimation {
add(a, forKey: a.keyPath!)
} else if let a = animation as? CAAnimationGroup {
add(a, forKey: nil)
} else if let a = animation as? CATransition {
add(a, forKey: kCATransition)
}
}
}
/**
A function that accepts a list of MotionAnimation values and executes them.
- Parameter animations: A list of MotionAnimation values.
*/
func animate(_ animations: MotionAnimation...) {
animate(animations)
}
/**
A function that accepts an Array of MotionAnimation values and executes them.
- Parameter animations: An Array of MotionAnimation values.
- Parameter completion: An optional completion block.
*/
func animate(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) {
startAnimations(animations, completion: completion)
}
}
fileprivate extension CALayer {
/**
A function that executes an Array of MotionAnimation values.
- Parameter _ animations: An Array of MotionAnimations.
- Parameter completion: An optional completion block.
*/
func startAnimations(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) {
let ts = MotionAnimationState(animations: animations)
Motion.delay(ts.delay) { [weak self,
ts = ts,
completion = completion] in
guard let `self` = self else {
return
}
var anims = [CABasicAnimation]()
var duration = 0 == ts.duration ? 0.01 : ts.duration
if let v = ts.backgroundColor {
let a = MotionCAAnimation.background(color: UIColor(cgColor: v))
a.fromValue = self.backgroundColor
anims.append(a)
}
if let v = ts.borderColor {
let a = MotionCAAnimation.border(color: UIColor(cgColor: v))
a.fromValue = self.borderColor
anims.append(a)
}
if let v = ts.borderWidth {
let a = MotionCAAnimation.border(width: v)
a.fromValue = NSNumber(floatLiteral: Double(self.borderWidth))
anims.append(a)
}
if let v = ts.cornerRadius {
let a = MotionCAAnimation.corner(radius: v)
a.fromValue = NSNumber(floatLiteral: Double(self.cornerRadius))
anims.append(a)
}
if let v = ts.transform {
let a = MotionCAAnimation.transform(v)
a.fromValue = NSValue(caTransform3D: self.transform)
anims.append(a)
}
if let v = ts.spin {
var a = MotionCAAnimation.spin(x: v.x)
a.fromValue = NSNumber(floatLiteral: 0)
anims.append(a)
a = MotionCAAnimation.spin(y: v.y)
a.fromValue = NSNumber(floatLiteral: 0)
anims.append(a)
a = MotionCAAnimation.spin(z: v.z)
a.fromValue = NSNumber(floatLiteral: 0)
anims.append(a)
}
if let v = ts.position {
let a = MotionCAAnimation.position(v)
a.fromValue = NSValue(cgPoint: self.position)
anims.append(a)
}
if let v = ts.opacity {
let a = MotionCAAnimation.fade(v)
a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.opacity.rawValue) ?? NSNumber(floatLiteral: 1)
anims.append(a)
}
if let v = ts.zPosition {
let a = MotionCAAnimation.zPosition(v)
a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.zPosition.rawValue) ?? NSNumber(floatLiteral: 0)
anims.append(a)
}
if let v = ts.size {
let a = MotionCAAnimation.size(v)
a.fromValue = NSValue(cgSize: self.bounds.size)
anims.append(a)
}
if let v = ts.shadowPath {
let a = MotionCAAnimation.shadow(path: v)
a.fromValue = self.shadowPath
anims.append(a)
}
if let v = ts.shadowColor {
let a = MotionCAAnimation.shadow(color: UIColor(cgColor: v))
a.fromValue = self.shadowColor
anims.append(a)
}
if let v = ts.shadowOffset {
let a = MotionCAAnimation.shadow(offset: v)
a.fromValue = NSValue(cgSize: self.shadowOffset)
anims.append(a)
}
if let v = ts.shadowOpacity {
let a = MotionCAAnimation.shadow(opacity: v)
a.fromValue = NSNumber(floatLiteral: Double(self.shadowOpacity))
anims.append(a)
}
if let v = ts.shadowRadius {
let a = MotionCAAnimation.shadow(radius: v)
a.fromValue = NSNumber(floatLiteral: Double(self.shadowRadius))
anims.append(a)
}
if #available(iOS 9.0, *), let (stiffness, damping) = ts.spring {
for i in 0..<anims.count where nil != anims[i].keyPath {
let v = anims[i]
guard "cornerRadius" != v.keyPath else {
continue
}
let a = MotionCAAnimation.convert(animation: v, stiffness: stiffness, damping: damping)
anims[i] = a
if a.settlingDuration > duration {
duration = a.settlingDuration
}
}
}
let g = Motion.animate(group: anims, timingFunction: ts.timingFunction, duration: duration)
self.animate(g)
if let v = ts.completion {
Motion.delay(duration, execute: v)
}
if let v = completion {
Motion.delay(duration, execute: v)
}
}
}
}
private extension CALayer {
/**
Updates the model with values provided in animation.
- Parameter animation: A CAAnimation.
*/
func updateModel(_ animation: CAAnimation) {
if let a = animation as? CABasicAnimation {
setValue(a.toValue, forKeyPath: a.keyPath!)
} else if let a = animation as? CAAnimationGroup {
a.animations?.forEach {
updateModel($0)
}
}
}
}
|
abd74b1213d973680720522290509605
| 30.633987 | 157 | 0.631302 | false | false | false | false |
tobbi/projectgenerator
|
refs/heads/master
|
target_includes/ios_bridges/Button.swift
|
gpl-2.0
|
1
|
//
// Button.swift
// MobileApplicationsSwiftAufgabe1
//
// Created by Tobias Markus on 21.04.15.
// Copyright (c) 2015 Tobias Markus. All rights reserved.
//
import Foundation
import UIKit
/**
* Class that represents a button
* @author tobiasmarkus
*/
public class Button {
private var innerButton: UIButton;
private var x: CGFloat = 0, y: CGFloat = 0;
/**
* Specifies the place where the textfield goes.
*/
private var parentUIContext: UIViewController;
/**
* Specifies the place where the handlers are defined
*/
private var parentEventContext: UIResponder;
/**
* Public constructor of class "Button"
*/
public init(context: UIViewController!, eventContext: UIResponder!)
{
// Set parent context:
self.parentUIContext = context;
self.parentEventContext = eventContext;
// Initialize button
self.innerButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30));
// Set the default look for this button
self.innerButton.backgroundColor = UIColor.whiteColor();
self.innerButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
self.innerButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Selected);
self.innerButton.layer.borderWidth = 1;
self.innerButton.layer.cornerRadius = 5;
if let titleLabel = self.innerButton.titleLabel
{
titleLabel.font = UIFont(name: "Arial", size: 12);
}
}
/**
* Returns the label for this button
* @return String The label for this element
*/
public func getLabel() -> String
{
if let titleLabel = self.innerButton.titleLabel
{
if let text = titleLabel.text
{
return text;
}
}
return "";
}
/**
* Sets the label for this button
* @param String The label to set
*/
public func setLabel(label: String)
{
self.innerButton.setTitle(label, forState: UIControlState.Normal);
}
/**
* Sets the size of this element
* @param width The width of this element in percent
* @param height The height of this element in percent
*/
public func setSize(width: CGFloat, height: CGFloat)
{
var screenWidth = (self.parentUIContext as! ApplicationView).getWidth();
var screenHeight = (self.parentUIContext as! ApplicationView).getHeight();
var newWidth = (screenWidth / 100) * width;
var newHeight = (screenHeight / 100) * height;
self.innerButton.frame = CGRectMake(self.x, self.y, newWidth, newHeight);
}
/**
* Sets the size of this element
* @param width The width of this element in percent
* @param height The height of this element in percent
*/
public func setSize(width: Int, height: Int)
{
var f_width = CGFloat(width);
var f_height = CGFloat(height);
setSize(f_width, height: f_height);
}
/**
* Sets the position of this element
* @param x The x position of this element
* @param y The y position of this element
*/
public func setPosition(x: CGFloat, y: CGFloat)
{
var screenWidth = (self.parentUIContext as! ApplicationView).getWidth();
var screenHeight = (self.parentUIContext as! ApplicationView).getHeight();
var newX = (screenWidth / 100) * x;
var newY = (screenHeight / 100) * y;
self.x = newX;
self.y = newY;
self.innerButton.frame = CGRectMake(newX, newY, self.innerButton.frame.width, self.innerButton.frame.height);
}
/**
* Sets the position of this element
* @param x The x position of this element
* @param y The y position of this element
*/
public func setPosition(x: Int, y: Int)
{
var f_x = CGFloat(x);
var f_y = CGFloat(y);
setPosition(f_x, y: f_y);
}
/**
* Gets the wrapped element
*/
public func getWrappedElement() -> UIButton
{
return innerButton;
}
/**
* Adds this button to the specified application view
*/
public func addToApplicationView()
{
parentUIContext.view.addSubview(getWrappedElement());
}
/**
* Adds an onClick listener to this button
* @param listenerName Function name of the listener
*/
public func addOnClickListener(methodName: String) {
// add a target
innerButton.addTarget(parentEventContext, action: Selector(methodName + ":"), forControlEvents: UIControlEvents.TouchUpInside);
}
}
|
7afa9ac6e9305c87a6721d65ebd04ee9
| 28.08642 | 135 | 0.614601 | false | false | false | false |
mirrorinf/Mathematicus
|
refs/heads/master
|
Mathematicus/Polynomial.swift
|
apache-2.0
|
1
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
public struct Polynomial<Field: Number> {
public var coffcient: [Int : Field]
public internal(set) var maxexp: Int
public static func identityPolynomial() -> Polynomial<Field> {
return Polynomial<Field>(coffcient: [1 : Field.identity], maxexp: 1)
}
public static func zeroPolynomial() -> Polynomial<Field> {
return Polynomial<Field>(coffcient: [0 : Field.zero], maxexp: 0)
}
public static func constantPolynomial(c: Field) -> Polynomial<Field> {
return Polynomial<Field>(coffcient: [0 : c], maxexp: 0)
}
public static func findOrder<T>(of p: [Int : T], maxiumTrial: Int) -> Int {
for i in (1...maxiumTrial).reversed() {
if p[i] != nil {
return i
}
}
return 0
}
}
public func +<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> {
let e = max(lhs.maxexp, rhs.maxexp)
var coff: [Int : U] = [ : ]
for i in 0...e {
if lhs.coffcient[i] != nil {
coff[i] = lhs.coffcient[i]!
if rhs.coffcient[i] != nil {
coff[i] = rhs.coffcient[i]! + coff[i]!
}
} else {
coff[i] = rhs.coffcient[i]
}
if let j = coff[i] {
if j == U.zero {
coff[i] = nil
}
}
}
var rst = Polynomial<U>.identityPolynomial()
rst.coffcient = coff
rst.maxexp = Polynomial<U>.findOrder(of: coff, maxiumTrial: e)
return rst
}
public func *<U>(lhs: U, rhs: Polynomial<U>) -> Polynomial<U> {
if lhs == U.zero {
return Polynomial<U>.zeroPolynomial()
}
var newcoff = rhs.coffcient
for i in 0...rhs.maxexp {
if let c = newcoff[i] {
newcoff[i] = c * lhs
}
}
return Polynomial<U>(coffcient: newcoff, maxexp: rhs.maxexp)
}
public func *<U>(lhs: Polynomial<U>, rhs: U) -> Polynomial<U> {
return rhs * lhs
}
public func *<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> {
var rst = Polynomial<U>.zeroPolynomial()
for (i, c) in lhs.coffcient {
var newcoff: [Int : U] = [ : ]
for (j, m) in rhs.coffcient {
newcoff[i + j] = c * m
}
let newpoly = Polynomial<U>(coffcient: newcoff, maxexp: rhs.maxexp + i)
rst = rst + newpoly
}
return rst
}
public func -<U>(lhs: Polynomial<U>, rhs: Polynomial<U>) -> Polynomial<U> {
let minusOne = -U.identity
let s = minusOne * rhs
return lhs + s
}
public extension Polynomial {
func evaluate(at x: Field) -> Field {
var rst = Field.zero
var run = Field.identity
for i in 0...self.maxexp {
if let c = self.coffcient[i] {
rst = rst + c * run
}
run = run * x
}
return rst
}
}
public extension Polynomial {
func isZeroPolynomial() -> Bool {
let n = self.maxexp
var s: [Field] = [Field.randomElement()]
for _ in 0..<n {
var flag = true
var new: Field = Field.randomElement()
while flag {
flag = s.map { $0 == new }
.reduce(false) {
$0 || $1
}
new = Field.randomElement()
}
s.append(new)
}
let test = s.map { self.evaluate(at: $0) }.map { $0 == Field.zero }
.reduce(true) {
$0 && $1
}
return test
}
}
|
3072282dd2e4a36eb5fa9c27321395ec
| 25.034965 | 76 | 0.641955 | false | false | false | false |
nakau1/Formations
|
refs/heads/master
|
Formations/Sources/Models/Json.swift
|
apache-2.0
|
1
|
// =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import UIKit
enum Json: FileType {
case formation(teamId: String)
var directory: String {
switch self {
case .formation:
return "formations"
}
}
var name: String {
switch self {
case let .formation(teamId): return teamId
}
}
var extensionName: String {
return "json"
}
}
extension Json {
func save(_ jsonString: String?) {
makeDirectoryIfNeeded()
if let string = jsonString {
try? string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8)
} else {
delete()
}
}
func load() -> String? {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return nil }
return String(data: data, encoding: .utf8)
}
}
|
8789d750c336174f0cb09922cb0dade8
| 23.795455 | 96 | 0.472044 | false | false | false | false |
radvansky-tomas/NutriFacts
|
refs/heads/master
|
nutri-facts/nutri-facts/Model/User.swift
|
gpl-2.0
|
1
|
//
// User.swift
// nutri-facts
//
// Created by Tomas Radvansky on 20/05/2015.
// Copyright (c) 2015 Tomas Radvansky. All rights reserved.
//
import UIKit
import RealmSwift
class User: Object {
dynamic var userID:Int = 0
dynamic var gender:Bool = false
dynamic var age:Int = 0
dynamic var height:Int = 0
dynamic var weight:Double = 0.0
dynamic var desiredWeight:Double = 0.0
override static func primaryKey() -> String? {
return "userID"
}
}
|
12696ae1aeac0a21fd8e03e5c04019aa
| 20.478261 | 60 | 0.651822 | false | false | false | false |
samodom/TestableUIKit
|
refs/heads/master
|
TestableUIKit/UIResponder/UIView/UITableView/UITableViewReloadDataSpy.swift
|
mit
|
1
|
//
// UITableViewReloadDataSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/22/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
import TestSwagger
public extension UITableView {
private static let reloadDataCalledString = UUIDKeyString()
private static let reloadDataCalledKey = ObjectAssociationKey(reloadDataCalledString)
private static let reloadDataCalledReference = SpyEvidenceReference(key: reloadDataCalledKey)
/// Spy controller for ensuring a table view has had `reloadData` called on it.
public enum ReloadDataSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UITableView.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(UITableView.reloadData),
spy: #selector(UITableView.spy_reloadData)
)
] as Set
public static let evidence = [reloadDataCalledReference] as Set
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `reloadData`
public func spy_reloadData() {
reloadDataCalled = true
spy_reloadData()
}
/// Indicates whether the `reloadData` method has been called on this object.
public final var reloadDataCalled: Bool {
get {
return loadEvidence(with: UITableView.reloadDataCalledReference) as? Bool ?? false
}
set {
saveEvidence(true, with: UITableView.reloadDataCalledReference)
}
}
}
|
27a70e3bec52f59b92eaf8c29410283e
| 30.660377 | 97 | 0.67938 | false | false | false | false |
Minitour/WWDC-Collaborators
|
refs/heads/master
|
Macintosh.playground/Sources/Interface/OSApplicationWindow.swift
|
mit
|
1
|
import UIKit
public protocol OSApplicationWindowDelegate{
/// Delegate function called when window is about to be dragged.
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - container: The application's view.
func applicationWindow(_ applicationWindow: OSApplicationWindow, willStartDraggingContainer container: UIView)
/// Delegate function called when window has finished dragging
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - container: The application's view.
func applicationWindow(_ applicationWindow: OSApplicationWindow, didFinishDraggingContainer container: UIView)
/// Delegate function, called when users taps the panel of the OSApplicationWindow.
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - panel: The window panel view instance that was tapped.
/// - point: The location of the tap.
func applicationWindow(_ applicationWindow: OSApplicationWindow, didTapWindowPanel panel: WindowPanel,atPoint point: CGPoint)
/// Delegate function, called when user clicks the "close" button in the panel.
///
/// - Parameters:
/// - application: The current application window.
/// - panel: The window panel view instance which holds the button that was clicked.
func applicationWindow(_ application: OSApplicationWindow, didCloseWindowWithPanel panel: WindowPanel)
/// Delegate function, called after user has finished dragging. note that `point` parameter is an `inout`. This is to allow the class which conforms to this delegate the option to modify the point incase the point that was given isn't good.
///
/// - Parameters:
/// - application: The current application window.
/// - point: The panel which the user dragged with.
/// - Returns: return true to allow the movment of the window to the point, and false to ignore the movment.
func applicationWindow(_ application: OSApplicationWindow, canMoveToPoint point: inout CGPoint)->Bool
}
public class OSApplicationWindow: UIView{
fileprivate var lastLocation = CGPoint(x: 0, y: 0)
open var windowOrigin: MacAppDesktopView?
open var delegate: OSApplicationWindowDelegate?
open var dataSource: MacApp?{
didSet{
tabBar?.contentStyle = dataSource?.contentMode
tabBar?.requestContentStyleUpdate()
windowTitle = dataSource?.windowTitle
backgroundColor = dataSource?.contentMode ?? .default == .default ? .white : .black
}
}
open var container: UIView?
open var windowTitle: String?{
set{
tabBar?.title = newValue
}get{
return tabBar?.title
}
}
open var containerSize: CGSize?{
return dataSource?.sizeForWindow()
}
fileprivate (set) open var tabBar: WindowPanel?{
didSet{
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:)))
tabBar?.addGestureRecognizer(gestureRecognizer)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
tabBar?.addGestureRecognizer(tapGesture)
}
}
fileprivate var transitionWindowFrame: MovingWindow?
public convenience init(delegate: OSApplicationWindowDelegate,dataSource: MacApp){
self.init()
self.delegate = delegate
self.dataSource = dataSource
tabBar?.contentStyle = self.dataSource?.contentMode
tabBar?.requestContentStyleUpdate()
windowTitle = self.dataSource?.windowTitle
backgroundColor = self.dataSource?.contentMode ?? .default == .default ? .white : .black
}
public convenience init(){
self.init(frame: CGRect.zero)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleTap(sender: UITapGestureRecognizer){
delegate?.applicationWindow(self, didTapWindowPanel: tabBar!, atPoint: sender.location(in: tabBar))
}
func handlePan(sender: UIPanGestureRecognizer){
if dataSource?.shouldDragApplication == false{
return
}
let translation = sender.translation(in: self.superview!)
switch sender.state{
case .began:
transitionWindowFrame?.isHidden = false
transitionWindowFrame?.frame = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size)
transitionWindowFrame?.lastLocation = (self.transitionWindowFrame?.center)!
delegate?.applicationWindow(self, willStartDraggingContainer: container!)
dataSource?.macApp(self, willStartDraggingContainer: container!)
break
case .ended:
transitionWindowFrame?.isHidden = true
var point = convert(transitionWindowFrame!.center, to: superview!)
if delegate?.applicationWindow(self, canMoveToPoint: &point) ?? true{
self.center = point
}
delegate?.applicationWindow(self, didFinishDraggingContainer: container!)
dataSource?.macApp(self, didFinishDraggingContainer: container!)
return
default:
break
}
let point = CGPoint(x: (transitionWindowFrame?.lastLocation.x)! + translation.x , y: (transitionWindowFrame?.lastLocation.y)! + translation.y)
transitionWindowFrame?.layer.shadowOpacity = 0
transitionWindowFrame?.center = point
}
func setup(){
backgroundColor = .white
tabBar = WindowPanel()
tabBar?.backgroundColor = .clear
tabBar?.delegate = self
addSubview(tabBar!)
container = UIView()
container?.backgroundColor = .clear
addSubview(container!)
transitionWindowFrame = MovingWindow()
transitionWindowFrame?.isHidden = true
transitionWindowFrame?.backgroundColor = .clear
addSubview(transitionWindowFrame!)
}
override public func layoutSubviews() {
super.layoutSubviews()
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 5
self.layer.cornerRadius = 2
transitionWindowFrame?.bounds = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size)
frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0) + CGFloat(20))
tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20)
container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0)
}
public override func didMoveToSuperview() {
tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20)
tabBar?.setNeedsDisplay()
container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0)
frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0 ) + CGFloat(20))
if let view = dataSource?.container{
view.frame = container!.bounds
container!.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true
view.leftAnchor.constraint(equalTo: container!.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: container!.rightAnchor).isActive = true
}
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
lastLocation = self.center
super.touchesBegan(touches, with: event)
}
open func close(){
self.dataSource?.willTerminateApplication()
self.delegate?.applicationWindow(self, didCloseWindowWithPanel: tabBar!)
self.removeFromSuperview()
}
}
public class MovingWindow: UIView{
var lastLocation = CGPoint(x: 0, y: 0)
open var borderColor: UIColor = .gray
override public func draw(_ rect: CGRect) {
borderColor.setStroke()
let path = UIBezierPath(rect: rect)
path.lineWidth = 4
path.stroke()
}
}
extension OSApplicationWindow: WindowPanelDelegate{
public func didSelectCloseMenu(_ windowPanel: WindowPanel, panelButton button: PanelButton) {
self.dataSource?.willTerminateApplication()
self.delegate?.applicationWindow(self, didCloseWindowWithPanel: windowPanel)
self.removeFromSuperview()
}
}
|
a2bdc2f685102b25bc98454776fb0ffe
| 37.236515 | 244 | 0.648508 | false | false | false | false |
YQqiang/Nunchakus
|
refs/heads/master
|
Pods/BMPlayer/BMPlayer/Classes/BMPlayerControlView.swift
|
mit
|
1
|
//
// BMPlayerControlView.swift
// Pods
//
// Created by BrikerMan on 16/4/29.
//
//
import UIKit
import NVActivityIndicatorView
@objc public protocol BMPlayerControlViewDelegate: class {
/**
call when control view choose a definition
- parameter controlView: control view
- parameter index: index of definition
*/
func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int)
/**
call when control view pressed an button
- parameter controlView: control view
- parameter button: button type
*/
func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton)
/**
call when slider action trigged
- parameter controlView: control view
- parameter slider: progress slider
- parameter event: action
*/
func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents)
/**
call when needs to change playback rate
- parameter controlView: control view
- parameter rate: playback rate
*/
@objc optional func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float)
}
open class BMPlayerControlView: UIView {
open weak var delegate: BMPlayerControlViewDelegate?
// MARK: Variables
open var resource: BMPlayerResource?
open var selectedIndex = 0
open var isFullscreen = false
open var isMaskShowing = true
open var totalDuration:TimeInterval = 0
open var delayItem: DispatchWorkItem?
var playerLastState: BMPlayerState = .notSetURL
fileprivate var isSelectecDefitionViewOpened = false
// MARK: UI Components
/// main views which contains the topMaskView and bottom mask view
open var mainMaskView = UIView()
open var topMaskView = UIView()
open var bottomMaskView = UIView()
/// Image view to show video cover
open var maskImageView = UIImageView()
/// top views
open var backButton = UIButton(type : UIButtonType.custom)
open var titleLabel = UILabel()
open var chooseDefitionView = UIView()
/// bottom view
open var currentTimeLabel = UILabel()
open var totalTimeLabel = UILabel()
/// Progress slider
open var timeSlider = BMTimeSlider()
/// load progress view
open var progressView = UIProgressView()
/* play button
playButton.isSelected = player.isPlaying
*/
open var playButton = UIButton(type: UIButtonType.custom)
/* fullScreen button
fullScreenButton.isSelected = player.isFullscreen
*/
open var fullscreenButton = UIButton(type: UIButtonType.custom)
open var subtitleLabel = UILabel()
open var subtitleBackView = UIView()
open var subtileAttrabute: [String : Any]?
/// Activty Indector for loading
open var loadingIndector = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
open var seekToView = UIView()
open var seekToViewImage = UIImageView()
open var seekToLabel = UILabel()
open var replayButton = UIButton(type: UIButtonType.custom)
/// Gesture used to show / hide control view
open var tapGesture: UITapGestureRecognizer!
// MARK: - handle player state change
/**
call on when play time changed, update duration here
- parameter currentTime: current play time
- parameter totalTime: total duration
*/
open func playTimeDidChange(currentTime: TimeInterval, totalTime: TimeInterval) {
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
totalTimeLabel.text = BMPlayer.formatSecondsToString(totalTime)
timeSlider.value = Float(currentTime) / Float(totalTime)
if let subtitle = resource?.subtitle {
showSubtile(from: subtitle, at: currentTime)
}
}
/**
call on load duration changed, update load progressView here
- parameter loadedDuration: loaded duration
- parameter totalDuration: total duration
*/
open func loadedTimeDidChange(loadedDuration: TimeInterval , totalDuration: TimeInterval) {
progressView.setProgress(Float(loadedDuration)/Float(totalDuration), animated: true)
}
open func playerStateDidChange(state: BMPlayerState) {
switch state {
case .readyToPlay:
hideLoader()
case .buffering:
showLoader()
case .bufferFinished:
hideLoader()
case .playedToTheEnd:
playButton.isSelected = false
showPlayToTheEndView()
controlViewAnimation(isShow: true)
cancelAutoFadeOutAnimation()
default:
break
}
playerLastState = state
}
/**
Call when User use the slide to seek function
- parameter toSecound: target time
- parameter totalDuration: total duration of the video
- parameter isAdd: isAdd
*/
open func showSeekToView(to toSecound: TimeInterval, total totalDuration:TimeInterval, isAdd: Bool) {
seekToView.isHidden = false
seekToLabel.text = BMPlayer.formatSecondsToString(toSecound)
let rotate = isAdd ? 0 : CGFloat(Double.pi)
seekToViewImage.transform = CGAffineTransform(rotationAngle: rotate)
let targetTime = BMPlayer.formatSecondsToString(toSecound)
timeSlider.value = Float(toSecound / totalDuration)
currentTimeLabel.text = targetTime
}
// MARK: - UI update related function
/**
Update UI details when player set with the resource
- parameter resource: video resouce
- parameter index: defualt definition's index
*/
open func prepareUI(for resource: BMPlayerResource, selectedIndex index: Int) {
self.resource = resource
self.selectedIndex = index
titleLabel.text = resource.name
prepareChooseDefinitionView()
autoFadeOutControlViewWithAnimation()
}
open func playStateDidChange(isPlaying: Bool) {
autoFadeOutControlViewWithAnimation()
playButton.isSelected = isPlaying
}
/**
auto fade out controll view with animtion
*/
open func autoFadeOutControlViewWithAnimation() {
cancelAutoFadeOutAnimation()
delayItem = DispatchWorkItem {
self.controlViewAnimation(isShow: false)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + BMPlayerConf.animateDelayTimeInterval,
execute: delayItem!)
}
/**
cancel auto fade out controll view with animtion
*/
open func cancelAutoFadeOutAnimation() {
delayItem?.cancel()
}
/**
Implement of the control view animation, override if need's custom animation
- parameter isShow: is to show the controlview
*/
open func controlViewAnimation(isShow: Bool) {
let alpha: CGFloat = isShow ? 1.0 : 0.0
self.isMaskShowing = isShow
UIApplication.shared.setStatusBarHidden(!isShow, with: .fade)
UIView.animate(withDuration: 0.3, animations: {
self.topMaskView.alpha = alpha
self.bottomMaskView.alpha = alpha
self.mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: isShow ? 0.4 : 0.0)
if isShow {
if self.isFullscreen { self.chooseDefitionView.alpha = 1.0 }
} else {
self.replayButton.isHidden = true
self.chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(35)
}
self.chooseDefitionView.alpha = 0.0
}
self.layoutIfNeeded()
}) { (_) in
if isShow {
self.autoFadeOutControlViewWithAnimation()
}
}
}
/**
Implement of the UI update when screen orient changed
- parameter isForFullScreen: is for full screen
*/
open func updateUI(_ isForFullScreen: Bool) {
isFullscreen = isForFullScreen
fullscreenButton.isSelected = isForFullScreen
chooseDefitionView.isHidden = !isForFullScreen
if isForFullScreen {
if BMPlayerConf.topBarShowInCase.rawValue == 2 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
} else {
if BMPlayerConf.topBarShowInCase.rawValue >= 1 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
}
}
/**
Call when video play's to the end, override if you need custom UI or animation when played to the end
*/
open func showPlayToTheEndView() {
replayButton.isHidden = false
}
open func hidePlayToTheEndView() {
replayButton.isHidden = true
}
open func showLoader() {
loadingIndector.isHidden = false
loadingIndector.startAnimating()
}
open func hideLoader() {
loadingIndector.isHidden = true
}
open func hideSeekToView() {
seekToView.isHidden = true
}
open func showCoverWithLink(_ cover:String) {
self.showCover(url: URL(string: cover))
}
open func showCover(url: URL?) {
if let url = url {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async(execute: {
if let data = data {
self.maskImageView.image = UIImage(data: data)
} else {
self.maskImageView.image = nil
}
self.hideLoader()
});
}
}
}
open func hideCoverImageView() {
self.maskImageView.isHidden = true
}
open func prepareChooseDefinitionView() {
guard let resource = resource else {
return
}
for item in chooseDefitionView.subviews {
item.removeFromSuperview()
}
for i in 0..<resource.definitions.count {
let button = BMPlayerClearityChooseButton()
if i == 0 {
button.tag = selectedIndex
} else if i <= selectedIndex {
button.tag = i - 1
} else {
button.tag = i
}
button.setTitle("\(resource.definitions[button.tag].definition)", for: UIControlState())
chooseDefitionView.addSubview(button)
button.addTarget(self, action: #selector(self.onDefinitionSelected(_:)), for: UIControlEvents.touchUpInside)
button.snp.makeConstraints({ (make) in
make.top.equalTo(chooseDefitionView.snp.top).offset(35 * i)
make.width.equalTo(50)
make.height.equalTo(25)
make.centerX.equalTo(chooseDefitionView)
})
if resource.definitions.count == 1 {
button.isEnabled = false
}
}
}
// MARK: - Action Response
/**
Call when some action button Pressed
- parameter button: action Button
*/
open func onButtonPressed(_ button: UIButton) {
autoFadeOutControlViewWithAnimation()
if let type = ButtonType(rawValue: button.tag) {
switch type {
case .play, .replay:
if playerLastState == .playedToTheEnd {
hidePlayToTheEndView()
}
default:
break
}
}
delegate?.controlView(controlView: self, didPressButton: button)
}
/**
Call when the tap gesture tapped
- parameter gesture: tap gesture
*/
open func onTapGestureTapped(_ gesture: UITapGestureRecognizer) {
if playerLastState == .playedToTheEnd {
return
}
controlViewAnimation(isShow: !isMaskShowing)
}
// MARK: - handle UI slider actions
@objc func progressSliderTouchBegan(_ sender: UISlider) {
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchDown)
}
@objc func progressSliderValueChanged(_ sender: UISlider) {
hidePlayToTheEndView()
cancelAutoFadeOutAnimation()
let currentTime = Double(sender.value) * totalDuration
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .valueChanged)
}
@objc func progressSliderTouchEnded(_ sender: UISlider) {
autoFadeOutControlViewWithAnimation()
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchUpInside)
}
// MARK: - private functions
fileprivate func showSubtile(from subtitle: BMSubtitles, at time: TimeInterval) {
if let group = subtitle.search(for: time) {
subtitleBackView.isHidden = false
subtitleLabel.attributedText = NSAttributedString(string: group.text,
attributes: subtileAttrabute)
} else {
subtitleBackView.isHidden = true
}
}
@objc fileprivate func onDefinitionSelected(_ button:UIButton) {
let height = isSelectecDefitionViewOpened ? 35 : resource!.definitions.count * 40
chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
})
isSelectecDefitionViewOpened = !isSelectecDefitionViewOpened
if selectedIndex != button.tag {
selectedIndex = button.tag
delegate?.controlView(controlView: self, didChooseDefition: button.tag)
}
prepareChooseDefinitionView()
}
@objc fileprivate func onReplyButtonPressed() {
replayButton.isHidden = true
}
// MARK: - Init
override public init(frame: CGRect) {
super.init(frame: frame)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
/// Add Customize functions here
open func customizeUIComponents() {
}
func setupUIComponents() {
// Subtile view
subtitleLabel.numberOfLines = 0
subtitleLabel.textAlignment = .center
subtitleLabel.textColor = UIColor.white
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.minimumScaleFactor = 0.5
subtitleLabel.font = UIFont.systemFont(ofSize: 13)
subtitleBackView.layer.cornerRadius = 2
subtitleBackView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
subtitleBackView.addSubview(subtitleLabel)
subtitleBackView.isHidden = true
addSubview(subtitleBackView)
// Main mask view
addSubview(mainMaskView)
mainMaskView.addSubview(topMaskView)
mainMaskView.addSubview(bottomMaskView)
mainMaskView.insertSubview(maskImageView, at: 0)
mainMaskView.clipsToBounds = true
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 )
// Top views
topMaskView.addSubview(backButton)
topMaskView.addSubview(titleLabel)
addSubview(chooseDefitionView)
backButton.tag = BMPlayerControlView.ButtonType.back.rawValue
backButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_back"), for: .normal)
backButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
titleLabel.textColor = UIColor.white
titleLabel.text = ""
titleLabel.font = UIFont.systemFont(ofSize: 16)
chooseDefitionView.clipsToBounds = true
// Bottom views
bottomMaskView.addSubview(playButton)
bottomMaskView.addSubview(currentTimeLabel)
bottomMaskView.addSubview(totalTimeLabel)
bottomMaskView.addSubview(progressView)
bottomMaskView.addSubview(timeSlider)
bottomMaskView.addSubview(fullscreenButton)
playButton.tag = BMPlayerControlView.ButtonType.play.rawValue
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_play"), for: .normal)
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_pause"), for: .selected)
playButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
currentTimeLabel.textColor = UIColor.white
currentTimeLabel.font = UIFont.systemFont(ofSize: 12)
currentTimeLabel.text = "00:00"
currentTimeLabel.textAlignment = NSTextAlignment.center
totalTimeLabel.textColor = UIColor.white
totalTimeLabel.font = UIFont.systemFont(ofSize: 12)
totalTimeLabel.text = "00:00"
totalTimeLabel.textAlignment = NSTextAlignment.center
timeSlider.maximumValue = 1.0
timeSlider.minimumValue = 0.0
timeSlider.value = 0.0
timeSlider.setThumbImage(BMImageResourcePath("Pod_Asset_BMPlayer_slider_thumb"), for: .normal)
timeSlider.maximumTrackTintColor = UIColor.clear
timeSlider.minimumTrackTintColor = BMPlayerConf.tintColor
timeSlider.addTarget(self, action: #selector(progressSliderTouchBegan(_:)),
for: UIControlEvents.touchDown)
timeSlider.addTarget(self, action: #selector(progressSliderValueChanged(_:)),
for: UIControlEvents.valueChanged)
timeSlider.addTarget(self, action: #selector(progressSliderTouchEnded(_:)),
for: [UIControlEvents.touchUpInside,UIControlEvents.touchCancel, UIControlEvents.touchUpOutside])
progressView.tintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 )
progressView.trackTintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3 )
fullscreenButton.tag = BMPlayerControlView.ButtonType.fullscreen.rawValue
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_fullscreen"), for: .normal)
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_portialscreen"), for: .selected)
fullscreenButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
mainMaskView.addSubview(loadingIndector)
loadingIndector.type = BMPlayerConf.loaderType
loadingIndector.color = BMPlayerConf.tintColor
// View to show when slide to seek
addSubview(seekToView)
seekToView.addSubview(seekToViewImage)
seekToView.addSubview(seekToLabel)
seekToLabel.font = UIFont.systemFont(ofSize: 13)
seekToLabel.textColor = UIColor ( red: 0.9098, green: 0.9098, blue: 0.9098, alpha: 1.0 )
seekToView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 )
seekToView.layer.cornerRadius = 4
seekToView.layer.masksToBounds = true
seekToView.isHidden = true
seekToViewImage.image = BMImageResourcePath("Pod_Asset_BMPlayer_seek_to_image")
addSubview(replayButton)
replayButton.isHidden = true
replayButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_replay"), for: .normal)
replayButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
replayButton.tag = ButtonType.replay.rawValue
tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureTapped(_:)))
addGestureRecognizer(tapGesture)
}
func addSnapKitConstraint() {
// Main mask view
mainMaskView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
maskImageView.snp.makeConstraints { (make) in
make.edges.equalTo(mainMaskView)
}
topMaskView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(mainMaskView)
make.height.equalTo(65)
}
bottomMaskView.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(mainMaskView)
make.height.equalTo(50)
}
// Top views
backButton.snp.makeConstraints { (make) in
make.width.height.equalTo(50)
make.left.bottom.equalTo(topMaskView)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(backButton.snp.right)
make.centerY.equalTo(backButton)
}
chooseDefitionView.snp.makeConstraints { (make) in
make.right.equalTo(topMaskView.snp.right).offset(-20)
make.top.equalTo(titleLabel.snp.top).offset(-4)
make.width.equalTo(60)
make.height.equalTo(30)
}
// Bottom views
playButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.left.bottom.equalTo(bottomMaskView)
}
currentTimeLabel.snp.makeConstraints { (make) in
make.left.equalTo(playButton.snp.right)
make.centerY.equalTo(playButton)
make.width.equalTo(40)
}
timeSlider.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(currentTimeLabel.snp.right).offset(10).priority(750)
make.height.equalTo(30)
}
progressView.snp.makeConstraints { (make) in
make.centerY.left.right.equalTo(timeSlider)
make.height.equalTo(2)
}
totalTimeLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(timeSlider.snp.right).offset(5)
make.width.equalTo(40)
}
fullscreenButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(totalTimeLabel.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
loadingIndector.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX).offset(0)
make.centerY.equalTo(mainMaskView.snp.centerY).offset(0)
}
// View to show when slide to seek
seekToView.snp.makeConstraints { (make) in
make.center.equalTo(self.snp.center)
make.width.equalTo(100)
make.height.equalTo(40)
}
seekToViewImage.snp.makeConstraints { (make) in
make.left.equalTo(seekToView.snp.left).offset(15)
make.centerY.equalTo(seekToView.snp.centerY)
make.height.equalTo(15)
make.width.equalTo(25)
}
seekToLabel.snp.makeConstraints { (make) in
make.left.equalTo(seekToViewImage.snp.right).offset(10)
make.centerY.equalTo(seekToView.snp.centerY)
}
replayButton.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX)
make.centerY.equalTo(mainMaskView.snp.centerY)
make.width.height.equalTo(50)
}
subtitleBackView.snp.makeConstraints {
$0.bottom.equalTo(snp.bottom).offset(-5)
$0.centerX.equalTo(snp.centerX)
$0.width.lessThanOrEqualTo(snp.width).offset(-10).priority(750)
}
subtitleLabel.snp.makeConstraints {
$0.left.equalTo(subtitleBackView.snp.left).offset(10)
$0.right.equalTo(subtitleBackView.snp.right).offset(-10)
$0.top.equalTo(subtitleBackView.snp.top).offset(2)
$0.bottom.equalTo(subtitleBackView.snp.bottom).offset(-2)
}
}
fileprivate func BMImageResourcePath(_ fileName: String) -> UIImage? {
let bundle = Bundle(for: BMPlayer.self)
let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
return image
}
}
|
c2ee5e00c9b458dab912bea4c918099b
| 34.436185 | 126 | 0.610465 | false | false | false | false |
LYM-mg/MGDYZB
|
refs/heads/master
|
MGDYZB简单封装版/MGDYZB/Class/Live/ViewModel/AllListViewModel.swift
|
mit
|
1
|
//
// AllListViewModel.swift
// MGDYZB
//
// Created by ming on 16/10/30.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
import UIKit
class AllListViewModel: NSObject {
// 用于上下拉刷新
var currentPage = 0
var rooms: [RoomModel] = []
fileprivate let tagID: String = "0"
}
extension AllListViewModel {
func loadAllListData(_ finishedCallback: @escaping () -> ()) {
let parameters:[String : Any] = ["offset": 20*currentPage, "limit": 20, "time": String(format: "%.0f", Date().timeIntervalSince1970)]
let url = "http://capi.douyucdn.cn/api/v1/live/" + "\(tagID)?"
NetWorkTools.requestData(type: .get, urlString: url,parameters: parameters, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
NetWorkTools.requestData(type: .get, urlString: "http://www.douyu.com/api/v1/live/directory",parameters: nil, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
}
}
|
189ca15da02c2fc7f6f094903211ff5a
| 32.775862 | 145 | 0.552833 | false | false | false | false |
jkereako/MassStateKeno
|
refs/heads/master
|
Sources/Views/DrawingTableViewCell.swift
|
mit
|
1
|
//
// DrawingTableViewCell.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/19/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import UIKit
final class DrawingTableViewCell: UITableViewCell {
var viewModel: DrawingViewModel? {
didSet {
gameIdentifier.text = viewModel?.gameIdentifier
bonusMultiplier.text = viewModel?.bonus
}
}
@IBOutlet private weak var innerContent: UIView!
@IBOutlet private weak var gameIdentifier: UILabel!
@IBOutlet private weak var bonusMultiplier: UILabel!
@IBInspectable private var innerContentBorderColor: UIColor = UIColor.white
@IBInspectable private var innerContentBorderWidth: CGFloat = 3.0
@IBInspectable private var innerContentCornerRadius: CGFloat = 15.0
private let selectedBackgroundColor = UIColor(named: "DarkBlue")
private let unselectedBackgroundColor = UIColor(named: "MediumBlue")
override func awakeFromNib() {
super.awakeFromNib()
gameIdentifier.text = nil
bonusMultiplier.text = nil
innerContent.layer.borderColor = innerContentBorderColor.cgColor
innerContent.layer.borderWidth = innerContentBorderWidth
innerContent.layer.cornerRadius = innerContentCornerRadius
selectionStyle = .none
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
if (highlighted) {
innerContent.backgroundColor = selectedBackgroundColor
return
}
innerContent.backgroundColor = unselectedBackgroundColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
if (selected) {
innerContent.backgroundColor = selectedBackgroundColor
return
}
innerContent.backgroundColor = unselectedBackgroundColor
}
override func layoutSubviews() {
super.layoutSubviews()
#if TARGET_INTERFACE_BUILDER
innerContent.layer.borderColor = innerContentBorderColor.cgColor
innerContent.layer.borderWidth = innerContentBorderWidth
innerContent.layer.cornerRadius = innerContentCornerRadius
#endif
}
}
|
f7c8bd57c39e0711fbdf62d77579a449
| 29.985915 | 79 | 0.695909 | false | false | false | false |
psobot/hangover
|
refs/heads/master
|
Hangover/ConversationEvent.swift
|
mit
|
1
|
//
// ConversationEvent.swift
// Hangover
//
// Created by Peter Sobot on 6/8/15.
// Copyright © 2015 Peter Sobot. All rights reserved.
//
import Foundation
struct UserID : Hashable {
let chat_id: String
let gaia_id: String
var hashValue: Int {
get {
return chat_id.hashValue &+ gaia_id.hashValue
}
}
}
func ==(lhs: UserID, rhs: UserID) -> Bool {
return lhs.hashValue == rhs.hashValue
}
class ConversationEvent : Equatable {
// An event which becomes part of the permanent record of a conversation.
// This corresponds to ClientEvent in the API.
// This is the base class for such events.
let event: CLIENT_EVENT
init(client_event: CLIENT_EVENT) {
event = client_event
}
lazy var timestamp: NSDate = {
// A timestamp of when the event occurred.
return self.event.timestamp
}()
lazy var user_id: UserID = {
// A UserID indicating who created the event.
return UserID(
chat_id: self.event.sender_id!.chat_id as String,
gaia_id: self.event.sender_id!.gaia_id as String
)
}()
lazy var conversation_id: NSString = {
// The ID of the conversation the event belongs to.
return self.event.conversation_id.id
}()
lazy var id: Conversation.EventID = {
// The ID of the ConversationEvent.
return self.event.event_id! as Conversation.EventID
}()
}
func ==(lhs: ConversationEvent, rhs: ConversationEvent) -> Bool {
return lhs.event == rhs.event
}
class ChatMessageSegment {
let type: SegmentType
let text: String
let is_bold: Bool
let is_italic: Bool
let is_strikethrough: Bool
let is_underline: Bool
let link_target: String?
// A segment of a chat message.
init(text: String,
segment_type: SegmentType?=nil,
is_bold: Bool=false,
is_italic: Bool=false,
is_strikethrough: Bool=false,
is_underline: Bool=false,
link_target: String?=nil
) {
// Create a new chat message segment.
if let type = segment_type {
self.type = type
} else if link_target != nil {
self.type = SegmentType.LINK
} else {
self.type = SegmentType.TEXT
}
self.text = text
self.is_bold = is_bold
self.is_italic = is_italic
self.is_strikethrough = is_strikethrough
self.is_underline = is_underline
self.link_target = link_target
}
// static func from_str(string: text) -> [ChatMessageSegment] {
// // Generate ChatMessageSegment list parsed from a string.
// // This method handles automatically finding line breaks, URLs and
// // parsing simple formatting markup (simplified Markdown and HTML).
// segment_list = chat_message_parser.parse(text)
// return [ChatMessageSegment(segment.text, **segment.params) for segment in segment_list]
// }
init(segment: MESSAGE_SEGMENT) {
// Create a chat message segment from a parsed MESSAGE_SEGMENT.
text = segment.text! as String
type = segment.type_
// The formatting options are optional.
is_bold = segment.formatting?.bold?.boolValue ?? false
is_italic = segment.formatting?.italic?.boolValue ?? false
is_strikethrough = segment.formatting?.strikethrough?.boolValue ?? false
is_underline = segment.formatting?.underline?.boolValue ?? false
link_target = (segment.link_data?.link_target as String?) ?? nil
}
func serialize() -> NSArray {
// Serialize the segment to pblite.
return [self.type.representation, self.text, [
self.is_bold ? 1 : 0,
self.is_italic ? 1 : 0,
self.is_strikethrough ? 1 : 0,
self.is_underline ? 1 : 0,
], [self.link_target ?? NSNull()]]
}
}
class ChatMessageEvent : ConversationEvent {
// An event containing a chat message.
// Corresponds to ClientChatMessage in the API.
lazy var text: String = {
// A textual representation of the message.
var lines = [""]
for segment in self.segments {
switch (segment.type) {
case SegmentType.TEXT, SegmentType.LINK:
let replacement = lines.last! + segment.text
lines.removeLast()
lines.append(replacement)
case SegmentType.LINE_BREAK:
lines.append("")
default:
print("Ignoring unknown chat message segment type: \(segment.type.representation)")
}
}
lines += self.attachments
return "\n".join(lines)
}()
lazy var segments: [ChatMessageSegment] = {
// List of ChatMessageSegments in the message.
if let list = self.event.chat_message?.message_content.segment {
return list.map { ChatMessageSegment(segment: $0) }
} else {
return []
}
}()
var attachments: [String] {
get {
// Attachments in the message.
let raw_attachments = self.event.chat_message?.message_content.attachment ?? [MESSAGE_ATTACHMENT]()
var attachments = [String]()
for attachment in raw_attachments {
if attachment.embed_item.type_ == [249] { // PLUS_PHOTO
// Try to parse an image message. Image messages contain no
// message segments, and thus have no automatic textual
// fallback.
if let data = attachment.embed_item.data["27639957"] as? NSArray,
zeroth = data[0] as? NSArray,
third = zeroth[3] as? String {
attachments.append(third)
}
} else if attachment.embed_item.type_ == [340, 335, 0] {
// Google Maps URL that's already in the text.
} else {
print("Ignoring unknown chat message attachment: \(attachment)")
}
}
return attachments
}
}
}
class RenameEvent : ConversationEvent {
// An event that renames a conversation.
// Corresponds to ClientConversationRename in the API.
var new_name: String {
get {
// The conversation's new name.
// An empty string if the conversation's name was cleared.
return self.event.conversation_rename!.new_name as String
}
}
var old_name: String {
get {
// The conversation's old name.
// An empty string if the conversation had no previous name.
return self.event.conversation_rename!.old_name as String
}
}
}
class MembershipChangeEvent : ConversationEvent {
// An event that adds or removes a conversation participant.
// Corresponds to ClientMembershipChange in the API.
var type: MembershipChangeType {
get {
// The membership change type (MembershipChangeType).
return self.event.membership_change!.type_
}
}
var participant_ids: [UserID] {
get {
// Return the UserIDs involved in the membership change.
// Multiple users may be added to a conversation at the same time.
return self.event.membership_change!.participant_ids.map {
UserID(chat_id: $0.chat_id as String, gaia_id: $0.gaia_id as String)
}
}
}
}
|
4ed9af8062051c3022e731c6ca4f3bdc
| 31.616379 | 111 | 0.583928 | false | false | false | false |
IAskWind/IAWExtensionTool
|
refs/heads/master
|
IAWExtensionTool/IAWExtensionTool/Classes/Common/IAW_EditTextViewController.swift
|
mit
|
1
|
//
// EditViewController.swift
// WingBid
//
// Created by winston on 16/10/6.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
//import OMExtension
import Easy
public protocol EditTextViewDelegate: NSObjectProtocol {
func editClick(editKey: String,editValue:String)
}
// key value的形式 key实际就是title value
open class IAW_EditTextViewController: IAW_BaseViewController {
var editKey:String = ""
var editValue: String = ""
weak var delegate: EditTextViewDelegate?
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initUI()
}
override open func viewWillAppear(_ animated: Bool) {
editTextfield.text = editValue
}
func initUI(){
setRightBarBtn()
view.addSubview(editTextfield)
editTextfield.snp.makeConstraints{
(make) in
make.top.equalTo(10)
make.width.equalTo(view)
make.height.equalTo(40)
}
}
func setRightBarBtn(){
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(rightBarBtnClick))
}
private lazy var editTextfield:UITextField = {
let editTextfield = UITextField()
editTextfield.clearButtonMode = .always
editTextfield.leftView = UIView(frame: CGRect(x:0,y:0,width:8,height:0))
editTextfield.leftViewMode = .always
editTextfield.backgroundColor = UIColor.white
editTextfield.textColor = UIColor.iaw_Color(0, g: 0, b: 0, a: 0.6)
editTextfield.font = UIFont.systemFont(ofSize: 16)
editTextfield.setLimit(20)
return editTextfield
}()
@objc func rightBarBtnClick(){
if (editTextfield.text?.isEmpty)! {
IAW_ProgressHUDTool.showErrorInfo(msg: "\(navigationItem.title!)不能为空!")
return
}
if(editValue == editTextfield.text!){//没有改变直接关闭
_ = self.navigationController?.popViewController(animated: true)
return
}
delegate?.editClick(editKey: editKey,editValue:editTextfield.text!)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
6f064644cbe4af8ba79fddedff73e8e2
| 30.933333 | 138 | 0.640501 | false | false | false | false |
stv-ekushida/STV-Extensions
|
refs/heads/master
|
STV-Extensions/Classes/Foundation/Date+Helper.swift
|
mit
|
1
|
//
// Date+Helper.swift
// ios-extension-demo
//
// Created by Eiji Kushida on 2017/03/13.
// Copyright © 2017年 Eiji Kushida. All rights reserved.
//
import Foundation
public extension Date {
/// Date型をString型に変更する
func toStr(dateFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale!
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: self)
}
/// Unixタイムスタンプを取得する
static var unixTimestamp: String {
get {
return Date().timeIntervalSince1970.description
}
}
}
|
b77e7d2716ea12dc17c8302cd743ea7d
| 23.0625 | 77 | 0.623377 | false | false | false | false |
tonyarnold/Differ
|
refs/heads/main
|
Sources/Differ/NestedExtendedDiff.swift
|
mit
|
1
|
public struct NestedExtendedDiff: DiffProtocol {
public typealias Index = Int
public enum Element {
case deleteSection(Int)
case insertSection(Int)
case moveSection(from: Int, to: Int)
case deleteElement(Int, section: Int)
case insertElement(Int, section: Int)
case moveElement(from: (item: Int, section: Int), to: (item: Int, section: Int))
}
/// Returns the position immediately after the given index.
///
/// - Parameters:
/// - i: A valid index of the collection. `i` must be less than `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
/// An array of particular diff operations
public var elements: [Element]
/// Initializes a new ``NestedExtendedDiff`` from a given array of diff operations.
///
/// - Parameters:
/// - elements: an array of particular diff operations
public init(elements: [Element]) {
self.elements = elements
}
}
public typealias NestedElementEqualityChecker<T: Collection> = (T.Element.Element, T.Element.Element) -> Bool where T.Element: Collection
public extension Collection
where Element: Collection {
/// Creates a diff between the callee and `other` collection. It diffs elements two levels deep (therefore "nested")
///
/// - Parameters:
/// - other: a collection to compare the calee to
/// - Returns: a ``NestedDiff`` between the calee and `other` collection
func nestedExtendedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedExtendedDiff {
// FIXME: This implementation is a copy paste of NestedDiff with some adjustments.
let diffTraces = outputDiffPathTraces(to: to, isEqual: isEqualSection)
let sectionDiff =
extendedDiff(
from: Diff(traces: diffTraces),
other: to,
isEqual: isEqualSection
).map { element -> NestedExtendedDiff.Element in
switch element {
case let .delete(at):
return .deleteSection(at)
case let .insert(at):
return .insertSection(at)
case let .move(from, to):
return .moveSection(from: from, to: to)
}
}
// Diff matching sections (moves, deletions, insertions)
let filterMatchPoints = { (trace: Trace) -> Bool in
if case .matchPoint = trace.type() {
return true
}
return false
}
let sectionMoves =
sectionDiff.compactMap { diffElement -> (Int, Int)? in
if case let .moveSection(from, to) = diffElement {
return (from, to)
}
return nil
}.flatMap { move -> [NestedExtendedDiff.Element] in
return itemOnStartIndex(advancedBy: move.0).extendedDiff(to.itemOnStartIndex(advancedBy: move.1), isEqual: isEqualElement)
.map { diffElement -> NestedExtendedDiff.Element in
switch diffElement {
case let .insert(at):
return .insertElement(at, section: move.1)
case let .delete(at):
return .deleteElement(at, section: move.0)
case let .move(from, to):
return .moveElement(from: (from, move.0), to: (to, move.1))
}
}
}
// offset & section
let matchingSectionTraces = diffTraces
.filter(filterMatchPoints)
let fromSections = matchingSectionTraces.map {
itemOnStartIndex(advancedBy: $0.from.x)
}
let toSections = matchingSectionTraces.map {
to.itemOnStartIndex(advancedBy: $0.from.y)
}
let elementDiff = zip(zip(fromSections, toSections), matchingSectionTraces)
.flatMap { (args) -> [NestedExtendedDiff.Element] in
let (sections, trace) = args
return sections.0.extendedDiff(sections.1, isEqual: isEqualElement).map { diffElement -> NestedExtendedDiff.Element in
switch diffElement {
case let .delete(at):
return .deleteElement(at, section: trace.from.x)
case let .insert(at):
return .insertElement(at, section: trace.from.y)
case let .move(from, to):
return .moveElement(from: (from, trace.from.x), to: (to, trace.from.y))
}
}
}
return NestedExtendedDiff(elements: sectionDiff + sectionMoves + elementDiff)
}
}
public extension Collection
where Element: Collection,
Element.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>
) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: isEqualSection,
isEqualElement: { $0 == $1 }
)
}
}
public extension Collection
where Element: Collection, Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(
to: Self,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: isEqualElement
)
}
}
public extension Collection
where Element: Collection, Element: Equatable,
Element.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(to: Self) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: { $0 == $1 }
)
}
}
extension NestedExtendedDiff.Element: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .deleteElement(row, section):
return "DE(\(row),\(section))"
case let .deleteSection(section):
return "DS(\(section))"
case let .insertElement(row, section):
return "IE(\(row),\(section))"
case let .insertSection(section):
return "IS(\(section))"
case let .moveElement(from, to):
return "ME((\(from.item),\(from.section)),(\(to.item),\(to.section)))"
case let .moveSection(from, to):
return "MS(\(from),\(to))"
}
}
}
extension NestedExtendedDiff: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: NestedExtendedDiff.Element...) {
self.elements = elements
}
}
|
677aa840003ca7bf4be535f234fd3fb8
| 34.173267 | 138 | 0.572695 | false | false | false | false |
bmichotte/HSTracker
|
refs/heads/master
|
HSTracker/Logging/Parsers/TagChangeActions.swift
|
mit
|
1
|
//
// TagChanceActions.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
struct TagChangeActions {
func callAction(eventHandler: PowerEventHandler, tag: GameTag, id: Int, value: Int, prevValue: Int) {
switch tag {
case .zone: self.zoneChange(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue)
case .playstate: self.playstateChange(eventHandler: eventHandler, id: id, value: value)
case .cardtype: self.cardTypeChange(eventHandler: eventHandler, id: id, value: value)
case .last_card_played: self.lastCardPlayedChange(eventHandler: eventHandler, value: value)
case .defending: self.defendingChange(eventHandler: eventHandler, id: id, value: value)
case .attacking: self.attackingChange(eventHandler: eventHandler, id: id, value: value)
case .proposed_defender: self.proposedDefenderChange(eventHandler: eventHandler, value: value)
case .proposed_attacker: self.proposedAttackerChange(eventHandler: eventHandler, value: value)
case .num_minions_played_this_turn:
self.numMinionsPlayedThisTurnChange(eventHandler: eventHandler, value: value)
case .predamage: self.predamageChange(eventHandler: eventHandler, id: id, value: value)
case .num_turns_in_play: self.numTurnsInPlayChange(eventHandler: eventHandler, id: id, value: value)
case .num_attacks_this_turn: self.numAttacksThisTurnChange(eventHandler: eventHandler, id: id, value: value)
case .zone_position: self.zonePositionChange(eventHandler: eventHandler, id: id)
case .card_target: self.cardTargetChange(eventHandler: eventHandler, id: id, value: value)
case .equipped_weapon: self.equippedWeaponChange(eventHandler: eventHandler, id: id, value: value)
case .exhausted: self.exhaustedChange(eventHandler: eventHandler, id: id, value: value)
case .controller:
self.controllerChange(eventHandler: eventHandler, id: id, prevValue: prevValue, value: value)
case .fatigue: self.fatigueChange(eventHandler: eventHandler, value: value, id: id)
case .step: self.stepChange(eventHandler: eventHandler)
case .turn: self.turnChange(eventHandler: eventHandler)
case .state: self.stateChange(eventHandler: eventHandler, value: value)
case .transformed_from_card: self.transformedFromCardChange(eventHandler: eventHandler,
id: id,
value: value)
default: break
}
}
private func transformedFromCardChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == 0 { return }
guard let entity = eventHandler.entities[id] else { return }
entity.info.set(originalCardId: value)
}
private func lastCardPlayedChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.lastCardPlayed = value
}
private func defendingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.defending(entity: value == 1 ? entity : nil)
}
private func attackingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.attacking(entity: value == 1 ? entity : nil)
}
private func proposedDefenderChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.opponentSecrets?.proposedDefenderEntityId = value
}
private func proposedAttackerChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.opponentSecrets?.proposedAttackerEntityId = value
}
private func numMinionsPlayedThisTurnChange(eventHandler: PowerEventHandler, value: Int) {
guard value > 0 else { return }
guard let playerEntity = eventHandler.playerEntity else { return }
if playerEntity.isCurrentPlayer {
eventHandler.playerMinionPlayed()
}
}
private func predamageChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let playerEntity = eventHandler.playerEntity, let entity = eventHandler.entities[id] else { return }
if playerEntity.isCurrentPlayer {
eventHandler.opponentDamage(entity: entity)
}
}
private func numTurnsInPlayChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
eventHandler.turnsInPlayChange(entity: entity, turn: eventHandler.turnNumber())
}
private func fatigueChange(eventHandler: PowerEventHandler, value: Int, id: Int) {
guard let entity = eventHandler.entities[id] else { return }
let controller = entity[.controller]
if controller == eventHandler.player.id {
eventHandler.playerFatigue(value: value)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentFatigue(value: value)
}
}
private func controllerChange(eventHandler: PowerEventHandler, id: Int, prevValue: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
if prevValue <= 0 {
entity.info.originalController = value
return
}
guard !entity.has(tag: .player_id) else { return }
if value == eventHandler.player.id {
if entity.isInZone(zone: .secret) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
} else if value == eventHandler.opponent.id && prevValue != value {
if entity.isInZone(zone: .secret) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
}
}
private func exhaustedChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
guard entity[.cardtype] == CardType.hero_power.rawValue else { return }
}
private func equippedWeaponChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func cardTargetChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func zonePositionChange(eventHandler: PowerEventHandler, id: Int) {
}
private func numAttacksThisTurnChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func stateChange(eventHandler: PowerEventHandler, value: Int) {
if value != State.complete.rawValue {
return
}
eventHandler.gameEnd()
eventHandler.gameEnded = true
}
private func turnChange(eventHandler: PowerEventHandler) {
guard eventHandler.setupDone && eventHandler.playerEntity != nil else { return }
guard let playerEntity = eventHandler.playerEntity else { return }
let activePlayer: PlayerType = playerEntity.has(tag: .current_player) ? .player : .opponent
if activePlayer == .player {
eventHandler.playerUsedHeroPower = false
} else {
eventHandler.opponentUsedHeroPower = false
}
}
private func stepChange(eventHandler: PowerEventHandler) {
guard !eventHandler.setupDone && eventHandler.entities.first?.1.name == "GameEntity" else { return }
Log.info?.message("Game was already in progress.")
eventHandler.wasInProgress = true
}
private func cardTypeChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == CardType.hero.rawValue {
setHeroAsync(eventHandler: eventHandler, id: id)
}
}
private func playstateChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == PlayState.conceded.rawValue {
eventHandler.concede()
}
guard !eventHandler.gameEnded else { return }
if let entity = eventHandler.entities[id], !entity.isPlayer(eventHandler: eventHandler) {
return
}
if let value = PlayState(rawValue: value) {
switch value {
case .won:
eventHandler.win()
case .lost:
eventHandler.loss()
case .tied:
eventHandler.tied()
default: break
}
}
}
private func zoneChange(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int) {
guard id > 3 else { return }
guard let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == nil {
if prevValue != Zone.invalid.rawValue && prevValue != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: prevValue)
} else if value != Zone.invalid.rawValue && value != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: value)
}
}
let controller = entity[.controller]
guard let zoneValue = Zone(rawValue: prevValue) else { return }
switch zoneValue {
case .deck:
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue,
controller: controller,
cardId: entity.cardId)
case .hand:
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .play:
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .secret:
zoneChangeFromSecret(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .invalid:
let maxId = getMaxHeroPowerId(eventHandler: eventHandler)
if !eventHandler.setupDone
&& (id <= maxId || eventHandler.gameEntity?[.step] == Step.invalid.rawValue
&& entity[.zone_position] < 5) {
entity.info.originalZone = .deck
simulateZoneChangesFromDeck(eventHandler: eventHandler, id: id, value: value,
cardId: entity.cardId, maxId: maxId)
} else {
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
}
case .graveyard, .setaside, .removedfromgame:
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value, prevValue: prevValue,
controller: controller, cardId: entity.cardId)
}
}
// The last heropower is created after the last hero, therefore +1
private func getMaxHeroPowerId(eventHandler: PowerEventHandler) -> Int {
return max(eventHandler.playerEntity?[.hero_entity] ?? 66,
eventHandler.opponentEntity?[.hero_entity] ?? 66) + 1
}
private func simulateZoneChangesFromDeck(eventHandler: PowerEventHandler, id: Int,
value: Int, cardId: String?, maxId: Int) {
if value == Zone.deck.rawValue {
return
}
guard let entity = eventHandler.entities[id] else { return }
if value == Zone.setaside.rawValue {
entity.info.created = true
return
}
if entity.isHero || entity.isHeroPower || entity.has(tag: .player_id)
|| entity[.cardtype] == CardType.game.rawValue || entity.has(tag: .creator) {
return
}
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: Zone.hand.rawValue,
prevValue: Zone.deck.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.hand.rawValue {
return
}
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: Zone.play.rawValue,
prevValue: Zone.hand.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.play.rawValue {
return
}
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value, prevValue: Zone.play.rawValue,
controller: entity[.controller], cardId: cardId)
}
private func zoneChangeFromOther(eventHandler: PowerEventHandler, id: Int, rawValue: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let value = Zone(rawValue: rawValue), let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == .deck && rawValue != Zone.deck.rawValue {
// This entity was moved from DECK to SETASIDE to HAND, e.g. by Tracking
entity.info.discarded = false
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: rawValue, prevValue: prevValue,
controller: controller, cardId: cardId)
return
}
entity.info.created = true
switch value {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .deck:
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.playerGetToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.opponentGetToDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerGet(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentGet(entity: entity, turn: eventHandler.turnNumber(), id: id)
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: -1,
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .setaside:
if controller == eventHandler.player.id {
eventHandler.playerCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
}
default:
break
}
}
private func zoneChangeFromSecret(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .secret, .graveyard:
if controller == eventHandler.opponent.id {
eventHandler.opponentSecretTrigger(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), otherId: id)
}
default:
break
}
}
private func zoneChangeFromPlay(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerBackToHand(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToHand(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), id: id)
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerPlayToGraveyard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if let playerEntity = eventHandler.playerEntity {
eventHandler.opponentPlayToGraveyard(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(),
playersTurn: playerEntity.isCurrentPlayer)
}
}
case .removedfromgame, .setaside:
if controller == eventHandler.player.id {
eventHandler.playerRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
}
case .play:
break
default:
break
}
}
private func zoneChangeFromHand(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlay(entity: entity, cardId: cardId, from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .removedfromgame, .setaside, .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerHandDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentHandDiscard(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerMulligan(entity: entity, cardId: cardId)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentMulligan(entity: entity, from: entity[.zone_position])
}
default:
break
}
}
private func zoneChangeFromDeck(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerDraw(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDraw(entity: entity, turn: eventHandler.turnNumber())
}
case .setaside, .removedfromgame:
if !eventHandler.setupDone {
entity.info.created = true
return
}
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.playerRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.opponentRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .play:
if controller == eventHandler.player.id {
eventHandler.playerDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: -1, turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
default:
break
}
}
private func setHeroAsync(eventHandler: PowerEventHandler, id: Int) {
Log.info?.message("Found hero with id \(id) ")
DispatchQueue.global().async {
if eventHandler.playerEntity == nil {
Log.info?.message("Waiting for playerEntity")
while eventHandler.playerEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let playerEntity = eventHandler.playerEntity,
let entity = eventHandler.entities[id] {
Log.info?.message("playerEntity found playerClass : "
+ "\(String(describing: eventHandler.player.playerClass)), "
+ "\(id) -> \(playerEntity[.hero_entity]) -> \(entity) ")
if id == playerEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(playerHero: cardId)
}
return
}
}
if eventHandler.opponentEntity == nil {
Log.info?.message("Waiting for opponentEntity")
while eventHandler.opponentEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let opponentEntity = eventHandler.opponentEntity,
let entity = eventHandler.entities[id] {
Log.info?.message("opponentEntity found playerClass : "
+ "\(String(describing: eventHandler.opponent.playerClass)),"
+ " \(id) -> \(opponentEntity[.hero_entity]) -> \(entity) ")
if id == opponentEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(opponentHero: cardId)
}
return
}
}
}
}
}
|
d3ab00cd8583721d0e56a250484c6b54
| 44.787022 | 116 | 0.574715 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Neocom/Neocom/Utility/Views/SearchController.swift
|
lgpl-2.1
|
2
|
//
// SearchController.swift
// Neocom
//
// Created by Artem Shimanski on 5/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Combine
struct SearchController<Results, Content: View, P: Publisher>: UIViewControllerRepresentable where P.Failure == Never, P.Output == Results {
var search: (String) -> P
var content: (Results?) -> Content
init(search: @escaping (String) -> P, @ViewBuilder content: @escaping (Results?) -> Content) {
self.search = search
self.content = content
}
func makeUIViewController(context: Context) -> SearchControllerWrapper<Results, Content, P> {
SearchControllerWrapper(search: search, content: content)
}
func updateUIViewController(_ uiViewController: SearchControllerWrapper<Results, Content, P>, context: Context) {
}
}
struct SearchControllerTest: View {
@State private var text: String = "123"
@State private var isEditing: Bool = false
@State private var text2: String = "321"
let subject = CurrentValueSubject<String, Never>("123")
var binding: Binding<String> {
Binding(get: {
self.text
}) {
self.text = $0
self.subject.send($0)
}
}
var body: some View {
VStack{
// SearchBar()
SearchField(text: binding, isEditing: $isEditing)
List {
Text(text2)
}.onReceive(subject.debounce(for: .seconds(0.25), scheduler: RunLoop.main)) {
self.text2 = $0
}
}
}
}
struct SearchController_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
SearchControllerTest()
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
|
75ce5e9288a0df80011dd4c3e0acb4c7
| 27.184615 | 140 | 0.6119 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/Interop/Cxx/stdlib/overlay/custom-collection-module-interface.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-ide-test -print-module -module-to-print=CustomSequence -source-filename=x -I %S/Inputs -enable-experimental-cxx-interop -module-cache-path %t | %FileCheck %s
// CHECK: struct SimpleArrayWrapper : CxxRandomAccessCollection {
// CHECK: typealias Element = UnsafePointer<Int32>.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleArrayWrapper>
// CHECK: typealias RawIterator = UnsafePointer<Int32>
// CHECK: }
// CHECK: struct SimpleCollectionNoSubscript : CxxRandomAccessCollection {
// CHECK: typealias Element = ConstRACIterator.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleCollectionNoSubscript>
// CHECK: typealias RawIterator = SimpleCollectionNoSubscript.iterator
// CHECK: }
// CHECK: struct SimpleCollectionReadOnly : CxxRandomAccessCollection {
// CHECK: typealias Element = ConstRACIteratorRefPlusEq.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleCollectionReadOnly>
// CHECK: typealias RawIterator = SimpleCollectionReadOnly.iterator
// CHECK: }
|
f51629d51112f8a6a1d7ba86cc43ed1c
| 53 | 179 | 0.778752 | false | true | false | false |
ios-ximen/DYZB
|
refs/heads/master
|
斗鱼直播/斗鱼直播/Classes/Home/Views/KGameView.swift
|
mit
|
1
|
//
// KGameView.swift
// 斗鱼直播
//
// Created by niujinfeng on 2017/7/6.
// Copyright © 2017年 niujinfeng. All rights reserved.
//
import UIKit
fileprivate let KGameID = "KGameID"
fileprivate let KEdgeMargin : CGFloat = 10
class KGameView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
//定义模型属性
var gameGroup : [BaseGameModel]?{
didSet{
//刷新数据
collectionView.reloadData()
}
}
//系统回调方法
override func awakeFromNib() {
super.awakeFromNib()
//子控件不随父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
//注册cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: KGameID)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(0, KEdgeMargin, 0, KEdgeMargin)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: 80, height: 90)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.showsHorizontalScrollIndicator = false
}
}
//快速创建类方法
extension KGameView {
class func kGameView() -> KGameView {
return Bundle.main.loadNibNamed("KGameView", owner: nil, options: nil)?.first as! KGameView
}
}
extension KGameView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameGroup?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KGameID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameGroup?[indexPath.item]
//cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.green
return cell
}
}
|
cd777174a470320da0225be99d1fb793
| 30.235294 | 122 | 0.670433 | false | false | false | false |
PurpleSweetPotatoes/customControl
|
refs/heads/master
|
SwiftKit/UI/BQSheetView.swift
|
apache-2.0
|
1
|
//
// BQSheetView.swift
// swift-Test
//
// Created by MrBai on 2017/6/13.
// Copyright © 2017年 MrBai. All rights reserved.
//
import UIKit
enum SheetType {
case table
case collection
}
class BQSheetView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
//MARK: - ***** Ivars *****
private var title: String?
private var type: SheetType!
private var tableDatas: [String] = []
private var shareDatas: [Dictionary<String,String>] = []
private var backView: UIView!
private var bottomView: UIView!
private var callBlock: ((Int) -> ())!
//MARK: - ***** Class Method *****
class func showSheetView(tableDatas:[String] ,title:String? = nil, handle:@escaping (Int)->()) {
let sheetView = BQSheetView(tableDatas: tableDatas, title: title)
sheetView.callBlock = handle
UIApplication.shared.keyWindow?.addSubview(sheetView)
sheetView.startAnimation()
}
/// 弹出脚部分享视图
///
/// - Parameters:
/// - shareDatas: ["image":"图片名"]
/// - title: 抬头名称
/// - handle: 回调方法
class func showShareView(shareDatas:[Dictionary<String,String>] ,title:String, handle:@escaping (Int)->()) {
let sheetView = BQSheetView(shareDatas: shareDatas, title: title)
sheetView.callBlock = handle
UIApplication.shared.keyWindow?.addSubview(sheetView)
sheetView.startAnimation()
}
//MARK: - ***** initialize Method *****
private init(tableDatas:[String] ,title:String? = nil) {
self.title = title
self.type = .table
self.tableDatas = tableDatas
super.init(frame: UIScreen.main.bounds)
self.initData()
self.initUI()
}
private init(shareDatas:[Dictionary<String,String>] ,title:String? = nil) {
self.title = title
self.type = .collection
self.shareDatas = shareDatas
super.init(frame: UIScreen.main.bounds)
self.initData()
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ***** public Method *****
//MARK: - ***** private Method *****
private func initData() {
}
private func initUI() {
self.backView = UIView(frame: self.bounds)
self.backView.backgroundColor = UIColor(white: 0.3, alpha: 0.6)
self.backView.alpha = 0
self.backView.addTapGes {[weak self] (view) in
self?.removeAnimation()
}
self.addSubview(self.backView)
self.bottomView = UIView(frame: CGRect(x: 0, y: self.height, width: self.width, height: 0))
self.addSubview(self.bottomView)
var top: CGFloat = 0
if self.type == .table {
top = self.createTableUI(y: top)
}else {
top = self.createShareUI(y: top)
}
self.bottomView.height = top + 8
}
private func startAnimation() {
UIView.animate(withDuration: 0.25) {
self.bottomView.top = self.height - self.bottomView.height
self.backView.alpha = 1
}
}
private func removeAnimation() {
UIView.animate(withDuration: 0.25, animations: {
self.bottomView.top = self.height
self.backView.alpha = 0
}) { (flag) in
self.removeFromSuperview()
}
}
//MARK: - ***** LoadData Method *****
//MARK: - ***** respond event Method *****
@objc private func tableBtnAction(btn:UIButton) {
self.callBlock(btn.tag)
self.removeAnimation()
}
//MARK: - ***** Protocol *****
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.shareDatas.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BQShareItemCell", for: indexPath) as! BQShareItemCell
cell.loadInfo(dic: self.shareDatas[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
self.callBlock(indexPath.row)
self.removeAnimation()
}
//MARK: - ***** create Method *****
private func createTableUI(y:CGFloat) -> CGFloat {
var top = y
let spacing: CGFloat = 20
let height: CGFloat = 44
let labWidth: CGFloat = self.width - spacing * 2
if let titl = self.title {
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = titl
lab.textAlignment = .center
lab.numberOfLines = 0
lab.font = UIFont.systemFont(ofSize: 14)
lab.textColor = UIColor.gray
let labHeight = titl.boundingRect(with: CGSize(width: labWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:lab.font], context: nil).size.height + 20
lab.height = labHeight
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
top = labHeight
}
top += 1
var count = 0
for str in self.tableDatas {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: spacing, y: top, width: labWidth, height: height)
btn.setTitle(str, for: .normal)
btn.tag = count
btn.titleLabel?.textAlignment = .center
btn.setTitleColor(UIColor.black, for: .normal)
btn.addTarget(self, action: #selector(tableBtnAction(btn:)), for: .touchUpInside)
self.bottomView.addSubview(btn)
if count == self.tableDatas.count - 1 {
btn.setCornerColor(color: UIColor.white, readius: 8, corners: [.bottomLeft,.bottomRight])
}else {
if count == 0 && self.title == nil {
btn.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
}else {
btn.backgroundColor = UIColor.white
}
}
count += 1
top = btn.bottom + 1
}
top += 7
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = "返回"
lab.layer.cornerRadius = 8
lab.layer.masksToBounds = true
lab.textAlignment = .center
lab.backgroundColor = UIColor.white
lab.addTapGes(action: {[weak self] (view) in
self?.removeAnimation()
})
self.bottomView.addSubview(lab)
return lab.bottom
}
private func createShareUI(y:CGFloat) -> CGFloat {
var top = y
let spacing: CGFloat = 10
let labWidth: CGFloat = self.width - spacing * 2
let itemWidth = labWidth / 4.0
if let titl = self.title {
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = titl
lab.textAlignment = .center
lab.numberOfLines = 0
lab.font = UIFont.systemFont(ofSize: 14)
lab.textColor = UIColor.gray
let labHeight = titl.boundingRect(with: CGSize(width: labWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:lab.font], context: nil).size.height + 20
lab.height = labHeight
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
top = labHeight
}
top += 1
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.scrollDirection = .vertical
var num = self.shareDatas.count / 4
if self.shareDatas.count % 4 > 0 {
num += 1
}
let collectionView = UICollectionView(frame: CGRect(x: spacing, y: top, width: labWidth, height: CGFloat(num) * itemWidth), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.register(BQShareItemCell.classForCoder(), forCellWithReuseIdentifier: "BQShareItemCell")
collectionView.dataSource = self
collectionView.delegate = self
self.bottomView.addSubview(collectionView)
top = collectionView.bottom + 1
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: 44))
lab.text = "返回"
lab.textAlignment = .center
lab.addTapGes(action: {[weak self] (view) in
self?.removeAnimation()
})
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.bottomLeft,.bottomRight])
return lab.bottom
}
}
class BQShareItemCell: UICollectionViewCell {
private var imgView: UIImageView!
private var titleLab: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func initUI() {
let imgWidth = self.width / 2.0
let spacing = (self.width - imgWidth) * 0.5
let imageView = UIImageView(frame: CGRect(x: spacing, y: spacing * 0.7, width: imgWidth, height: imgWidth))
self.contentView.addSubview(imageView)
self.imgView = imageView
let lab = UILabel(frame: CGRect(x: 0, y: imageView.bottom, width: self.width, height: spacing))
lab.textAlignment = .center
lab.font = UIFont.systemFont(ofSize: 13)
lab.textColor = UIColor.gray
self.contentView.addSubview(lab)
self.titleLab = lab
}
public func loadInfo(dic:Dictionary<String,String>) {
self.imgView.image = UIImage(named:dic["image"] ?? "")
self.titleLab.text = dic["image"]
}
}
|
3aefb19d28c1be2761e067259ff67bb9
| 37.935849 | 226 | 0.604381 | false | false | false | false |
freshOS/Komponents
|
refs/heads/master
|
Source/PageControl.swift
|
mit
|
1
|
//
// PageControl.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 12/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
public struct PageControl: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public var children = [IsNode]()
let props: PageControlProps
public var layout: Layout
public let ref: UnsafeMutablePointer<UIPageControl>?
public init(props:((inout PageControlProps) -> Void)? = nil,
_ layout: Layout? = nil,
ref: UnsafeMutablePointer<UIPageControl>? = nil) {
let defaultProps = PageControlProps()
if let p = props {
var prop = defaultProps
p(&prop)
self.props = prop
} else {
self.props = defaultProps
}
self.layout = layout ?? Layout()
self.ref = ref
}
}
public func == (lhs: PageControl, rhs: PageControl) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public struct PageControlProps: HasViewProps, Equatable, Hashable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public var numberOfPages = 0
public var currentPage = 0
public var pageIndicatorTintColor: UIColor?
public var currentPageIndicatorTintColor: UIColor?
public var hashValue: Int {
return viewPropsHash
^ numberOfPages.hashValue
^ currentPage.hashValue
^ hashFor(pageIndicatorTintColor)
^ hashFor(currentPageIndicatorTintColor)
}
}
public func == (lhs: PageControlProps, rhs: PageControlProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
|
c94a12bd630e223bdd951c27bdc88e3f
| 28.753623 | 71 | 0.645397 | false | false | false | false |
minikin/Algorithmics
|
refs/heads/master
|
Pods/PSOperations/PSOperations/ReachabilityCondition.swift
|
mit
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
#if !os(watchOS)
import Foundation
import SystemConfiguration
/**
This is a condition that performs a very high-level reachability check.
It does *not* perform a long-running reachability check, nor does it respond to changes in reachability.
Reachability is evaluated once when the operation to which this is attached is asked about its readiness.
*/
public struct ReachabilityCondition: OperationCondition {
public static let hostKey = "Host"
public static let name = "Reachability"
public static let isMutuallyExclusive = false
let host: NSURL
public init(host: NSURL) {
self.host = host
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return nil
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
ReachabilityController.requestReachability(host) { reachable in
if reachable {
completion(.Satisfied)
}
else {
let error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.hostKey: self.host
])
completion(.Failed(error))
}
}
}
}
/// A private singleton that maintains a basic cache of `SCNetworkReachability` objects.
private class ReachabilityController {
static var reachabilityRefs = [String: SCNetworkReachability]()
static let reachabilityQueue = dispatch_queue_create("Operations.Reachability", DISPATCH_QUEUE_SERIAL)
static func requestReachability(url: NSURL, completionHandler: (Bool) -> Void) {
if let host = url.host {
dispatch_async(reachabilityQueue) {
var ref = self.reachabilityRefs[host]
if ref == nil {
let hostString = host as NSString
ref = SCNetworkReachabilityCreateWithName(nil, hostString.UTF8String)
}
if let ref = ref {
self.reachabilityRefs[host] = ref
var reachable = false
var flags: SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(ref, &flags) {
/*
Note that this is a very basic "is reachable" check.
Your app may choose to allow for other considerations,
such as whether or not the connection would require
VPN, a cellular connection, etc.
*/
reachable = flags.contains(.Reachable)
}
completionHandler(reachable)
}
else {
completionHandler(false)
}
}
}
else {
completionHandler(false)
}
}
}
#endif
|
1995a86ff8c309982bd978a9e99c5ee3
| 33.177083 | 109 | 0.57391 | false | false | false | false |
grandiere/box
|
refs/heads/master
|
box/Model/Stats/MStatsItemBugs.swift
|
mit
|
1
|
import UIKit
class MStatsItemBugs:MStatsItem
{
init()
{
let image:UIImage = #imageLiteral(resourceName: "assetTextureBugDetail")
let title:String = NSLocalizedString("MStatsItemBugs_title", comment:"")
let count:Int
if let bugs:Int16 = MSession.sharedInstance.settings?.stats?.bugs
{
count = Int(bugs)
}
else
{
count = 0
}
super.init(
image:image,
title:title,
count:count)
}
}
|
1b8c03b870bd1232e0cc03732f6d495a
| 20.96 | 80 | 0.520947 | false | false | false | false |
sman591/csh-drink-ios
|
refs/heads/master
|
CSH Drink/TimeAgo.swift
|
mit
|
1
|
//
// TimeAgo.swift
// CSH Drink
//
// Created by Henry Saniuk on 10/14/16.
// Copyright © 2016 Stuart Olivera. All rights reserved.
//
// Based on https://github.com/zemirco/swift-timeago
//
import Foundation
public func timeAgoSince(_ date: Date, timestamp: String) -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let month = components.month, month >= 2 {
return timestamp
}
if let month = components.month, month >= 1 {
return "Last month"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) weeks ago"
}
if let week = components.weekOfYear, week >= 1 {
return "Last week"
}
if let day = components.day, day >= 2 {
return "\(day) days ago"
}
if let day = components.day, day >= 1 {
return "Yesterday"
}
if let hour = components.hour, hour >= 2 {
return "\(hour) hours ago"
}
if let hour = components.hour, hour >= 1 {
return "An hour ago"
}
if let minute = components.minute, minute >= 2 {
return "\(minute) minutes ago"
}
if let minute = components.minute, minute >= 1 {
return "A minute ago"
}
if let second = components.second, second >= 3 {
return "\(second) seconds ago"
}
return "Just now"
}
|
2d6c85396774335a87c415c482647e70
| 22.910448 | 101 | 0.566167 | false | false | false | false |
PjGeeroms/IOSRecipeDB
|
refs/heads/master
|
YummlyProject/Controllers/RecipeOverviewController.swift
|
mit
|
1
|
//
// RecipeOverviewController.swift
// YummlyProject
//
// Created by Pieter-Jan Geeroms on 25/12/2016.
// Copyright © 2016 Pieter-Jan Geeroms. All rights reserved.
//
import UIKit
import Alamofire
class RecipeOverviewController: UIViewController {
var recipe: Recipe!
@IBOutlet weak var recipeTitle: UILabel!
@IBOutlet weak var recipeDescription: UILabel!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var deleteButton: UIButton!
@IBAction func makeRecipe() {}
@IBAction func delete() {
let confirm = UIAlertController(title: "Delete recipe", message: "Are you sure you want to delete the recipe?", preferredStyle: .alert)
confirm.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type" : "application/json",
"Authorization" : "Token \(Service.shared.user.token!)"
]
Alamofire.request("\(Service.shared.baseApi)/recipes/\(self.recipe.slug)", method: .delete, headers: headers).responseJSON(completionHandler: {
response in
if response.result.isSuccess {
self.image.isHidden = true
self.performSegue(withIdentifier: "unwindFromAdd", sender: self)
}
})
}))
confirm.addAction(UIAlertAction(title: "Hell no", style: .cancel, handler: { (action: UIAlertAction!) in
// Do nothing
}))
present(confirm, animated: true, completion: nil)
}
@IBAction func back() {
image.isHidden = true
performSegue(withIdentifier: "unwindToRecipes", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier! {
case "recipeGuide":
let recipeGuideController = segue.destination as! RecipeGuideController
recipeGuideController.recipe = self.recipe
default: break
}
}
override func viewDidLoad() {
navigationController?.isNavigationBarHidden = true
recipeTitle.text = recipe.name
recipeDescription.text = recipe.body
image.image = recipe.image
recipeTitle.adjustsFontSizeToFitWidth = true
if recipe.author.username != Service.shared.user.username {
deleteButton.isHidden = true
}
}
}
|
05690c425ee79081f22271fca6cad596
| 33.648649 | 155 | 0.610374 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.