repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
thislooksfun/Tavi
Tavi/Helper/Favorites.swift
1
2635
// // Favorites.swift // Tavi // // Copyright (C) 2016 thislooksfun // // 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 UIKit /// Manage favorite repos class Favorites { /// Called when the app is launched static func appStarted() { Settings.Favorites.onSet(favoritesSet) favoritesSet() } /// Gets the current favorites /// /// - Returns: A String array (`[String]`) of all the slugs of the favorited repos static func getFavorites() -> [String] { return Settings.Favorites.getWithDefault([]) } /// Called when `Settings.Favorites` is changed static func favoritesSet() { if let favorites = Settings.Favorites.get() { var favoriteShortcuts = [UIApplicationShortcutItem]() for slug in favorites { favoriteShortcuts.append(UIApplicationShortcutItem(type: "\(NSBundle.mainBundle().bundleIdentifier!).openFavorite", localizedTitle: slug, localizedSubtitle: "", icon: UIApplicationShortcutIcon(templateImageName: "icon-heart-outline"), userInfo: nil)) } UIApplication.sharedApplication().shortcutItems = favoriteShortcuts } } /// Toggles the favorited state of the given repo /// /// - Parameters: /// - slug: The slug of the repo to toggle /// - atIndex: the index to insert the favorite, if it doesn't already exist static func toggleFavorite(slug: String, atIndex: Int? = nil) { if var favorites = Settings.Favorites.get() { let index = favorites.indexOf(slug) if index != nil { favorites.removeAtIndex(favorites.startIndex.distanceTo(index!)) } else { if atIndex == nil { favorites.append(slug) } else { favorites.insert(slug, atIndex: atIndex!) } } Settings.Favorites.set(favorites) } else { Settings.Favorites.set([slug]) } } /// Checks whether or not a repo is favorited /// /// - Parameter slug: The slug to check /// /// - Returns: `true` if the repo is favorited, otherwise `false` static func isFavorite(slug: String) -> Bool { return Settings.Favorites.get()?.contains(slug) ?? false } }
gpl-3.0
bb4ea7f954bdef83e47ed16c474d21b1
31.146341
254
0.702467
3.863636
false
false
false
false
touchopia/HackingWithSwift
project8/Project8/ViewController.swift
1
3463
// // ViewController.swift // Project8 // // Created by TwoStraws on 15/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import GameplayKit import UIKit class ViewController: UIViewController { @IBOutlet weak var cluesLabel: UILabel! @IBOutlet weak var answersLabel: UILabel! @IBOutlet weak var currentAnswer: UITextField! @IBOutlet weak var scoreLabel: UILabel! var letterButtons = [UIButton]() var activatedButtons = [UIButton]() var solutions = [String]() var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var level = 1 override func viewDidLoad() { super.viewDidLoad() for subview in view.subviews where subview.tag == 1001 { let btn = subview as! UIButton letterButtons.append(btn) btn.addTarget(self, action: #selector(letterTapped), for: .touchUpInside) } loadLevel() } func letterTapped(btn: UIButton) { currentAnswer.text = currentAnswer.text! + btn.titleLabel!.text! activatedButtons.append(btn) btn.isHidden = true } func loadLevel() { var clueString = "" var solutionString = "" var letterBits = [String]() if let levelFilePath = Bundle.main.path(forResource: "level\(level)", ofType: "txt") { if let levelContents = try? String(contentsOfFile: levelFilePath) { var lines = levelContents.components(separatedBy: "\n") lines = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: lines) as! [String] for (index, line) in lines.enumerated() { let parts = line.components(separatedBy: ": ") let answer = parts[0] let clue = parts[1] clueString += "\(index + 1). \(clue)\n" let solutionWord = answer.replacingOccurrences(of: "|", with: "") solutionString += "\(solutionWord.characters.count) letters\n" solutions.append(solutionWord) let bits = answer.components(separatedBy: "|") letterBits += bits } } } cluesLabel.text = clueString.trimmingCharacters(in: .whitespacesAndNewlines) answersLabel.text = solutionString.trimmingCharacters(in: .whitespacesAndNewlines) letterBits = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: letterBits) as! [String] if letterBits.count == letterButtons.count { for i in 0 ..< letterBits.count { letterButtons[i].setTitle(letterBits[i], for: .normal) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func submitTapped(_ sender: AnyObject) { if let solutionPosition = solutions.index(of: currentAnswer.text!) { activatedButtons.removeAll() var splitClues = answersLabel.text!.components(separatedBy: "\n") splitClues[solutionPosition] = currentAnswer.text! answersLabel.text = splitClues.joined(separator: "\n") currentAnswer.text = "" score += 1 if score % 7 == 0 { let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Let's go!", style: .default, handler: levelUp)) present(ac, animated: true) } } } @IBAction func clearTapped(_ sender: AnyObject) { currentAnswer.text = "" for btn in activatedButtons { btn.isHidden = false } activatedButtons.removeAll() } func levelUp(action: UIAlertAction!) { level += 1 solutions.removeAll(keepingCapacity: true) loadLevel() for btn in letterButtons { btn.isHidden = false } } }
unlicense
9f3685f155258dc28f491e29084f0fc4
25.030075
121
0.696418
3.783607
false
false
false
false
tkremenek/swift
test/IRGen/dynamic_self_metadata.swift
20
2389
// RUN: %target-swift-frontend -disable-generic-metadata-prespecialization %s -emit-ir -parse-as-library | %FileCheck %s // UNSUPPORTED: OS=windows-msvc // REQUIRES: CPU=x86_64 // FIXME: Not a SIL test because we can't parse dynamic Self in SIL. // <rdar://problem/16931299> // CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }> @inline(never) func id<T>(_ t: T) -> T { return t } // CHECK-LABEL: define hidden swiftcc void @"$s21dynamic_self_metadata2idyxxlF" protocol P { associatedtype T } extension P { func f() {} } struct G<T> : P { var t: T } class C { class func fromMetatype() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC12fromMetatypeACXDSgyFZ"(%swift.type* swiftself %0) // CHECK: ret i64 0 func fromInstance() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC12fromInstanceACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself %0) // CHECK: ret i64 0 func dynamicSelfArgument() -> Self? { return id(nil) } // CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC0A12SelfArgumentACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself %0) // CHECK: [[GEP1:%.+]] = getelementptr {{.*}} %0 // CHECK: [[TYPE1:%.+]] = load {{.*}} [[GEP1]] // CHECK: [[T0:%.+]] = call swiftcc %swift.metadata_response @"$sSqMa"(i64 0, %swift.type* [[TYPE1]]) // CHECK: [[TYPE2:%.+]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: call swiftcc void @"$s21dynamic_self_metadata2idyxxlF"({{.*}}, %swift.type* [[TYPE2]]) func dynamicSelfConformingType() -> Self? { _ = G(t: self).f() return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC0A18SelfConformingTypeACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself %0) // CHECK: [[SELF_GEP:%.+]] = getelementptr {{.*}} %0 // CHECK: [[SELF_TYPE:%.+]] = load {{.*}} [[SELF_GEP]] // CHECK: [[METADATA_RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s21dynamic_self_metadata1GVMa"(i64 0, %swift.type* [[SELF_TYPE]]) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call i8** @swift_getWitnessTable(%swift.protocol_conformance_descriptor* bitcast ({{.*}} @"$s21dynamic_self_metadata1GVyxGAA1PAAMc" to %swift.protocol_conformance_descriptor*), %swift.type* [[METADATA]], i8*** undef) }
apache-2.0
882d5dedc8d186c374ed0c6f28a621a6
40.912281
228
0.664713
3.369535
false
false
false
false
SwiftFMI/iOS_2017_2018
Lectures/code/19.01.2018/CoreImageDemo/CoreImageDemo/ViewController.swift
1
1635
// // ViewController.swift // CoreImageDemo // // Created by Emil Atanasov on 19.01.18. // Copyright © 2018 SwiftFMI. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func applyFilter(_ sender: Any) { //https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP40004346 let filter = CIFilter(name: "CIGaussianBlur") if let _ = imageView.image?.ciImage { print("has CIImage") } if let _ = imageView.image?.cgImage { print("has CGImage") } let ciImage = CIImage(cgImage: (imageView.image?.cgImage!)!) filter?.setValue(ciImage, forKey: "inputImage") // filter?.setValue(CIColor.black, forKey: "inputColor") // filter?.setValue(1.0, forKey: "inputIntensity") let context = CIContext() // context. if let outputImage = filter?.outputImage { print("???") imageView.image = UIImage(cgImage: context.createCGImage(outputImage, from: ciImage.extent)!) } } }
apache-2.0
d442a46d04d5a81ded2ad0c5d13e1ee2
25.786885
160
0.585067
4.892216
false
false
false
false
mihyaeru21/Aurum
Example/Tests/ProductsRequestHandlerSpec.swift
1
2045
// // ProductsRequestHandlerSpec.swift // Aurum // // Created by Mihyaeru on 7/19/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import StoreKit import Quick import Nimble import Aurum private var dummyStart : () -> () = {} extension SKProductsRequest { override public func start() { dummyStart() } } class DummyResponse: SKProductsResponse { override var products : [SKProduct] { get { return [] } } override var invalidProductIdentifiers : [String] { get{ return [] } } override init() { super.init() } } class ProductsRequestHandlerSpec: QuickSpec { override func spec() { let handler = ProductsRequestHandler() describe("request") { it ("calls SKProcuctsRequest#start") { var called = 0 dummyStart = { called++ } handler.request(productIds: Set(["hoge_id"])) expect(called) == 1 } it("calls onStarted callback") { var called = 0 handler.onStarted = { (_, _) in called++ } handler.request(productIds: Set(["hoge_id"])) expect(called) == 1 } } describe("productsRequest:didReceiveResponse:") { it("calls onSuccess callback") { var called = 0 handler.onSuccess = { _ in called++ } handler.productsRequest(SKProductsRequest(productIdentifiers: Set([])), didReceiveResponse: DummyResponse()) expect(called) == 1 } } describe("request:didFailWithError:") { it("calls onFailure callback") { var called = 0 handler.onFailure = { _ in called++ } handler.request(SKProductsRequest(productIdentifiers: Set([])), didFailWithError: NSError(domain: Aurum.ErrorDomain, code: Aurum.Error.InvalidProductId.rawValue, userInfo: [:] as [NSObject: AnyObject])) expect(called) == 1 } } } }
mit
7df9aa555099529aa26520888f881cc6
29.522388
218
0.56088
4.701149
false
false
false
false
CalvinChina/Demo
Swift3Demo/Swift3Demo/AlertController/AlertViewController.swift
1
3672
// // AlertViewController.swift // Swift3Demo // // Created by pisen on 16/9/18. // Copyright © 2016年 丁文凯. All rights reserved. // import UIKit class AlertViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func ShowAlert(_ sender: UIButton) { let alertController = UIAlertController(title:"你好",message:"你是最棒的",preferredStyle:UIAlertControllerStyle.alert) let cancelAction = UIAlertAction(title:"Cancel",style:.cancel){_ in print("this is so unbelivable!") } alertController.addAction(cancelAction) let okAction = UIAlertAction(title:"OK",style:.default){_ in print("点击了👌") } alertController.addAction(okAction) self.present(alertController, animated: true, completion:{ () -> Void in //your code here }) } @IBAction func ShowActionSheet(_ sender: AnyObject) { let alertController = UIAlertController(title: "My Title", message: "This is an alert", preferredStyle:UIAlertControllerStyle.actionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in print("you have pressed the Cancel button"); } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "OK", style: .default) { _ in print("you have pressed OK button"); } alertController.addAction(OKAction) self.present(alertController, animated: true, completion:{ () -> Void in //your code here }) } @IBAction func AlertWithForm(_ sender: UIButton) { let alertController = UIAlertController(title:"123",message:"你是🐖么?",preferredStyle:.alert) let cancelAction = UIAlertAction(title:"不是",style:.cancel){_ in print("那你是🐶么") } alertController.addAction(cancelAction) let okAction = UIAlertAction(title:"你才是",style:.default){_ in print("you have pressed OK button"); let userName = alertController.textFields![0].text let password = alertController.textFields![1].text self.doSomething(userName, password: password) } alertController.addAction(okAction) alertController.addTextField { (textField:UITextField) in textField.placeholder = "userName" textField.isSecureTextEntry = false } alertController.addTextField { (textField:UITextField) in textField.placeholder = "password" textField.isSecureTextEntry = true } self.present(alertController, animated: true, completion:{ () -> Void in //your code here }) } func doSomething(_ userName: String?, password: String?) { print("username: \(userName ?? "") password: \(password ?? "")") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
cb338ce996a230d0859e438febbe435e
33.037736
146
0.610588
5.169054
false
false
false
false
ddaguro/clintonconcord
OIMApp/ApprovalDetailCell.swift
1
2174
// // ApprovalDetailCell.swift // OIMApp // // Created by Linh NGUYEN on 2/16/16. // Copyright © 2016 Persistent Systems. All rights reserved. // import UIKit class ApprovalDetailCell: UITableViewCell { @IBOutlet var requestType : UILabel! @IBOutlet var entityName : UILabel! @IBOutlet var assignee: UILabel! @IBOutlet var requestDate: UILabel! @IBOutlet var requestId: UILabel! @IBOutlet var justification: UILabel! @IBOutlet var requestStatus: UILabel! @IBOutlet var avatar: UIImageView! @IBOutlet var taskTitle: UILabel! @IBOutlet var taskAssignedOn: UILabel! @IBOutlet var timelineStart: UIImageView! override func awakeFromNib() { assignee.font = UIFont(name: MegaTheme.fontName, size: 14) assignee.textColor = MegaTheme.darkColor requestDate.font = UIFont(name: MegaTheme.fontName, size: 10) requestDate.textColor = MegaTheme.lightColor requestId.font = UIFont(name: MegaTheme.fontName, size: 10) requestId.textColor = MegaTheme.lightColor /* requestStatus.layer.cornerRadius = 8 requestStatus.layer.masksToBounds = true requestStatus.font = UIFont(name: MegaTheme.fontName, size: 10) requestStatus.textColor = UIColor.whiteColor() */ requestType.font = UIFont(name: MegaTheme.fontName, size: 12) requestType.textColor = MegaTheme.darkColor entityName.font = UIFont(name: MegaTheme.fontName, size: 12) entityName.textColor = MegaTheme.lightColor justification.font = UIFont(name: MegaTheme.fontName, size: 12) justification.textColor = MegaTheme.lightColor // start timeline timelineStart.image = UIImage(named: "timeline-start") taskTitle.layer.cornerRadius = 8 taskTitle.layer.masksToBounds = true taskTitle.font = UIFont(name: MegaTheme.fontName, size: 10) taskTitle.textColor = UIColor.whiteColor() taskAssignedOn.font = UIFont(name: MegaTheme.fontName, size: 10) taskAssignedOn.textColor = MegaTheme.lightColor } }
mit
faf2cb23300da662c2f481c1bb61829d
32.96875
72
0.668661
4.796909
false
false
false
false
sayanee/ios-learning
Psychologist/Psychologist/FaceView.swift
2
3714
// // FaceView.swift // Happiness // // Created by Sayanee Basu on 30/12/15. // Copyright © 2015 Sayanee Basu. All rights reserved. // import UIKit protocol FaceViewDataSource { func smilinessForFaceView(sender: FaceView) -> Double? } @IBDesignable class FaceView: UIView { @IBInspectable var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } } @IBInspectable var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } @IBInspectable var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } } private var faceCenter: CGPoint { return convertPoint(center, fromView: superview) } private var faceRadius: CGFloat { return min(bounds.size.width, bounds.size.height) / 2 * scale } var dataSource: FaceViewDataSource? func scale(gesture: UIPinchGestureRecognizer) { if gesture.state == .Changed { scale *= gesture.scale gesture.scale = 1 } } private struct Scaling { static let FaceRadiusToEyeRadiusRatio: CGFloat = 10 static let FaceRadiusToEyeOffsetRatio: CGFloat = 3 static let FaceRadiusToEyeSeperationRatio: CGFloat = 1.5 static let FaceRadiusToMouthWidthRatio: CGFloat = 1 static let FaceRadiusToMouthHeightRatio: CGFloat = 3 static let FaceRadiusToMouthOffsetRatio: CGFloat = 3 } private enum Eye { case Left, Right } private func bezierPathForEye(whichEye: Eye) -> UIBezierPath { let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio let eyeHorizontalSeperation = faceRadius / Scaling.FaceRadiusToEyeSeperationRatio var eyeCenter = faceCenter eyeCenter.y -= eyeVerticalOffset switch whichEye { case .Left: eyeCenter.x -= eyeHorizontalSeperation / 2 case .Right: eyeCenter.x += eyeHorizontalSeperation / 2 } let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true) path.lineWidth = lineWidth return path } private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath { let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset) let end = CGPoint(x: start.x + mouthWidth, y: start.y) let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight) let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y) let path = UIBezierPath() path.moveToPoint(start) path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } override func drawRect(rect: CGRect) { let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true) facePath.lineWidth = lineWidth color.set() facePath.stroke() bezierPathForEye(.Left).stroke() bezierPathForEye(.Right).stroke() let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0 let smilePath = bezierPathForSmile(smiliness) smilePath.stroke() } }
mit
9e846b105ea24d30325d85ee751df0b5
34.028302
137
0.652572
4.859948
false
false
false
false
JARMourato/JMProjectEuler
JMProjectEuler/Problems/1-10/2.swift
1
1251
// // 2.swift // JMProjectEuler // // Created by iOS on 26/12/15. // Copyright © 2015 JARM. All rights reserved. // /* PROBLEM - 2 : Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ extension EulerProblem { public mutating func solutionAlgorithmForProblem2(n : Int) { var res : Int = 0 var array : [Int] = [1,2] var index : Int = 2 var current : Int = 3 if (n < 3) { return } while(true) { if current < n { current = array[index-2] + array[index - 1] array.append(current) index+=1 } else { break } } let filtered = array.filter { $0 % 2 == 0 } res = filtered.reduce(0, combine: +) result = res } public mutating func sumOfEvenFibonacciNumbersUpTo4Million(){ solutionAlgorithmForProblem2(4000000) } }
mit
65b1af62e3923bd76434f3cf61d85c78
25.595745
140
0.5552
3.955696
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Charts/PieRadarChartViewBase.swift
2
27361
// // PieRadarChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base class of PieChartView and RadarChartView. open class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not @objc open var rotationEnabled = true /// Sets the minimum offset (padding) around the chart, defaults to 0.0 @objc open var minOffset = CGFloat(0.0) /// iOS && OSX only: Enabled multi-touch rotation using two fingers. private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) private var _rotationGestureRecognizer: NSUIRotationGestureRecognizer! #endif public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:))) self.addGestureRecognizer(_tapGestureRecognizer) #if !os(tvOS) _rotationGestureRecognizer = NSUIRotationGestureRecognizer(target: self, action: #selector(rotationGestureRecognized(_:))) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.isEnabled = rotationWithTwoFingers #endif } internal override func calcMinMax() { /*_xAxis.axisRange = Double((_data?.xVals.count ?? 0) - 1)*/ } open override var maxVisibleCount: Int { get { return data?.entryCount ?? 0 } } open override func notifyDataSetChanged() { calcMinMax() if let data = _data , _legend !== nil { legendRenderer.computeLegend(data: data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if _legend != nil && _legend.enabled && !_legend.drawInside { let fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) switch _legend.orientation { case .vertical: var xLegendOffset: CGFloat = 0.0 if _legend.horizontalAlignment == .left || _legend.horizontalAlignment == .right { if _legend.verticalAlignment == .center { // this is the space between the legend and the chart let spacing = CGFloat(13.0) xLegendOffset = fullLegendWidth + spacing } else { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomX = _legend.horizontalAlignment == .right ? self.bounds.width - legendWidth + 15.0 : legendWidth - 15.0 let bottomY = legendHeight + 15 let distLegend = distanceToCenter(x: bottomX, y: bottomY) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomX, y: bottomY)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if bottomY >= c.y && self.bounds.height - legendWidth > self.bounds.width { xLegendOffset = legendWidth } else if distLegend < distReference { let diff = distReference - distLegend xLegendOffset = minOffset + diff } } } switch _legend.horizontalAlignment { case .left: legendLeft = xLegendOffset case .right: legendRight = xLegendOffset case .center: switch _legend.verticalAlignment { case .top: legendTop = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) case .bottom: legendBottom = min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) default: break } } case .horizontal: var yLegendOffset: CGFloat = 0.0 if _legend.verticalAlignment == .top || _legend.verticalAlignment == .bottom { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = self.requiredLegendOffset yLegendOffset = min( _legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } switch _legend.verticalAlignment { case .top: legendTop = yLegendOffset case .bottom: legendBottom = yLegendOffset default: break } } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset legendBottom += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = self.minOffset if self is RadarChartView { let x = self.xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(minOffset, x.labelRotatedWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: The angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... @objc open func angleForPoint(x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r.RAD2DEG if x > c.x { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if angle > 360.0 { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. @objc open func getPosition(center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle.DEG2RAD), y: center.y + dist * sin(angle.DEG2RAD)) } /// - returns: The distance of a certain point on the chart to the center of the chart. @objc open func distanceToCenter(x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if x > c.x { xDist = x - c.x } else { xDist = c.x - x } if y > c.y { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: The xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. @objc open func indexForAngle(_ angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: Will always return a normalized value, which will be between 0.0 < 360.0 @objc open var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = newValue.normalizedAngle setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. @objc open var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: The diameter of the pie- or radar-chart @objc open var diameter: CGFloat { var content = _viewPortHandler.contentRect content.origin.x += extraLeftOffset content.origin.y += extraTopOffset content.size.width -= extraLeftOffset + extraRightOffset content.size.height -= extraTopOffset + extraBottomOffset return min(content.width, content.height) } /// - returns: The radius of the chart in pixels. @objc open var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: The required offset for the chart legend. internal var requiredLegendOffset: CGFloat { fatalError("requiredLegendOffset cannot be called on PieRadarChartViewBase") } /// - returns: The base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } open override var chartYMax: Double { return 0.0 } open override var chartYMin: Double { return 0.0 } @objc open var isRotationEnabled: Bool { return rotationEnabled } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false @objc open var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue #if !os(tvOS) _rotationGestureRecognizer.isEnabled = _rotationWithTwoFingers #endif } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// On iOS this will disable one-finger rotation. /// On OSX this will keep two-finger multitouch rotation, and one-pointer mouse rotation. /// /// **default**: false @objc open var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: Animator! /// Applys a spin animation to the Chart. @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if _spinAnimator != nil { _spinAnimator.stop() } _spinAnimator = Animator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * CGFloat(self._spinAnimator.phaseX) + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } @objc open func spin(duration: TimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } @objc open func stopSpinAnimation() { if _spinAnimator != nil { _spinAnimator.stop() } } // MARK: - Gestures private var _rotationGestureStartPoint: CGPoint! private var _isRotating = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: TimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: TimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 internal final func processRotationGestureBegan(location: CGPoint) { self.resetVelocity() if rotationEnabled { self.sampleVelocity(touchLocation: location) } self.setGestureStartAngle(x: location.x, y: location.y) _rotationGestureStartPoint = location } internal final func processRotationGestureMoved(location: CGPoint) { if isDragDecelerationEnabled { sampleVelocity(touchLocation: location) } if !_isRotating && distance( eventX: location.x, startX: _rotationGestureStartPoint.x, eventY: location.y, startY: _rotationGestureStartPoint.y) > CGFloat(8.0) { _isRotating = true } else { self.updateGestureRotation(x: location.x, y: location.y) setNeedsDisplay() } } internal final func processRotationGestureEnded(location: CGPoint) { if isDragDecelerationEnabled { stopDeceleration() sampleVelocity(touchLocation: location) _decelerationAngularVelocity = calculateVelocity() if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common) } } } internal final func processRotationGestureCancelled() { if _isRotating { _isRotating = false } } #if !os(OSX) open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() if !rotationWithTwoFingers, let touchLocation = touches.first?.location(in: self) { processRotationGestureBegan(location: touchLocation) } } if !_isRotating { super.nsuiTouchesBegan(touches, withEvent: event) } } open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if rotationEnabled && !rotationWithTwoFingers, let touch = touches.first { let touchLocation = touch.location(in: self) processRotationGestureMoved(location: touchLocation) } if !_isRotating { super.nsuiTouchesMoved(touches, withEvent: event) } } open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_isRotating { super.nsuiTouchesEnded(touches, withEvent: event) } if rotationEnabled && !rotationWithTwoFingers, let touch = touches.first { let touchLocation = touch.location(in: self) processRotationGestureEnded(location: touchLocation) } if _isRotating { _isRotating = false } } open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.nsuiTouchesCancelled(touches, withEvent: event) processRotationGestureCancelled() } #endif #if os(OSX) open override func mouseDown(with theEvent: NSEvent) { // if rotation by touch is enabled if rotationEnabled { stopDeceleration() let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureBegan(location: location) } if !_isRotating { super.mouseDown(with: theEvent) } } open override func mouseDragged(with theEvent: NSEvent) { if rotationEnabled { let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureMoved(location: location) } if !_isRotating { super.mouseDragged(with: theEvent) } } open override func mouseUp(with theEvent: NSEvent) { if !_isRotating { super.mouseUp(with: theEvent) } if rotationEnabled { let location = self.convert(theEvent.locationInWindow, from: nil) processRotationGestureEnded(location: location) } if _isRotating { _isRotating = false } } #endif private func resetVelocity() { _velocitySamples.removeAll(keepingCapacity: false) } private func sampleVelocity(touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds var i = 0, count = _velocitySamples.count while (i < count - 2) { if currentTime - _velocitySamples[i].time > 1.0 { _velocitySamples.remove(at: 0) i -= 1 count -= 1 } else { break } i += 1 } } private func calculateVelocity() -> CGFloat { if _velocitySamples.isEmpty { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for i in stride(from: (_velocitySamples.count - 1), through: 0, by: -1) { beforeLastSample = _velocitySamples[i] if beforeLastSample.angle != lastSample.angle { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if timeDelta == 0.0 { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if lastSample.angle - firstSample.angle > 180.0 { firstSample.angle += 360.0 } else if firstSample.angle - lastSample.angle > 180.0 { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if !clockwise { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } @objc open func stopDeceleration() { if _decelerationDisplayLink !== nil { _decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoop.Mode.common) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: The distance between two points private func distance(eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: The distance between two points private func distance(from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: Highlight! @objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if recognizer.state == NSUIGestureRecognizerState.ended { if !self.isHighLightPerTapEnabled { return } let location = recognizer.location(in: self) let high = self.getHighlightByTouchPoint(location) self.highlightValue(high, callDelegate: true) } } #if !os(tvOS) @objc private func rotationGestureRecognized(_ recognizer: NSUIRotationGestureRecognizer) { if recognizer.state == NSUIGestureRecognizerState.began { stopDeceleration() _startAngle = self.rawRotationAngle } if recognizer.state == NSUIGestureRecognizerState.began || recognizer.state == NSUIGestureRecognizerState.changed { let angle = recognizer.nsuiRotation.RAD2DEG self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if recognizer.state == NSUIGestureRecognizerState.ended { let angle = recognizer.nsuiRotation.RAD2DEG self.rotationAngle = _startAngle + angle setNeedsDisplay() if isDragDecelerationEnabled { stopDeceleration() _decelerationAngularVelocity = recognizer.velocity.RAD2DEG if _decelerationAngularVelocity != 0.0 { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(PieRadarChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common) } } } } #endif }
apache-2.0
f667a3799ed9c1d781d5e2c78a75b8bb
30.590069
191
0.553752
5.629012
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressShareExtension/UIImage+Extensions.swift
2
1046
import Foundation import ImageIO extension UIImage { convenience init?(contentsOfURL url: URL) { guard let rawImage = try? Data(contentsOf: url) else { return nil } self.init(data: rawImage) } func resizeWithMaximumSize(_ maximumSize: CGSize) -> UIImage? { let options: [CFString: Any] = [ kCGImageSourceCreateThumbnailFromImageIfAbsent: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: maximumSize, ] guard let imageData = pngData() as CFData?, let imageSource = CGImageSourceCreateWithData(imageData, nil), let image = CGImageSourceCreateImageAtIndex(imageSource, 0, options as CFDictionary) else { return nil } return UIImage(cgImage: image) } func JPEGEncoded(_ quality: CGFloat = 0.8) -> Data? { return self.jpegData(compressionQuality: quality) } }
gpl-2.0
b08b1b390a86308707c5131e29fa69e3
29.764706
105
0.643403
5.47644
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/UnneededParenthesesInClosureArgumentRule.swift
1
5467
import SwiftSyntax struct UnneededParenthesesInClosureArgumentRule: ConfigurationProviderRule, SwiftSyntaxCorrectableRule, OptInRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "unneeded_parentheses_in_closure_argument", name: "Unneeded Parentheses in Closure Argument", description: "Parentheses are not needed when declaring closure arguments.", kind: .style, nonTriggeringExamples: [ Example("let foo = { (bar: Int) in }\n"), Example("let foo = { bar, _ in }\n"), Example("let foo = { bar in }\n"), Example("let foo = { bar -> Bool in return true }\n"), Example(""" DispatchQueue.main.async { () -> Void in doSomething() } """), Example(""" registerFilter(name) { any, args throws -> Any? in doSomething(any, args) } """, excludeFromDocumentation: true) ], triggeringExamples: [ Example("call(arg: { ↓(bar) in })\n"), Example("call(arg: { ↓(bar, _) in })\n"), Example("let foo = { ↓(bar) -> Bool in return true }\n"), Example("foo.map { ($0, $0) }.forEach { ↓(x, y) in }"), Example("foo.bar { [weak self] ↓(x, y) in }"), Example(""" [].first { ↓(temp) in [].first { ↓(temp) in [].first { ↓(temp) in _ = temp return false } return false } return false } """), Example(""" [].first { temp in [].first { ↓(temp) in [].first { ↓(temp) in _ = temp return false } return false } return false } """), Example(""" registerFilter(name) { ↓(any, args) throws -> Any? in doSomething(any, args) } """, excludeFromDocumentation: true) ], corrections: [ Example("call(arg: { ↓(bar) in })\n"): Example("call(arg: { bar in })\n"), Example("call(arg: { ↓(bar, _) in })\n"): Example("call(arg: { bar, _ in })\n"), Example("call(arg: { ↓(bar, _)in })\n"): Example("call(arg: { bar, _ in })\n"), Example("let foo = { ↓(bar) -> Bool in return true }\n"): Example("let foo = { bar -> Bool in return true }\n"), Example("method { ↓(foo, bar) in }\n"): Example("method { foo, bar in }\n"), Example("foo.map { ($0, $0) }.forEach { ↓(x, y) in }"): Example("foo.map { ($0, $0) }.forEach { x, y in }"), Example("foo.bar { [weak self] ↓(x, y) in }"): Example("foo.bar { [weak self] x, y in }") ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: ClosureSignatureSyntax) { guard let clause = node.input?.as(ParameterClauseSyntax.self), !clause.parameterList.contains(where: { $0.type != nil }), clause.parameterList.isNotEmpty else { return } violations.append(clause.positionAfterSkippingLeadingTrivia) } } private final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] let locationConverter: SourceLocationConverter let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: ClosureSignatureSyntax) -> ClosureSignatureSyntax { guard let clause = node.input?.as(ParameterClauseSyntax.self), !clause.parameterList.contains(where: { $0.type != nil }), clause.parameterList.isNotEmpty, !node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else { return super.visit(node) } let items = clause.parameterList.enumerated().compactMap { idx, param -> ClosureParamSyntax? in guard let name = param.firstName else { return nil } let isLast = idx == clause.parameterList.count - 1 return ClosureParamSyntax( name: name, trailingComma: isLast ? nil : .commaToken(trailingTrivia: Trivia(pieces: [.spaces(1)])) ) } correctionPositions.append(clause.positionAfterSkippingLeadingTrivia) let paramList = ClosureParamListSyntax(items).withTrailingTrivia(.spaces(1)) return super.visit(node.withInput(.init(paramList))) } }
mit
61b12758b73b2c606a4a1259b3768ba1
38.071942
120
0.528448
4.914932
false
false
false
false
eito/geometry-api-swift
Geometry/Geometry/MathUtils.swift
1
6874
// // MathUtils.swift // Geometry // // Created by Eric Ito on 10/25/15. // Copyright © 2015 Eric Ito. All rights reserved. // import Foundation final class MathUtils { /** The implementation of the Kahan summation algorithm. Use to get better precision when adding a lot of values. */ final class KahanSummator { /** The accumulated sum */ private var sum: Double = 0.0 private var compensation: Double = 0.0 /** the Base (the class returns sum + startValue) */ private var startValue: Double = 0.0 /** initialize to the given start value. \param startValue_ The value to be added to the accumulated sum. */ init(startValue: Double) { self.startValue = startValue reset() } /** Resets the accumulated sum to zero. The getResult() returns startValue_ after this call. */ func reset() { sum = 0 compensation = 0 } /** add a value. */ func add(v: Double) { let y: Double = v - compensation let t: Double = sum + y let h: Double = t - sum compensation = h - y sum = t; } /** Subtracts a value. */ func sub(v: Double) { add(-v) } /** add another summator. */ func add(/* const */ v: KahanSummator) { let y: Double = (v.result() + v.compensation) - compensation let t: Double = sum + y let h: Double = t - sum compensation = h - y sum = t } /** Subtracts another summator. */ func sub(/* const */ v: KahanSummator) { let y: Double = -(v.result() - v.compensation) - compensation let t: Double = sum + y let h: Double = t - sum compensation = h - y sum = t } /** Returns current value of the sum. */ func result() -> Double /* const */{ return startValue + sum } } /** Returns one value with the sign of another (like copysign). */ class func copySign(x: Double, y: Double) -> Double { return y >= 0.0 ? abs(x) : -abs(x) } /** Calculates sign of the given value. Returns 0 if the value is equal to 0. */ class func sign(value: Double) -> Int { return value < 0 ? -1 : (value > 0) ? 1 : 0; } /** C fmod function. */ class func FMod(x: Double, y: Double) -> Double { return x - floor(x / y) * y } /** Rounds double to the closest integer value. */ class func round(v: Double) -> Double { return floor(v + 0.5) } class func sqr(v: Double) -> Double { return v * v } /** Computes interpolation between two values, using the interpolation factor t. The interpolation formula is (end - start) * t + start. However, the computation ensures that t = 0 produces exactly start, and t = 1, produces exactly end. It also guarantees that for 0 <= t <= 1, the interpolated value v is between start and end. */ class func lerp(start_: Double, end_: Double,t: Double) -> Double { // When end == start, we want result to be equal to start, for all t // values. At the same time, when end != start, we want the result to be // equal to start for t==0 and end for t == 1.0 // The regular formula end_ * t + (1.0 - t) * start_, when end_ == // start_, and t at 1/3, produces value different from start var v: Double = 0 if t <= 0.5 { v = start_ + (end_ - start_) * t } else { v = end_ - (end_ - start_) * (1.0 - t) } assert (t < 0 || t > 1.0 || (v >= start_ && v <= end_) || (v <= start_ && v >= end_) || NumberUtils.isNaN(start_) || NumberUtils.isNaN(end_)) return v } /** Computes interpolation between two values, using the interpolation factor t. The interpolation formula is (end - start) * t + start. However, the computation ensures that t = 0 produces exactly start, and t = 1, produces exactly end. It also guarantees that for 0 <= t <= 1, the interpolated value v is between start and end. */ class func lerp(start_: Point2D , end_: Point2D , t: Double, result: Point2D ) { // When end == start, we want result to be equal to start, for all t // values. At the same time, when end != start, we want the result to be // equal to start for t==0 and end for t == 1.0 // The regular formula end_ * t + (1.0 - t) * start_, when end_ == // start_, and t at 1/3, produces value different from start if t <= 0.5 { result.x = start_.x + (end_.x - start_.x) * t result.y = start_.y + (end_.y - start_.y) * t } else { result.x = end_.x - (end_.x - start_.x) * (1.0 - t) result.y = end_.y - (end_.y - start_.y) * (1.0 - t) } assert (t < 0 || t > 1.0 || (result.x >= start_.x && result.x <= end_.x) || (result.x <= start_.x && result.x >= end_.x)) assert (t < 0 || t > 1.0 || (result.y >= start_.y && result.y <= end_.y) || (result.y <= start_.y && result.y >= end_.y)) } class func lerp(start_x: Double, start_y: Double, end_x: Double, end_y: Double, t: Double, result: Point2D) { // When end == start, we want result to be equal to start, for all t // values. At the same time, when end != start, we want the result to be // equal to start for t==0 and end for t == 1.0 // The regular formula end_ * t + (1.0 - t) * start_, when end_ == // start_, and t at 1/3, produces value different from start if t <= 0.5 { result.x = start_x + (end_x - start_x) * t result.y = start_y + (end_y - start_y) * t } else { result.x = end_x - (end_x - start_x) * (1.0 - t) result.y = end_y - (end_y - start_y) * (1.0 - t) } assert (t < 0 || t > 1.0 || (result.x >= start_x && result.x <= end_x) || (result.x <= start_x && result.x >= end_x)) assert (t < 0 || t > 1.0 || (result.y >= start_y && result.y <= end_y) || (result.y <= start_y && result.y >= end_y)) } } // MARK: Operators for KahanSummator func +=(inout left: MathUtils.KahanSummator, right: Double) { left.add(right) } func -=(inout left: MathUtils.KahanSummator, right: Double) { left.add(-right) } func +=(inout left: MathUtils.KahanSummator, right: MathUtils.KahanSummator) { left.add(right) } func -=(inout left: MathUtils.KahanSummator, right: MathUtils.KahanSummator) { left.sub(right) }
apache-2.0
98a0584a6dd73e3fc2d285e522d2fa83
34.984293
149
0.521897
3.673437
false
false
false
false
wjk930726/CCColorPinker
CCColorPinker/CCColorPinker/Extension/Extension.swift
1
1843
// // Extension.swift // CCColorPinker // // Created by 王靖凯 on 2017/8/5. // Copyright © 2017年 王靖凯. All rights reserved. // import UIKit extension UIColor { class func colorWithHex(hex: UInt32) -> UIColor { let red: CGFloat = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green: CGFloat = CGFloat((hex & 0xFF00) >> 8) / 255.0 let blue: CGFloat = CGFloat(hex & 0xFF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } class func randomColor() -> UIColor { return UIColor(red: CGFloat(Double(arc4random_uniform(256)) / 255.0), green: CGFloat(Double(arc4random_uniform(256)) / 255.0), blue: CGFloat(Double(arc4random_uniform(256)) / 255.0), alpha: 1.0) } } extension UILabel { convenience init(text: String? = nil, fontSize: CGFloat? = nil, color: UIColor? = nil) { self.init() self.text = text if let fontSize = fontSize { font = UIFont.systemFont(ofSize: fontSize) } if let color = color { textColor = color } } } extension UIButton { convenience init(title: String? = nil, fontSize: CGFloat? = nil, color: UIColor? = nil, highlightedColor: UIColor? = nil, target: Any? = nil, action: Selector? = nil, event: UIControlEvents = .touchUpInside) { self.init() setTitle(title, for: .normal) if let fontSize = fontSize { titleLabel?.font = UIFont.systemFont(ofSize: fontSize) } if let color = color { setTitleColor(color, for: .normal) } if let highlightedColor = highlightedColor { setTitleColor(highlightedColor, for: .highlighted) } if let target = target, let action = action { addTarget(target, action: action, for: event) } } }
mit
909cd53149223b4a1078050e1c4c74aa
32.851852
213
0.599562
3.864693
false
false
false
false
keshavvishwkarma/KVConstraintKit
KVConstraintKit/KVConstraintKit.swift
1
14330
// // KVConstraintKit.swift // https://github.com/keshavvishwkarma/KVConstraintKit.git // // Distributed under the MIT License. // // Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. 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. // // #if os(iOS) || os(tvOS) import UIKit public typealias View = UIView @available(iOS 9.0, *) public typealias LayoutGuide = UILayoutGuide public typealias EdgeInsets = UIEdgeInsets public typealias LayoutPriority = UILayoutPriority #if swift(>=4.2) public typealias LayoutRelation = NSLayoutConstraint.Relation public typealias LayoutAttribute = NSLayoutConstraint.Attribute #else public typealias LayoutRelation = NSLayoutRelation public typealias LayoutAttribute = NSLayoutAttribute #endif #elseif os(OSX) import AppKit public typealias View = NSView @available(OSX 10.11, *) public typealias LayoutGuide = NSLayoutGuide #if !swift(>=3.0) || swift(>=4.0) public typealias EdgeInsets = NSEdgeInsets #endif #if swift(>=4.0) public typealias LayoutRelation = NSLayoutConstraint.Relation public typealias LayoutAttribute = NSLayoutConstraint.Attribute public typealias LayoutPriority = NSLayoutConstraint.Priority #else public typealias LayoutRelation = NSLayoutRelation public typealias LayoutAttribute = NSLayoutAttribute public typealias LayoutPriority = NSLayoutPriority #endif extension EdgeInsets { public static var zero: EdgeInsets { return EdgeInsets() } } #endif /// MARK: TO PREPARE VIEW FOR CONSTRAINTS /// Types adopting the `AutoLayoutView` protocol can be used to construct views or layout guides. public protocol AutoLayoutView: class { init() } extension AutoLayoutView { /// A method that allows you to create and return new instance of ui elements for autolayout. /// - parameter closure: The closure should take one parameter and have no return value. /// - returns: The newly created instance. public static func prepareAutoLayoutView(_ closure: @escaping (Self) -> Void = { _ in } ) -> Self { let preparedView = Self() if let view = preparedView as? View { view.translatesAutoresizingMaskIntoConstraints = false } closure(preparedView) return preparedView } } extension AutoLayoutView where Self: View { /// A method that allows you to prepare already created instance of ui elements for autolayout. public func prepareAutoLayoutView() -> Self { translatesAutoresizingMaskIntoConstraints = false; return self } /// This method adds the specified views or layout guides to the receiver's view. @discardableResult public static func + (lhs: Self, rhs: AutoLayoutView) -> Self { if let view = rhs as? View { lhs.addSubview(view.prepareAutoLayoutView()) } if #available(iOS 9.0, OSX 10.11, *), let guide = rhs as? LayoutGuide { lhs.addLayoutGuide(guide) } return lhs } } /// An `View`, `LayoutGuide` are adopting\confirmming `AutoLayoutView`. extension View : AutoLayoutView {} @available(iOS 9.0, OSX 10.11, *) extension LayoutGuide : AutoLayoutView {} /// MARK: TO PREPARE CONSTRAINTS extension View { /// Generalized public constraint methods for views. public final func prepareConstraintToSuperview( attribute attr1: LayoutAttribute, attribute attr2:LayoutAttribute, relation: LayoutRelation = .equal, multiplier:CGFloat = 1.0 ) -> NSLayoutConstraint { assert(superview != nil, "You should have `addSubView` on any other view, called `superview` of receiver’s \(self)"); #if os(iOS) || os(tvOS) switch attr1 { case .right, .rightMargin, .trailing, .trailingMargin, .bottom, .bottomMargin: return View.prepareConstraint(superview, attribute: attr1, secondView: self, attribute:attr2, relation: relation, multiplier:multiplier) default: break } #else switch attr1 { case .right, .trailing, .bottom: return View.prepareConstraint(superview, attribute: attr1, secondView: self, attribute:attr2, relation: relation, multiplier:multiplier) default: break } #endif return View.prepareConstraint(self, attribute: attr1, secondView: superview, attribute:attr2, relation: relation, multiplier:multiplier) } /// Prepare constraint of one sibling view to other sibling view and add it into its superview view. public final func prepareConstraintFromSiblingView(attribute attr1: LayoutAttribute, toAttribute attr2:LayoutAttribute, of otherView: View, relation:LayoutRelation = .equal, multiplier:CGFloat = 1.0 ) -> NSLayoutConstraint { assert(((NSSet(array: [superview!,otherView.superview!])).count == 1), "All the sibling views must belong to same superview") return View.prepareConstraint(self, attribute: attr1, secondView:otherView, attribute:attr2, relation:relation, multiplier: multiplier ) } } /// TO APPLY/ADD CONSTRAINTS OR TO REMOVE APPLIED CONSTRAINTS extension View { /// This is the common methods to add the constraint in the receiver only once. If constraint already exists then it will only update that constraint and return that constraint. public final func applyPreparedConstraintInView(constraint c: NSLayoutConstraint) -> NSLayoutConstraint { // If this constraint is already added then it update the constraint values else added new constraint. let appliedConstraint = constraints.containsApplied(constraint: c) if (appliedConstraint != nil) { appliedConstraint!.constant = c.constant if appliedConstraint!.multiplier != c.multiplier || appliedConstraint!.relation != c.relation { self - appliedConstraint! } else{ return appliedConstraint! } } addConstraint(c) return c } public final func applyConstraintFromSiblingView(attribute attr1: LayoutAttribute, toAttribute attr2:LayoutAttribute, of otherView: View, constant:CGFloat) -> NSLayoutConstraint { assert(!constant.isInfinite, "constant of view must not be INFINITY.") assert(!constant.isNaN, "constant of view must not be NaN.") let c = self.prepareConstraintFromSiblingView(attribute: attr1, toAttribute: attr2, of: otherView) c.constant = constant return self.superview! + c } /// MARK: - Remove Constraints From a specific View public final func removedConstraintFromSupreview() { let superview = self.superview removeFromSuperview() superview?.addSubview(self) } public final func removedAllConstraints() { removedConstraintFromSupreview() removeConstraints(constraints) } } /// MARK: TO ACCESS APPLIED CONSTRAINTS extension View { // MARK: - To Access Applied Constraint By Attributes From a specific View. public final func accessAppliedConstraintBy(attribute attr: LayoutAttribute, relation: LayoutRelation = .equal)->NSLayoutConstraint? { if (attr == .width || attr == .height) { let appliedConstraint = accessAppliedConstraintBy(attribute: attr, attribute: attr, relation: relation) if appliedConstraint == nil { return accessAppliedConstraintBy(attribute: attr, attribute: .notAnAttribute, relation: relation) } return appliedConstraint } return accessAppliedConstraintBy(attribute: attr, attribute: attr, relation: relation) } public final func accessAppliedConstraintBy(attribute attr: LayoutAttribute, relation: LayoutRelation = .equal, completionHandler: @escaping (NSLayoutConstraint?) -> Void){ DispatchQueue.main.async { () -> Void in completionHandler(self.accessAppliedConstraintBy(attribute: attr, relation: relation)) } } public final func accessConstraintFromSiblingView(by attribute: LayoutAttribute, toAttribute attr2:LayoutAttribute, of otherView: View, relation: LayoutRelation) ->NSLayoutConstraint? { let c = View.prepareConstraint(self, attribute:attribute, secondView:otherView, attribute:attr2, relation:relation) let appliedConstraint = lowestCommonAncestor(of: otherView)?.constraints.containsApplied(constraint: c) return appliedConstraint } public final func accessAppliedConstraintBy(attribute attr1: LayoutAttribute, attribute attr2: LayoutAttribute, relation: LayoutRelation = .equal)->NSLayoutConstraint? { // For Aspect Ratio if ( attr1 == .width && attr2 == .height || attr1 == .height && attr2 == .width){ let c = View.prepareConstraint(self, attribute:attr1, secondView:self, attribute:attr2, relation:relation) let appliedConstraint = constraints.containsApplied(constraint: c) return appliedConstraint } // For height & width else if attr2 == .notAnAttribute && (attr1 == .width || attr1 == .height){ let c = View.prepareConstraint(self, attribute:attr1, attribute:attr2, relation:relation) let appliedConstraint = constraints.containsApplied(constraint: c) return appliedConstraint } else { let c = prepareConstraintToSuperview(attribute: attr1, attribute: attr2, relation: relation) let appliedConstraint = superview?.constraints.containsApplied(constraint: c) return appliedConstraint } } } /// MARK: TO UPDATE/MODIFY APPLIED CONSTRAINTS extension View { /// This method is used to replace already applied constraint by new constraint. public final func replacedConastrainInView(appliedConstraint ac: NSLayoutConstraint, replaceBy constraint: NSLayoutConstraint) { // assert( constraint != nil, "modified constraint must not be nil") self ~ (ac, constraint ) } /// This method is used to change the priority of constraint. public final func changedConstraint(_ priority: LayoutPriority, byAttribute attr: LayoutAttribute) { self ~ (attr, priority ) } #if os(iOS) || os(tvOS) /// This method is used to Update Modified Applied Constraints public final func updateModifyConstraints(){ layoutIfNeeded() setNeedsLayout() } public final func updateModifyConstraintsWithAnimation(_ completion:((Bool) -> Void)?) { #if swift(>=4.2) let duration = TimeInterval(UINavigationController.hideShowBarDuration) #else let duration = TimeInterval(UINavigationControllerHideShowBarDuration) #endif let referenceView = (superview != nil) ? superview! : self UIView.animate(withDuration: duration, animations: { () -> Void in referenceView.updateModifyConstraints() }, completion: completion) } public final func updateAppliedConstraintConstantValueForIpadBy(attribute a: LayoutAttribute) { if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ) { updateAppliedConstraintConstantValueBy(a, withConstantRatio: NSLayoutConstraint.Defualt.iPadRatio ) } } public final func updateAppliedConstraintConstantValueForIphoneBy(attribute a: LayoutAttribute) { if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone ) { updateAppliedConstraintConstantValueBy(a, withConstantRatio: 1.0 / NSLayoutConstraint.Defualt.iPadRatio ) } } #endif public final func updateAppliedConstraintConstantValueBy(_ attribute: LayoutAttribute, withConstantRatio ratio: CGFloat){ accessAppliedConstraintBy(attribute: attribute)?.constant *= ratio } } extension View { internal class final func prepareConstraint(_ firstView: View!, attribute attr1: LayoutAttribute, secondView: View?=nil, attribute attr2: LayoutAttribute = .notAnAttribute, relation: LayoutRelation = .equal, multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint{ assert(!multiplier.isInfinite, "Multiplier/Ratio of view must not be INFINITY.") assert(!multiplier.isNaN, "Multiplier/Ratio of view must not be NaN.") assert(!constant.isInfinite, "constant of view must not be INFINITY.") assert(!constant.isNaN, "constant of view must not be NaN.") return NSLayoutConstraint(item: firstView, attribute: attr1, relatedBy: relation, toItem: secondView, attribute: attr2, multiplier: multiplier, constant: constant) } internal func lowestCommonAncestor(of otherItem: View?) -> View? { guard let view = otherItem else { return self } var currentView: View? = self while currentView != nil && !view.isDescendant(of: currentView!) { currentView = currentView!.superview } return currentView } }
mit
bfbad08cacc6bc8458a1131a62f5bea6
42.679878
282
0.686676
4.991986
false
false
false
false
saagarjha/iina
iina/PrefPluginPermissionListView.swift
1
1631
// // PrefPluginPermissionListView.swift // iina // // Created by Collider LI on 14/3/2020. // Copyright © 2020 lhc. All rights reserved. // import Cocoa class PrefPluginPermissionListView: NSStackView { override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.orientation = .vertical } required init?(coder: NSCoder) { super.init(coder: coder) } func setPlugin(_ plugin: JavascriptPlugin, onlyShowAddedFrom previousPlugin: JavascriptPlugin? = nil) { views.forEach { removeView($0) } let permissions: Set<JavascriptPlugin.Permission> if let previous = previousPlugin { permissions = plugin.permissions.subtracting(previous.permissions) } else { permissions = plugin.permissions } let sorted = permissions.sorted { (a, b) in let da = a.isDangerous, db = b.isDangerous if da == db { return a.rawValue < b.rawValue } return da } for permission in sorted { func localize(_ key: String) -> String { return NSLocalizedString("permissions.\(permission.rawValue).\(key)", comment: "") } var desc = localize("desc") if case .networkRequest = permission { if plugin.domainList.contains("*") { desc += "\n- \(localize("any_site"))" } else { desc += "\n- " desc += plugin.domainList.joined(separator: "\n- ") } } let vc = PrefPluginPermissionView(name: localize("name"), desc: desc, isDangerous: permission.isDangerous) addView(vc.view, in: .top) Utility.quickConstraints(["H:|-0-[v]-0-|"], ["v": vc.view]) } } }
gpl-3.0
24ca4982495a75865d5a4f41ffce1588
28.636364
112
0.630675
4.004914
false
false
false
false
nessBautista/iOSBackup
iOSNotebook/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift
12
1705
// // KVORepresentable+CoreGraphics.swift // RxCocoa // // Created by Krunoslav Zaher on 11/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) import RxSwift import CoreGraphics import class Foundation.NSValue #if arch(x86_64) || arch(arm64) let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}" let CGSizeType = "{CGSize=dd}" let CGPointType = "{CGPoint=dd}" #elseif arch(i386) || arch(arm) let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}" let CGSizeType = "{CGSize=ff}" let CGPointType = "{CGPoint=ff}" #endif extension CGRect : KVORepresentable { public typealias KVOType = NSValue /// Constructs self from `NSValue`. public init?(KVOValue: KVOType) { if strcmp(KVOValue.objCType, CGRectType) != 0 { return nil } var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) KVOValue.getValue(&typedValue) self = typedValue } } extension CGPoint : KVORepresentable { public typealias KVOType = NSValue /// Constructs self from `NSValue`. public init?(KVOValue: KVOType) { if strcmp(KVOValue.objCType, CGPointType) != 0 { return nil } var typedValue = CGPoint(x: 0, y: 0) KVOValue.getValue(&typedValue) self = typedValue } } extension CGSize : KVORepresentable { public typealias KVOType = NSValue /// Constructs self from `NSValue`. public init?(KVOValue: KVOType) { if strcmp(KVOValue.objCType, CGSizeType) != 0 { return nil } var typedValue = CGSize(width: 0, height: 0) KVOValue.getValue(&typedValue) self = typedValue } } #endif
cc0-1.0
e2c4a3aa8f513974370661d68c63827e
24.058824
64
0.627934
3.855204
false
false
false
false
arvedviehweger/swift
test/IDE/newtype.swift
1
8504
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %build-clang-importer-objc-overlays // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=Newtype -skip-unavailable > %t.printed.A.txt // RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // RUN: %target-typecheck-verify-swift -sdk %clang-importer-sdk -I %S/Inputs/custom-modules -I %t // REQUIRES: objc_interop // PRINT-LABEL: struct ErrorDomain : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable, _ObjectiveCBridgeable { // PRINT-NEXT: init(_ rawValue: String) // PRINT-NEXT: init(rawValue: String) // PRINT-NEXT: var _rawValue: NSString // PRINT-NEXT: var rawValue: String { get } // PRINT-NEXT: typealias RawValue = String // PRINT-NEXT: typealias _ObjectiveCType = NSString // PRINT-NEXT: } // PRINT-NEXT: extension ErrorDomain { // PRINT-NEXT: func process() // PRINT-NEXT: static let one: ErrorDomain // PRINT-NEXT: static let errTwo: ErrorDomain // PRINT-NEXT: static let three: ErrorDomain // PRINT-NEXT: static let fourErrorDomain: ErrorDomain // PRINT-NEXT: static let stillAMember: ErrorDomain // PRINT-NEXT: } // PRINT-NEXT: struct Food { // PRINT-NEXT: init() // PRINT-NEXT: } // PRINT-NEXT: extension Food { // PRINT-NEXT: static let err: ErrorDomain // PRINT-NEXT: } // PRINT-NEXT: struct ClosedEnum : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable, _ObjectiveCBridgeable { // PRINT-NEXT: init(rawValue: String) // PRINT-NEXT: var _rawValue: NSString // PRINT-NEXT: var rawValue: String { get } // PRINT-NEXT: typealias RawValue = String // PRINT-NEXT: typealias _ObjectiveCType = NSString // PRINT-NEXT: } // PRINT-NEXT: extension ClosedEnum { // PRINT-NEXT: static let firstClosedEntryEnum: ClosedEnum // PRINT-NEXT: static let secondEntry: ClosedEnum // PRINT-NEXT: static let thirdEntry: ClosedEnum // PRINT-NEXT: } // PRINT-NEXT: struct IUONewtype : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable, _ObjectiveCBridgeable { // PRINT-NEXT: init(_ rawValue: String) // PRINT-NEXT: init(rawValue: String) // PRINT-NEXT: var _rawValue: NSString // PRINT-NEXT: var rawValue: String { get } // PRINT-NEXT: typealias RawValue = String // PRINT-NEXT: typealias _ObjectiveCType = NSString // PRINT-NEXT: } // PRINT-NEXT: struct MyFloat : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable { // PRINT-NEXT: init(_ rawValue: Float) // PRINT-NEXT: init(rawValue: Float) // PRINT-NEXT: let rawValue: Float // PRINT-NEXT: typealias RawValue = Float // PRINT-NEXT: } // PRINT-NEXT: extension MyFloat { // PRINT-NEXT: static let globalFloat: MyFloat{{$}} // PRINT-NEXT: static let PI: MyFloat{{$}} // PRINT-NEXT: static let version: MyFloat{{$}} // PRINT-NEXT: } // // PRINT-LABEL: struct MyInt : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable { // PRINT-NEXT: init(_ rawValue: Int32) // PRINT-NEXT: init(rawValue: Int32) // PRINT-NEXT: let rawValue: Int32 // PRINT-NEXT: typealias RawValue = Int32 // PRINT-NEXT: } // PRINT-NEXT: extension MyInt { // PRINT-NEXT: static let zero: MyInt{{$}} // PRINT-NEXT: static let one: MyInt{{$}} // PRINT-NEXT: } // PRINT-NEXT: let kRawInt: Int32 // PRINT-NEXT: func takesMyInt(_: MyInt) // // PRINT-LABEL: extension NSURLResourceKey { // PRINT-NEXT: static let isRegularFileKey: NSURLResourceKey // PRINT-NEXT: static let isDirectoryKey: NSURLResourceKey // PRINT-NEXT: static let localizedNameKey: NSURLResourceKey // PRINT-NEXT: } // PRINT-NEXT: extension NSNotification.Name { // PRINT-NEXT: static let Foo: NSNotification.Name // PRINT-NEXT: static let bar: NSNotification.Name // PRINT-NEXT: static let NSWibble: NSNotification.Name // PRINT-NEXT: } // PRINT-NEXT: let kNotification: String // PRINT-NEXT: let Notification: String // PRINT-NEXT: let swiftNamedNotification: String // // PRINT-LABEL: struct CFNewType : RawRepresentable, _SwiftNewtypeWrapper { // PRINT-NEXT: init(_ rawValue: CFString) // PRINT-NEXT: init(rawValue: CFString) // PRINT-NEXT: let rawValue: CFString // PRINT-NEXT: typealias RawValue = CFString // PRINT-NEXT: } // PRINT-NEXT: extension CFNewType { // PRINT-NEXT: static let MyCFNewTypeValue: CFNewType // PRINT-NEXT: static let MyCFNewTypeValueUnauditedButConst: CFNewType // PRINT-NEXT: static var MyCFNewTypeValueUnaudited: Unmanaged<CFString> // PRINT-NEXT: } // PRINT-NEXT: func FooAudited() -> CFNewType // PRINT-NEXT: func FooUnaudited() -> Unmanaged<CFString> // // PRINT-NEXT: struct MyABINewType : RawRepresentable, _SwiftNewtypeWrapper { // PRINT-NEXT: init(_ rawValue: CFString) // PRINT-NEXT: init(rawValue: CFString) // PRINT-NEXT: let rawValue: CFString // PRINT-NEXT: typealias RawValue = CFString // PRINT-NEXT: } // PRINT-NEXT: typealias MyABIOldType = CFString // PRINT-NEXT: extension MyABINewType { // PRINT-NEXT: static let global: MyABINewType! // PRINT-NEXT: } // PRINT-NEXT: let kMyABIOldTypeGlobal: MyABIOldType! // PRINT-NEXT: func getMyABINewType() -> MyABINewType! // PRINT-NEXT: func getMyABIOldType() -> MyABIOldType! // PRINT-NEXT: func takeMyABINewType(_: MyABINewType!) // PRINT-NEXT: func takeMyABIOldType(_: MyABIOldType!) // PRINT-NEXT: func takeMyABINewTypeNonNull(_: MyABINewType) // PRINT-NEXT: func takeMyABIOldTypeNonNull(_: MyABIOldType) // PRINT-NEXT: struct MyABINewTypeNS : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable, _ObjectiveCBridgeable { // PRINT-NEXT: init(_ rawValue: String) // PRINT-NEXT: init(rawValue: String) // PRINT-NEXT: var _rawValue: NSString // PRINT-NEXT: var rawValue: String { get } // PRINT-NEXT: typealias RawValue = String // PRINT-NEXT: typealias _ObjectiveCType = NSString // PRINT-NEXT: } // PRINT-NEXT: typealias MyABIOldTypeNS = NSString // PRINT-NEXT: func getMyABINewTypeNS() -> MyABINewTypeNS! // PRINT-NEXT: func getMyABIOldTypeNS() -> String! // PRINT-NEXT: func takeMyABINewTypeNonNullNS(_: MyABINewTypeNS) // PRINT-NEXT: func takeMyABIOldTypeNonNullNS(_: String) // // PRINT-NEXT: struct NSSomeContext { // PRINT-NEXT: var i: Int32 // PRINT-NEXT: init() // PRINT-NEXT: init(i: Int32) // PRINT-NEXT: } // PRINT-NEXT: extension NSSomeContext { // PRINT-NEXT: struct Name : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, Comparable, _ObjectiveCBridgeable { // PRINT-NEXT: init(_ rawValue: String) // PRINT-NEXT: init(rawValue: String) // PRINT-NEXT: var _rawValue: NSString // PRINT-NEXT: var rawValue: String { get } // PRINT-NEXT: typealias RawValue = String // PRINT-NEXT: typealias _ObjectiveCType = NSString // PRINT-NEXT: } // PRINT-NEXT: } // PRINT-NEXT: extension NSSomeContext.Name { // PRINT-NEXT: static let myContextName: NSSomeContext.Name // PRINT-NEXT: } import Newtype func tests() { let errOne = ErrorDomain.one errOne.process() let fooErr = Food.err fooErr.process() Food().process() // expected-error{{value of type 'Food' has no member 'process'}} let thirdEnum = ClosedEnum.thirdEntry thirdEnum.process() // expected-error@-1{{value of type 'ClosedEnum' has no member 'process'}} let _ = ErrorDomain(rawValue: thirdEnum.rawValue) let _ = ClosedEnum(rawValue: errOne.rawValue) let _ = NSNotification.Name.Foo let _ = NSNotification.Name.bar let _ : CFNewType = CFNewType.MyCFNewTypeValue let _ : CFNewType = CFNewType.MyCFNewTypeValueUnauditedButConst let _ : CFNewType = CFNewType.MyCFNewTypeValueUnaudited // expected-error@-1{{cannot convert value of type 'Unmanaged<CFString>!' to specified type 'CFNewType'}} } func acceptSwiftNewtypeWrapper<T : _SwiftNewtypeWrapper>(_ t: T) { } func acceptEquatable<T : Equatable>(_ t: T) { } func acceptHashable<T : Hashable>(_ t: T) { } func acceptComparable<T : Hashable>(_ t: T) { } func acceptObjectiveCBridgeable<T : _ObjectiveCBridgeable>(_ t: T) { } func testConformances(ed: ErrorDomain) { acceptSwiftNewtypeWrapper(ed) acceptEquatable(ed) acceptHashable(ed) acceptComparable(ed) acceptObjectiveCBridgeable(ed) } func testFixit() { let _ = NSMyContextName // expected-error@-1{{'NSMyContextName' has been renamed to 'NSSomeContext.Name.myContextName'}} {{10-25=NSSomeContext.Name.myContextName}} }
apache-2.0
7ce547190b57e42d3f2a8811a7f652e9
42.387755
200
0.706726
3.665517
false
false
false
false
edgarmoises/FoodTruck
FoodTruckiOS/FoodTruck/FoodTruck.swift
1
2069
// // FoodTruck.swift // FoodTruck // // Created by Edgar Pérez on 1/1/17. // Copyright © 2017 Edgar Pérez. All rights reserved. // import Foundation import CoreLocation import MapKit class FoodTruck: NSObject, MKAnnotation { var id: String = "" var name: String = "" var foodType: String = "" var avgCost: Double = 0.0 var geomType: String = "Point" var lat: Double = 0.0 var long: Double = 0.0 @objc var title: String? @objc var subtitle: String? @objc var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: self.lat, longitude: self.long) } static func parseFoodTruckJSONData(data: Data) -> [FoodTruck] { var foodtrucks = [FoodTruck]() do { let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) // Parse JSON Data if let trucks = jsonResult as? [Dictionary<String, AnyObject>] { for truck in trucks { let newTruck = FoodTruck() newTruck.id = truck["_id"] as! String newTruck.name = truck["name"] as! String newTruck.foodType = truck["foodtype"] as! String newTruck.avgCost = truck["avgcost"] as! Double let geometry = truck["geometry"] as! Dictionary<String, AnyObject> newTruck.geomType = geometry["type"] as! String let coords = geometry["coordinates"] as! Dictionary<String, AnyObject> newTruck.lat = coords["lat"] as! Double newTruck.long = coords["long"] as! Double newTruck.title = newTruck.name newTruck.subtitle = newTruck.foodType foodtrucks.append(newTruck) } } } catch let error { print("Error deserializing JSON \(error)") } return foodtrucks } }
gpl-3.0
b485d06294a1689cb5afd849ebf08e58
33.433333
102
0.546467
4.591111
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/Providers/StemItemViewProvider.swift
1
1170
// // StemItemViewProvider.swift // StemCode // // Created by David Evans on 06/09/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import Foundation import StemProjectKit protocol StemItemViewable { associatedtype ViewType: UIView func createView(delegate: StemItemViewDelegate, openFile: StemFile) -> ViewType } extension StemFile { typealias ViewType = StemFileView func createView(delegate: StemItemViewDelegate, openFile: StemFile) -> StemFileView { let fileView = Bundle.main.loadNibNamed("StemFile", owner: nil, options: nil)?.first as! StemFileView fileView.delegate = delegate fileView.setItem(self, openFile: openFile) fileView.translatesAutoresizingMaskIntoConstraints = false return fileView } } extension StemGroup { typealias ViewType = StemGroupView func createView(delegate: StemItemViewDelegate, openFile: StemFile) -> StemGroupView { let groupView = Bundle.main.loadNibNamed("StemGroup", owner: nil, options: nil)?.first as! StemGroupView groupView.delegate = delegate groupView.setItem(self, openFile: openFile) groupView.translatesAutoresizingMaskIntoConstraints = false return groupView } }
mit
31313c8309c5681a0f227381d0100ddc
27.512195
106
0.779299
4.14539
false
false
false
false
xedin/swift
test/stdlib/Accelerate.swift
2
20669
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var AccelerateTests = TestSuite("Accelerate") if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 4.0, *) { AccelerateTests.test("BNNS/ImageStackDescriptor") { var succeed = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, row_stride: 0, image_stride: 0, data_type: .int8) expectEqual(succeed.data_scale, 1) expectEqual(succeed.data_bias, 0) succeed = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, row_stride: 0, image_stride: 0, data_type: .int16, data_scale: 0.5, data_bias: 0.5) expectEqual(succeed.data_scale, 0.5) expectEqual(succeed.data_bias, 0.5) expectCrashLater() // indexed8 is not allowed as an imageStack data type. let _ = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0, row_stride: 0, image_stride: 0, data_type: .indexed8) } AccelerateTests.test("BNNS/VectorDescriptor") { var succeed = BNNSVectorDescriptor(size: 0, data_type: .int8) expectEqual(succeed.data_scale, 1) expectEqual(succeed.data_bias, 0) succeed = BNNSVectorDescriptor(size: 0, data_type: .int8, data_scale: 0.5, data_bias: 0.5) expectEqual(succeed.data_scale, 0.5) expectEqual(succeed.data_bias, 0.5) expectCrashLater() // indexed8 is not allowed as a vector data type. let _ = BNNSVectorDescriptor(size: 0, data_type: .indexed8) } AccelerateTests.test("BNNS/LayerData") { // The zero layer should have data == nil. expectEqual(BNNSLayerData.zero.data, nil) var succeed = BNNSLayerData(data: nil, data_type: .int8) expectEqual(succeed.data_scale, 1) expectEqual(succeed.data_bias, 0) succeed = BNNSLayerData(data: nil, data_type: .int8, data_scale: 0.5, data_bias: 0.5, data_table: nil) expectEqual(succeed.data_scale, 0.5) expectEqual(succeed.data_bias, 0.5) var table: [Float] = [1.0] succeed = BNNSLayerData.indexed8(data: nil, data_table: &table) expectCrashLater() // indexed8 requires a non-nil data table. let _ = BNNSLayerData(data: nil, data_type: .indexed8) } AccelerateTests.test("BNNS/Activation") { expectEqual(BNNSActivation.identity.function, .identity) let id = BNNSActivation(function: .identity) expectTrue(id.alpha.isNaN) expectTrue(id.beta.isNaN) } } //===----------------------------------------------------------------------===// // // vDSP Discrete Cosine Transform // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { AccelerateTests.test("vDSP/DiscreteCosineTransform") { let n = 1024 let source = (0 ..< n).map{ i in return sin(Float(i) * 0.05) + sin(Float(i) * 0.025) } for transformType in vDSP.DCTTransformType.allCases { let dct = vDSP.DCT(count: n, transformType: transformType) var destination = [Float](repeating: 0, count: n) dct?.transform(source, result: &destination) let returnedResult = dct!.transform(source) // Legacy API let legacySetup = vDSP_DCT_CreateSetup(nil, vDSP_Length(n), transformType.dctType)! var legacyDestination = [Float](repeating: -1, count: n) vDSP_DCT_Execute(legacySetup, source, &legacyDestination) expectTrue(destination.elementsEqual(legacyDestination)) expectTrue(destination.elementsEqual(returnedResult)) } } } //===----------------------------------------------------------------------===// // // Sliding window summation // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { AccelerateTests.test("vDSP/SinglePrecisionSlidingWindowSum") { let source: [Float] = [1, 10, 12, 9, 3, 7, 2, 6] var destination = [Float](repeating: .nan, count: 6) vDSP.slidingWindowSum(source, usingWindowLength: 3, result: &destination) let returnedResult = vDSP.slidingWindowSum(source, usingWindowLength: 3) expectTrue(destination.elementsEqual(returnedResult)) expectTrue(destination.map{ Int($0) }.elementsEqual([23, 31, 24, 19, 12, 15])) } AccelerateTests.test("vDSP/DoublePrecisionSlidingWindowSum") { let source: [Double] = [1, 10, 12, 9, 3, 7, 2, 6] var destination = [Double](repeating: .nan, count: 6) vDSP.slidingWindowSum(source, usingWindowLength: 3, result: &destination) let returnedResult = vDSP.slidingWindowSum(source, usingWindowLength: 3) expectTrue(destination.elementsEqual(returnedResult)) expectTrue(destination.map{ Int($0) }.elementsEqual([23, 31, 24, 19, 12, 15])) } } //===----------------------------------------------------------------------===// // // Linear interpolation // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { let n = 1024 AccelerateTests.test("vDSP/SinglePrecisionInterpolateBetweenVectors") { var result = [Float](repeating: 0, count: n) var legacyResult = [Float](repeating: -1, count: n) let a: [Float] = (0 ..< n).map{ i in return sin(Float(i) * 0.025) } let b: [Float] = (0 ..< n).map{ i in return sin(Float(i) * 0.05) } let interpolationConstant: Float = 0.5 vDSP.linearInterpolate(a, b, using: interpolationConstant, result: &result) vDSP_vintb(a, 1, b, 1, [interpolationConstant], &legacyResult, 1, vDSP_Length(n)) let returnedResult = vDSP.linearInterpolate(a, b, using: interpolationConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/SinglePrecisionInterpolateBetweenNeighbours") { var result = [Float](repeating: 0, count: n) var legacyResult = [Float](repeating: -1, count: n) let shortSignal: [Float] = (0 ... 10).map{ i in return sin(Float(i) * 0.1 * .pi * 4) } let controlVector: [Float] = { var controlVector = [Float](repeating: 0, count: 1024) vDSP_vgen([0], [Float(shortSignal.count)], &controlVector, 1, vDSP_Length(n)) return controlVector }() vDSP.linearInterpolate(elementsOf: shortSignal, using: controlVector, result: &result) vDSP_vlint(shortSignal, controlVector, 1, &legacyResult, 1, vDSP_Length(n), vDSP_Length(shortSignal.count)) let returnedResult = vDSP.linearInterpolate(elementsOf: shortSignal, using: controlVector) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/DoublePrecisionInterpolateBetweenVectors") { var result = [Double](repeating: 0, count: n) var legacyResult = [Double](repeating: -1, count: n) let a: [Double] = (0 ..< n).map{ i in return sin(Double(i) * 0.025) } let b: [Double] = (0 ..< n).map{ i in return sin(Double(i) * 0.05) } let interpolationConstant: Double = 0.5 vDSP.linearInterpolate(a, b, using: interpolationConstant, result: &result) vDSP_vintbD(a, 1, b, 1, [interpolationConstant], &legacyResult, 1, vDSP_Length(n)) let returnedResult = vDSP.linearInterpolate(a, b, using: interpolationConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/DoublePrecisionInterpolateBetweenNeighbours") { var result = [Double](repeating: 0, count: n) var legacyResult = [Double](repeating: -1, count: n) let shortSignal: [Double] = (0 ... 10).map{ i in return sin(Double(i) * 0.1 * .pi * 4) } let controlVector: [Double] = { var controlVector = [Double](repeating: 0, count: 1024) vDSP_vgenD([0], [Double(shortSignal.count)], &controlVector, 1, vDSP_Length(n)) return controlVector }() vDSP.linearInterpolate(elementsOf: shortSignal, using: controlVector, result: &result) vDSP_vlintD(shortSignal, controlVector, 1, &legacyResult, 1, vDSP_Length(n), vDSP_Length(shortSignal.count)) let returnedResult = vDSP.linearInterpolate(elementsOf: shortSignal, using: controlVector) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } //===----------------------------------------------------------------------===// // // vDSP difference equation // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { AccelerateTests.test("vDSP/DifferenceEquationSinglePrecision") { let n = 256 let source: [Float] = (0 ..< n).map { return sin(Float($0) * 0.05).sign == .minus ? -1 : 1 } var result = [Float](repeating: 0, count: n) var legacyResult = [Float](repeating: -1, count: n) let coefficients: [Float] = [0.0, 0.1, 0.2, 0.4, 0.8] vDSP.twoPoleTwoZeroFilter(source, coefficients: (coefficients[0], coefficients[1], coefficients[2], coefficients[3], coefficients[4]), result: &result) legacyResult[0] = 0 legacyResult[1] = 0 vDSP_deq22(source, 1, coefficients, &legacyResult, 1, vDSP_Length(n-2)) let returnedResult = vDSP.twoPoleTwoZeroFilter(source, coefficients: (coefficients[0], coefficients[1], coefficients[2], coefficients[3], coefficients[4])) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/DifferenceEquationDoublePrecision") { let n = 256 let source: [Double] = (0 ..< n).map { return sin(Double($0) * 0.05).sign == .minus ? -1 : 1 } var result = [Double](repeating: 0, count: n) var legacyResult = [Double](repeating: -1, count: n) let coefficients: [Double] = [0.0, 0.1, 0.2, 0.4, 0.8] vDSP.twoPoleTwoZeroFilter(source, coefficients: (coefficients[0], coefficients[1], coefficients[2], coefficients[3], coefficients[4]), result: &result) legacyResult[0] = 0 legacyResult[1] = 0 vDSP_deq22D(source, 1, coefficients, &legacyResult, 1, vDSP_Length(n-2)) let returnedResult = vDSP.twoPoleTwoZeroFilter(source, coefficients: (coefficients[0], coefficients[1], coefficients[2], coefficients[3], coefficients[4])) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } //===----------------------------------------------------------------------===// // // vDSP downsampling // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { AccelerateTests.test("vDSP/DownsampleSinglePrecision") { let decimationFactor = 2 let filterLength: vDSP_Length = 2 let filter = [Float](repeating: 1 / Float(filterLength), count: Int(filterLength)) let originalSignal: [Float] = [10, 15, 20, 25, 50, 25, 20, 15, 10, 10, 15, 20, 25, 50, 25, 20, 15, 10] let inputLength = vDSP_Length(originalSignal.count) let n = vDSP_Length((inputLength - filterLength) / vDSP_Length(decimationFactor)) + 1 var result = [Float](repeating: 0, count: Int(n)) vDSP.downsample(originalSignal, decimationFactor: decimationFactor, filter: filter, result: &result) var legacyResult = [Float](repeating: -1, count: Int(n)) vDSP_desamp(originalSignal, decimationFactor, filter, &legacyResult, n, filterLength) let returnedResult = vDSP.downsample(originalSignal, decimationFactor: decimationFactor, filter: filter) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/DownsampleDoublePrecision") { let decimationFactor = 2 let filterLength: vDSP_Length = 2 let filter = [Double](repeating: 1 / Double(filterLength), count: Int(filterLength)) let originalSignal: [Double] = [10, 15, 20, 25, 50, 25, 20, 15, 10, 10, 15, 20, 25, 50, 25, 20, 15, 10] let inputLength = vDSP_Length(originalSignal.count) let n = vDSP_Length((inputLength - filterLength) / vDSP_Length(decimationFactor)) + 1 var result = [Double](repeating: 0, count: Int(n)) vDSP.downsample(originalSignal, decimationFactor: decimationFactor, filter: filter, result: &result) var legacyResult = [Double](repeating: -1, count: Int(n)) vDSP_desampD(originalSignal, decimationFactor, filter, &legacyResult, n, filterLength) let returnedResult = vDSP.downsample(originalSignal, decimationFactor: decimationFactor, filter: filter) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } //===----------------------------------------------------------------------===// // // vDSP polynomial evaluation. // //===----------------------------------------------------------------------===// if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) { AccelerateTests.test("vDSP/PolynomialEvaluationSinglePrecision") { let coefficients: [Float] = [2, 3, 4, 5, 6, 7, 8, 9, 10] let variables = (0 ... 100).map { return Float($0) } var result = [Float](repeating: 0, count: variables.count) vDSP.evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables, result: &result) var legacyResult = [Float](repeating: -1, count: variables.count) vDSP_vpoly(coefficients, 1, variables, 1, &legacyResult, 1, vDSP_Length(legacyResult.count), vDSP_Length(coefficients.count - 1)) let returnedResult = vDSP.evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } AccelerateTests.test("vDSP/PolynomialEvaluationDoublePrecision") { let coefficients: [Double] = [2, 3, 4, 5, 6, 7, 8, 9, 10] let variables = (0 ... 100).map { return Double($0) } var result = [Double](repeating: 0, count: variables.count) vDSP.evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables, result: &result) var legacyResult = [Double](repeating: -1, count: variables.count) vDSP_vpolyD(coefficients, 1, variables, 1, &legacyResult, 1, vDSP_Length(legacyResult.count), vDSP_Length(coefficients.count - 1)) let returnedResult = vDSP.evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } runAllTests()
apache-2.0
84ecf2f03e795e4a7663f4b47f23f350
37.561567
93
0.458706
5.272704
false
true
false
false
wolfposd/DynamicFeedback
DynamicFeedbackSheets/DynamicFeedbackSheets/View/SliderCell.swift
1
1544
// // SliderCell.swift // DynamicFeedbackSheets // // Created by Jan Hennings on 09/06/14. // Copyright (c) 2014 Jan Hennings. All rights reserved. // import UIKit class SliderCell: ModuleCell { // MARK: Properties @IBOutlet var descriptionLabel: UILabel! @IBOutlet var slider: UISlider! override var module: FeedbackSheetModule? { willSet { if let sliderModule = newValue as? SliderModule { descriptionLabel.text = sliderModule.text slider.minimumValue = CFloat(sliderModule.minValue) slider.maximumValue = CFloat(sliderModule.maxValue) slider.value = CFloat(sliderModule.minValue) } } } // FIXME: Testing, current Bug in Xcode (Ambiguous use of module) func setModule(module: FeedbackSheetModule) { self.module = module } // MARK: Actions override func reloadWithResponseData(responseData: AnyObject) { slider.value = CFloat(responseData as Float) } // MARK: IBActions @IBAction func moveSlider(sender: UISlider) { if let sliderModule = module as? SliderModule { let steps = roundf((sender.value) / CFloat(sliderModule.stepValue)) let newValue = steps * CFloat(sliderModule.stepValue) slider.value = newValue sliderModule.responseData = slider.value delegate?.moduleCell(self, didGetResponse: sliderModule.responseData, forID: sliderModule.ID) } } }
gpl-2.0
17d0186ddc777082eced748bc1a35f1c
28.132075
105
0.632772
4.608955
false
false
false
false
QuarkX/Quark
Tests/QuarkTests/Venice/CoroutineTests.swift
1
6716
import XCTest import Quark class CoroutineTests : XCTestCase { var sum: Int = 0 func worker(count: Int, n: Int) { for _ in 0 ..< count { sum += n yield } } func testCo() { coroutine(self.worker(count: 3, n: 7)) co(self.worker(count: 1, n: 11)) co(self.worker(count: 2, n: 5)) nap(for: 100.milliseconds) XCTAssert(sum == 42) } func testStackdeallocationWorks() { for _ in 0 ..< 20 { after(50.milliseconds) {} } nap(for: 100.milliseconds) } func testWakeUp() { let deadline = 100.milliseconds.fromNow() wake(at: deadline) let diff = now() - deadline XCTAssert(diff > -200 && diff < 200) } func testNap() { let channel = Channel<Double>() func delay(duration: Double) { nap(for: duration) channel.send(duration) } co(delay(duration: 30.milliseconds)) co(delay(duration: 40.milliseconds)) co(delay(duration: 10.milliseconds)) co(delay(duration: 20.milliseconds)) XCTAssert(channel.receive() == 10.milliseconds) XCTAssert(channel.receive() == 20.milliseconds) XCTAssert(channel.receive() == 30.milliseconds) XCTAssert(channel.receive() == 40.milliseconds) } func testFork() { _ = Quark.fork() } func testLogicalCPUCount() { XCTAssert(logicalCPUCount > 0) } func testDump() { Quark.dump() } func testEvery() { let channel = Channel<Void>() var counter = 0 let period = 50.millisecond every(period) { done in counter += 1 if counter == 3 { channel.send() done() } } let then = now() channel.receive() let diff = now() - then let threshold = 50.millisecond XCTAssert(diff > 3 * period - threshold && diff < 3 * period + threshold) } func testPollFileDescriptor() throws { var event: PollEvent var size: Int let fds = UnsafeMutablePointer<Int32>.allocate(capacity: 2) #if os(Linux) let result = socketpair(AF_UNIX, Int32(SOCK_STREAM.rawValue), 0, fds) #else let result = socketpair(AF_UNIX, SOCK_STREAM, 0, fds) #endif XCTAssert(result == 0) event = try poll(fds[0], events: .write) XCTAssert(event == .write) event = try poll(fds[0], events: .write, deadline: 100.milliseconds.fromNow()) XCTAssert(event == .write) do { _ = try poll(fds[0], events: .read, deadline: 100.milliseconds.fromNow()) XCTFail() } catch PollError.timeout { // yeah (: } catch { XCTFail() } size = send(fds[1], "A", 1, 0) XCTAssert(size == 1) event = try poll(fds[0], events: .write) XCTAssert(event == .write) event = try poll(fds[0], events: [.read, .write]) XCTAssert(event == [.read, .write]) var c: Int8 = 0 size = recv(fds[0], &c, 1, 0) XCTAssert(size == 1) XCTAssert(c == 65) } func testSyncPerformanceVenice() { self.measure { let numberOfSyncs = 10000 let channel = Channel<Void>() for _ in 0 ..< numberOfSyncs { co { channel.send() } channel.receive() } } } func testManyCoroutines() { self.measure { let numberOfCoroutines = 10000 for _ in 0 ..< numberOfCoroutines { co {} } } } func testThousandWhispers() { self.measure { func whisper(_ left: SendingChannel<Int>, _ right: ReceivingChannel<Int>) { left.send(1 + right.receive()!) } let numberOfWhispers = 10000 let leftmost = Channel<Int>() var right = leftmost var left = leftmost for _ in 0 ..< numberOfWhispers { right = Channel<Int>() co(whisper(left.sendingChannel, right.receivingChannel)) left = right } co(right.send(1)) XCTAssert(leftmost.receive() == numberOfWhispers + 1) } } func testManyContextSwitches() { self.measure { let numberOfContextSwitches = 10000 let count = numberOfContextSwitches / 2 co { for _ in 0 ..< count { yield } } for _ in 0 ..< count { yield } } } func testSendReceiveManyMessages() { self.measure { let numberOfMessages = 10000 let channel = Channel<Int>(bufferSize: numberOfMessages) for _ in 0 ..< numberOfMessages { channel.send(0) } for _ in 0 ..< numberOfMessages { channel.receive() } } } func testManyRoundTrips() { self.measure { let numberOfRoundTrips = 10000 let input = Channel<Int>() let output = Channel<Int>() let initiaValue = 1969 var value = initiaValue co { while true { let value = output.receive()! input.send(value) } } for _ in 0 ..< numberOfRoundTrips { output.send(value) value = input.receive()! } XCTAssert(value == initiaValue) } } } extension CoroutineTests { static var allTests : [(String, (CoroutineTests) -> () throws -> Void)] { return [ ("testCo", testCo), ("testStackdeallocationWorks", testStackdeallocationWorks), ("testWakeUp", testWakeUp), ("testNap", testNap), ("testFork", testFork), ("testLogicalCPUCount", testLogicalCPUCount), ("testDump", testDump), ("testEvery", testEvery), ("testPollFileDescriptor", testPollFileDescriptor), ("testSyncPerformanceVenice", testSyncPerformanceVenice), ("testManyCoroutines", testManyCoroutines), ("testThousandWhispers", testThousandWhispers), ("testManyContextSwitches", testManyContextSwitches), ("testSendReceiveManyMessages", testSendReceiveManyMessages), ("testManyRoundTrips", testManyRoundTrips), ] } }
mit
f6ba7770bb3190ce6e8b836a5e33172a
26.983333
87
0.505211
4.543978
false
true
false
false
jaften/calendar-Swift-2.0-
CVCalendar/CVCalendarContentViewController.swift
2
7346
// // CVCalendarContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public typealias Identifier = String public class CVCalendarContentViewController: UIViewController { // MARK: - Constants public let Previous = "Previous" public let Presented = "Presented" public let Following = "Following" // MARK: - Public Properties public let calendarView: CalendarView public let scrollView: UIScrollView public var presentedMonthView: MonthView public var bounds: CGRect { return scrollView.bounds } public var currentPage = 1 public var pageChanged: Bool { get { return currentPage == 1 ? false : true } } public var pageLoadingEnabled = true public var presentationEnabled = true public var lastContentOffset: CGFloat = 0 public var direction: CVScrollDirection = .None public init(calendarView: CalendarView, frame: CGRect) { self.calendarView = calendarView scrollView = UIScrollView(frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: NSDate()) presentedMonthView.updateAppearance(frame) super.init(nibName: nil, bundle: nil) scrollView.contentSize = CGSizeMake(frame.width * 3, frame.height) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.layer.masksToBounds = true scrollView.pagingEnabled = true scrollView.delegate = self } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI Refresh extension CVCalendarContentViewController { public func updateFrames(frame: CGRect) { if frame != CGRectZero { scrollView.frame = frame scrollView.removeAllSubviews() scrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height) } calendarView.hidden = false } } // MARK: - Abstract methods /// UIScrollViewDelegate extension CVCalendarContentViewController: UIScrollViewDelegate { } /// Convenience API. extension CVCalendarContentViewController { public func performedDayViewSelection(dayView: DayView) { } public func togglePresentedDate(date: NSDate) { } public func presentNextView(view: UIView?) { } public func presentPreviousView(view: UIView?) { } public func updateDayViews(hidden: Bool) { } } // MARK: - Contsant conversion extension CVCalendarContentViewController { public func indexOfIdentifier(identifier: Identifier) -> Int { let index: Int switch identifier { case Previous: index = 0 case Presented: index = 1 case Following: index = 2 default: index = -1 } return index } } // MARK: - Date management extension CVCalendarContentViewController { public func dateBeforeDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month -= 1 let dateBefore = calendar.dateFromComponents(components)! return dateBefore } public func dateAfterDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month += 1 let dateAfter = calendar.dateFromComponents(components)! return dateAfter } public func matchedMonths(lhs: Date, _ rhs: Date) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month } public func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week) } public func matchedDays(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day) } } // MARK: - AutoLayout Management extension CVCalendarContentViewController { private func layoutViews(views: [UIView], toHeight height: CGFloat) { scrollView.frame.size.height = height var superStack = [UIView]() var currentView: UIView = calendarView while let currentSuperview = currentView.superview where !(currentSuperview is UIWindow) { superStack += [currentSuperview] currentView = currentSuperview } for view in views + superStack { view.layoutIfNeeded() } } public func updateHeight(height: CGFloat, animated: Bool) { if calendarView.shouldAnimateResizing { var viewsToLayout = [UIView]() if let calendarSuperview = calendarView.superview { for constraintIn in calendarSuperview.constraints { if let constraint = constraintIn as? NSLayoutConstraint { if let firstItem = constraint.firstItem as? UIView, let _/*secondItem*/ = constraint.secondItem as? CalendarView { viewsToLayout.append(firstItem) } } } } for constraintIn in calendarView.constraints { if let constraint = constraintIn as? NSLayoutConstraint where constraint.firstAttribute == NSLayoutAttribute.Height { constraint.constant = height if animated { UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { self.layoutViews(viewsToLayout, toHeight: height) }) { _ in self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize self.presentedMonthView.updateInteractiveView() } } else { layoutViews(viewsToLayout, toHeight: height) presentedMonthView.updateInteractiveView() presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } break } } } } public func updateLayoutIfNeeded() { if presentedMonthView.potentialSize.height != scrollView.bounds.height { updateHeight(presentedMonthView.potentialSize.height, animated: true) } else if presentedMonthView.frame.size != scrollView.frame.size { presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } } } extension UIView { public func removeAllSubviews() { for subview in subviews { if let view = subview as? UIView { view.removeFromSuperview() } } } }
mit
9fd41bb0cdab499f563fb608ce5afc25
32.094595
138
0.606452
5.766091
false
false
false
false
roambotics/swift
test/SILGen/properties_swift4.swift
2
7764
// RUN: %target-swift-emit-silgen -swift-version 4 -module-name properties -Xllvm -sil-full-demangle -parse-as-library %s | %FileCheck %s var zero: Int = 0 protocol ForceAccessors { var a: Int { get set } } struct DidSetWillSetTests: ForceAccessors { static var defaultValue: DidSetWillSetTests { return DidSetWillSetTests(a: 0) } var a: Int { // CHECK-LABEL: sil private [ossa] @$s10properties010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vw willSet(newA) { // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): a = zero // reassign, but don't infinite loop. // CHECK: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s10properties4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] var unrelatedValue = DidSetWillSetTests.defaultValue // CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "unrelatedValue" // CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin DidSetWillSetTests.Type // CHECK-NEXT: // function_ref static properties.DidSetWillSetTests.defaultValue.getter : properties.DidSetWillSetTests // CHECK-NEXT: [[DEFAULTVALUE_FN:%.*]] = function_ref @$s10properties{{[_0-9a-zA-Z]*}}vgZ : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests // CHECK-NEXT: [[DEFAULTRESULT:%.*]] = apply [[DEFAULTVALUE_FN]]([[METATYPE]]) : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests // CHECK-NEXT: store [[DEFAULTRESULT]] to [trivial] [[BOXADDR]] : $*DidSetWillSetTests // Access directly even when calling on another instance in order to maintain < Swift 5 behaviour. unrelatedValue.a = zero // CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s10properties4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests // CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests } // CHECK-LABEL: sil private [ossa] @$s10properties010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vW didSet { (self).a = zero // reassign, but don't infinite loop. // CHECK: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s10properties4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] var unrelatedValue = DidSetWillSetTests.defaultValue // CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "unrelatedValue" // CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin DidSetWillSetTests.Type // CHECK-NEXT: // function_ref static properties.DidSetWillSetTests.defaultValue.getter : properties.DidSetWillSetTests // CHECK-NEXT: [[DEFAULTVALUE_FN:%.*]] = function_ref @$s10properties{{[_0-9a-zA-Z]*}}vgZ : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests // CHECK-NEXT: [[DEFAULTRESULT:%.*]] = apply [[DEFAULTVALUE_FN]]([[METATYPE]]) : $@convention(method) (@thin DidSetWillSetTests.Type) -> DidSetWillSetTests // CHECK-NEXT: store [[DEFAULTRESULT]] to [trivial] [[BOXADDR]] : $*DidSetWillSetTests // Access directly even when calling on another instance in order to maintain < Swift 5 behaviour. unrelatedValue.a = zero // CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s10properties4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests // CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests var other = self // CHECK: [[BOX:%.*]] = alloc_box ${ var DidSetWillSetTests }, var, name "other" // CHECK-NEXT: [[BOXADDR:%.*]] = project_box [[BOX]] : ${ var DidSetWillSetTests }, 0 // CHECK-NEXT: [[READ_SELF:%.*]] = begin_access [read] [unknown] %0 : $*DidSetWillSetTests // CHECK-NEXT: copy_addr [[READ_SELF]] to [init] [[BOXADDR]] : $*DidSetWillSetTests // CHECK-NEXT: end_access [[READ_SELF]] : $*DidSetWillSetTests other.a = zero // CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s10properties4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOXADDR]] : $*DidSetWillSetTests // CHECK-NEXT: [[ELEMADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[ELEMADDR]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*DidSetWillSetTests } } }
apache-2.0
f611a9da67a32d538e69bef5e0d535bf
60.619048
172
0.616177
4.004126
false
true
false
false
GraphKit/swift
Sources/Relationship.swift
5
6554
/* * Copyright (C) 2015 - 2019 and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Authors: * Daniel Dahan <[email protected]>, * Orkhan Alikhanov <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreData @objc(Relationship) public class Relationship: Node { /// A reference to the managedNode. internal var managedNode: ManagedRelationship { return node as! ManagedRelationship } public override var description: String { return "[nodeClass: \(nodeClass), id: \(id), type: \(type), tags: \(tags), groups: \(groups), properties: \(properties), subject: \(String(describing: subject)), object: \(String(describing: object)), createdDate: \(createdDate)]" } /// A reference to the nodeClass. public var nodeClass: NodeClass { return .relationship } /// A reference to the subject Entity. public var subject: Entity? { get { return managedNode.performAndWait { relationship in relationship.subject.map { Entity(managedNode: $0) } } } set(entity) { managedNode.managedObjectContext?.performAndWait { [unowned self] in if let e = entity?.managedNode { self.managedNode.subject?.relationshipSubjectSet.remove(self.managedNode) self.managedNode.subject = e e.relationshipSubjectSet.insert(self.managedNode) } else { self.managedNode.subject?.relationshipSubjectSet.remove(self.managedNode) self.managedNode.subject = nil } } } } /// A reference to the object Entity. public var object: Entity? { get { return managedNode.performAndWait { relationship in relationship.object.map { Entity(managedNode: $0) } } } set(entity) { managedNode.managedObjectContext?.performAndWait { [unowned self] in if let e = entity?.managedNode { self.managedNode.object?.relationshipObjectSet.remove(self.managedNode) self.managedNode.object = e e.relationshipObjectSet.insert(self.managedNode) } else { self.managedNode.object?.relationshipObjectSet.remove(self.managedNode) self.managedNode.object = nil } } } } /// Generic creation of the managed node type. override class func createNode(_ type: String, in context: NSManagedObjectContext) -> ManagedNode { return ManagedRelationship(type, managedObjectContext: context) } /** Initializer that accepts a ManagedAction. - Parameter managedNode: A reference to a ManagedAction. */ required init(managedNode: ManagedNode) { super.init(managedNode: managedNode) } /** Checks equality between Entities. - Parameter object: A reference to an object to test equality against. - Returns: A boolean of the result, true if equal, false otherwise. */ public override func isEqual(_ object: Any?) -> Bool { return id == (object as? Relationship)?.id } /** Sets the object of the Relationship. - Parameter _ entity: An Entity. - Returns: The Relationship. */ @discardableResult public func of(_ entity: Entity) -> Relationship { self.object = entity return self } /** Sets the object of the Relationship. - Parameter object: An Entity. - Returns: The Relationship. */ @discardableResult public func `in`(object: Entity) -> Relationship { self.object = object return self } } extension Array where Element: Relationship { /** Finds the given types of subject Entities that are part of the relationships in the Array. - Parameter types: An Array of Strings. - Returns: An Array of Entities. */ public func subject(types: String...) -> [Entity] { return subject(types: types) } /** Finds the given types of subject Entities that are part of the relationships in the Array. - Parameter types: An Array of Strings. - Returns: An Array of Entities. */ public func subject(types: [String]) -> [Entity] { var s : Set<Entity> = [] forEach { [types = types] (r) in guard let e = r.subject else { return } guard types.contains(e.type) else { return } s.insert(e) } return [Entity](s) } /** Finds the given types of object Entities that are part of the relationships in the Array. - Parameter types: An Array of Strings. - Returns: An Array of Entities. */ public func object(types: String...) -> [Entity] { return object(types: types) } /** Finds the given types of object Entities that are part of the relationships in the Array. - Parameter types: An Array of Strings. - Returns: An Array of Entities. */ public func object(types: [String]) -> [Entity] { var s : Set<Entity> = [] forEach { [types = types] (r) in guard let e = r.subject else { return } guard types.contains(e.type) else { return } s.insert(e) } return [Entity](s) } }
agpl-3.0
bdb1e2aabd67924c2e8b9dc5d01a9806
30.815534
234
0.671803
4.360612
false
false
false
false
ambientlight/Perfect
Sources/PerfectLib/SwiftCompatibility.swift
1
1265
// // SwiftCompatibility.swift // PerfectLib // // Created by Kyle Jessup on 2016-04-22. // Copyright © 2016 PerfectlySoft. All rights reserved. // extension String { func range(ofString string: String, ignoreCase: Bool = false) -> Range<String.Index>? { var idx = self.startIndex let endIdx = self.endIndex while idx != endIdx { if ignoreCase ? (String(self[idx]).lowercased() == String(string[string.startIndex]).lowercased()) : (self[idx] == string[string.startIndex]) { var newIdx = self.index(after: idx) var findIdx = string.index(after: string.startIndex) let findEndIdx = string.endIndex while newIdx != endIndex && findIdx != findEndIdx && (ignoreCase ? (String(self[newIdx]).lowercased() == String(string[findIdx]).lowercased()) : (self[newIdx] == string[findIdx])) { newIdx = self.index(after: newIdx) findIdx = string.index(after: findIdx) } if findIdx == findEndIdx { // match return idx..<newIdx } } idx = self.index(after: idx) } return nil } }
apache-2.0
d7d8925437adf85d84d59fbb26ab6fa4
37.30303
197
0.541139
4.358621
false
false
false
false
iAugux/Weboot
Weboot/NSString+Additions.swift
1
800
// // NSString+Addtions.swift // iBBS // // Created by Augus on 9/5/15. // Copyright © 2015 iAugus. All rights reserved. // import Foundation extension NSString{ func ausCalculateSize(size: CGSize, font: UIFont) -> CGSize { var expectedLabelSize: CGSize = CGSizeZero let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping let attributes: [String : AnyObject] = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle.copy()] expectedLabelSize = self.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height)) } }
mit
a6df31106a4647575c3ef3766058a7ca
37.095238
158
0.737171
4.932099
false
false
false
false
mrchenhao/American-TV-Series-Calendar
American-tv-series-calendar/MovieCollectionCell.swift
1
647
// // MovieCollectionCell.swift // American-tv-series-calendar // // Created by ChenHao on 10/27/15. // Copyright © 2015 HarriesChen. All rights reserved. // import UIKit import AVOSCloud class MovieCollectionCell: UICollectionViewCell { @IBOutlet weak var movieImageView: UIImageView! @IBOutlet weak var movieTitleLabel: UILabel! func configCell(movie: Movie) { self.backgroundColor = UIColor.whiteColor() let imageFile: AVFile = movie.cover let imageData: NSData = imageFile.getData() movieImageView.image = UIImage(data: imageData) movieTitleLabel.text = movie.name } }
mit
3cb832f465e98fb9a60a8f0cd91f3063
25.916667
55
0.695046
4.194805
false
false
false
false
psharanda/adocgen
adocgen/CellModel.swift
1
1502
// // Copyright © 2016 Pavel Sharanda. All rights reserved. // import Foundation import SwiftyJSON class CellModel { func fromJson(_ json: JSON) { } required init() { } } /** Simplest type of cell. Has optional title and icon. Corresponds to cell of .Default style. */ class DefaultCellModel : CellModel { /** The name of a book, chapter, poem, essay, picture, statue, piece of music, play, film, etc */ var title: String? /** The name of icon */ var iconName: String? override func fromJson(_ json: JSON) { self.title = json["title"].string self.iconName = json["iconName"].string } } /** More advance type of cell. Has optional subtitle addionally to title and icon. Corresponds to cell of .Subtitle style. */ class SubtitleCellModel : DefaultCellModel { /** A secondary or explanatory title, as of a book or play */ var subtitle: String = "DEFAULT_SUBTITLE" override func fromJson(_ json: JSON) { super.fromJson(json) if let s = json["subtitle"].string { self.subtitle = s } } } /** Nice looking cell with title from the left and subtitle from the right. Corresponds to cell of .Value1 style. */ class Value1CellModel: SubtitleCellModel { } /** Ugly looking cell with blue title. Corresponds to cell of .Value2 style. */ class Value2CellModel: SubtitleCellModel { }
mit
917bf55d470ae717045fc82107d88665
19.283784
120
0.616922
4.078804
false
false
false
false
mro/ShaarliOS
swift4/ShaarliOS/SettingsVC.swift
1
13105
// // SettingsVC.swift // ShaarliOS // // Created by Marcus Rohrmoser on 21.02.20. // Copyright © 2020-2022 Marcus Rohrmoser mobile Software http://mro.name/me. All rights reserved. // // 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 UIKit import WebKit internal func endpoints(_ base : String?, _ uid : String?, _ pwd : String?) -> ArraySlice<URL> { var urls = ArraySlice<URL>() guard let base = base?.trimmingCharacters(in:.whitespacesAndNewlines) else { return urls } let base_ = base.hasPrefix(HTTP_HTTPS + "://") ? String(base.dropFirst(HTTP_HTTPS.count+"://".count)) : base.hasPrefix(HTTP_HTTP + "://") ? String(base.dropFirst(HTTP_HTTP.count+"://".count)) : base.hasPrefix("//") ? String(base.dropFirst("//".count)) : base guard var ep = URLComponents(string:"//\(base_)") else { return urls } ep.user = uid ep.password = pwd ep.scheme = HTTP_HTTPS; urls.append(ep.url!) ep.scheme = HTTP_HTTP; urls.append(ep.url!) let php = "/index.php" let pa = ep.path.dropLast(ep.path.hasSuffix(php) ? php.count : ep.path.hasSuffix("/") ? 1 : 0) ep.path = pa + php ep.scheme = HTTP_HTTPS; urls.append(ep.url!) ep.scheme = HTTP_HTTP; urls.append(ep.url!) return urls } class SettingsVC: UITableViewController, UITextFieldDelegate, WKNavigationDelegate { @IBOutlet private var txtEndpoint : UITextField! @IBOutlet private var sldTimeout : UISlider! @IBOutlet private var txtTimeout : UITextField! @IBOutlet private var swiSecure : UISwitch! @IBOutlet private var txtUserName : UITextField! @IBOutlet private var txtPassWord : UITextField! @IBOutlet private var txtBasicUid : UITextField! @IBOutlet private var txtBasicPwd : UITextField! @IBOutlet private var lblTitle : UILabel! @IBOutlet private var txtTags : UITextField! @IBOutlet private var spiLogin : UIActivityIndicatorView! @IBOutlet private var cellAbout : UITableViewCell! private let wwwAbout = WKWebView() var current : BlogM? // MARK: - Lifecycle // https://www.objc.io/blog/2018/04/24/bindings-with-kvo-and-keypaths/ override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Settings", comment:"SettingsVC") navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target:self, action:#selector(SettingsVC.actionCancel(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target:self, action:#selector(SettingsVC.actionSignIn(_:))) view.addSubview(spiLogin) spiLogin.backgroundColor = .clear txtTimeout.placeholder = NSLocalizedString("sec", comment:"SettingsVC") sldTimeout.minimumValue = Float(timeoutMinimumValue) sldTimeout.maximumValue = Float(timeoutMaximumValue) sldTimeout.value = Float(timeoutDefaultValue) [txtEndpoint, txtBasicUid, txtBasicPwd, txtTimeout, txtUserName, txtPassWord, txtTags].forEach { $0.setValue($0.textColor?.withAlphaComponent(0.4), forKeyPath:"placeholderLabel.textColor") } guard let url = Bundle(for:type(of:self)).url(forResource:"about", withExtension:"html") else { return } cellAbout.contentView.addSubview(wwwAbout) wwwAbout.navigationDelegate = self wwwAbout.frame = cellAbout!.contentView.bounds.insetBy(dx: 8, dy: 8) wwwAbout.autoresizingMask = [.flexibleWidth, .flexibleHeight] wwwAbout.contentScaleFactor = 1.0 wwwAbout.scrollView.isScrollEnabled = false wwwAbout.scrollView.bounces = false wwwAbout.isOpaque = false // avoid white flash https://stackoverflow.com/a/15670274 wwwAbout.backgroundColor = .black wwwAbout.customUserAgent = SHAARLI_COMPANION_APP_URL wwwAbout.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent()) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) spiLogin.stopAnimating() navigationItem.rightBarButtonItem?.isEnabled = true txtEndpoint.becomeFirstResponder() togui(current) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) spiLogin.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = spiLogin.centerXAnchor.constraint(equalTo: lblTitle.centerXAnchor) let verticalConstraint = spiLogin.centerYAnchor.constraint(equalTo: lblTitle.centerYAnchor) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint]) guard let url = UIPasteboard.general.url else { return } let alert = UIAlertController( title:NSLocalizedString("Use URL form Clipboard", comment: "SettingsVC"), message:String(format:NSLocalizedString("do you want to use the URL\n'%@'\nas shaarli endpoint?", comment:"SettingsVC"), url.description), preferredStyle:.alert ) alert.addAction(UIAlertAction( title:NSLocalizedString("Cancel", comment:"SettingsVC"), style:.cancel, handler:nil)) alert.addAction(UIAlertAction( title: NSLocalizedString("Yes", comment:"SettingsVC"), style:.default, handler:{(_) in self.togui(url)})) present(alert, animated:true, completion:nil) } private func togui(_ ur : URL?) { txtEndpoint.text = nil txtUserName.text = nil txtPassWord.text = nil swiSecure.isOn = false guard let ur = ur else { return } guard var uc = URLComponents(url:ur, resolvingAgainstBaseURL:true) else { return } txtUserName.text = uc.user txtPassWord.text = uc.password swiSecure.isOn = HTTP_HTTPS == uc.scheme uc.password = nil uc.user = nil uc.scheme = nil guard let s = uc.url?.absoluteString else { return } let su = s.suffix(from:.init(utf16Offset:2, in:s)) txtEndpoint.text = String(su) } private func togui(_ b : BlogM?) { guard let b = b else { lblTitle.text = NSLocalizedString("No Shaarli yet.", comment:"SettingsVC") lblTitle.textColor = .red return } lblTitle.textColor = ShaarliM.labelColor lblTitle.text = b.title; txtBasicUid.text = nil txtBasicPwd.text = nil if let cred = b.credential { if cred.hasPassword { txtBasicUid.text = cred.user txtBasicPwd.text = cred.password } } togui(b.endpoint) sldTimeout.value = Float(b.timeout) sldTimeoutChanged(self) txtTags.text = b.tagsDefault } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let vc = segue.destination as? MainVC else {return} vc.current = current } // MARK: - Actions @IBAction func sldTimeoutChanged(_ sender: Any) { txtTimeout.text = String(format:"%.1f", sldTimeout.value) } @IBAction func actionCancel(_ sender: Any) { print("actionCancel \(type(of: self))") guard let navigationController = navigationController else { return } navigationController.popViewController(animated:true) } @IBAction func actionSignIn(_ sender: Any) { print("actionSignIn \(type(of: self))") lblTitle.textColor = ShaarliM.labelColor lblTitle.text = NSLocalizedString("", comment:"SettingsVC")// … probing server … spiLogin.startAnimating() let cli = ShaarliHtmlClient(AppDelegate.shared.semver) let tim = TimeInterval(sldTimeout.value) let cre = URLCredential(user:txtBasicUid.text ?? "", password:txtBasicPwd.text ?? "", persistence:.forSession) func recurse(_ urls:ArraySlice<URL>) { guard let cur = urls.first else { self.failure("Oops, something went utterly wrong.") return } cli.probe(cur, cre, tim) { (ur, ti, pride, tizo, er) in guard !ShaarliHtmlClient.isOk(er) else { self.success(ur, cre, ti, pride, tizo, tim) return } let res = urls.dropFirst() let tryNext = !res.isEmpty // todo: and not banned guard tryNext else { self.failure(er) return } recurse(res) } } let urls = endpoints(txtEndpoint.text, txtUserName.text, txtPassWord.text) spiLogin.startAnimating() navigationItem.rightBarButtonItem?.isEnabled = false recurse(urls) } // MARK: - Controller Logic private func success(_ ur:URL, _ cre:URLCredential?, _ ti:String, _ pride:Bool, _ tizo:TimeZone?, _ tim:TimeInterval) { let ad = ShaarliM.shared DispatchQueue.main.sync { ad.saveBlog(ad.defaults, BlogM( endpoint:ur, credential:cre, title:ti, timeout:tim, privateDefault:pride, timezone:tizo, tagsDefault:txtTags.text ?? "" )) navigationController?.popViewController(animated:true) } } private func failure(_ er:String) { DispatchQueue.main.sync { spiLogin.stopAnimating() navigationItem.rightBarButtonItem?.isEnabled = true self.lblTitle.textColor = .red self.lblTitle.text = er } } // MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("textFieldShouldReturn \(type(of: self))") switch textField { case txtEndpoint: txtUserName.becomeFirstResponder() case txtUserName: txtPassWord.becomeFirstResponder() case txtPassWord: txtTags.becomeFirstResponder() case txtTags: txtTimeout.becomeFirstResponder() case txtTimeout: txtBasicUid.becomeFirstResponder() case txtBasicUid: txtBasicPwd.becomeFirstResponder() case txtBasicPwd: textField.resignFirstResponder() actionSignIn(textField) // keyboard doesn't show 'Done', but just in case... dispatch async? default: return false } return true } func textFieldDidEndEditing(_ textField: UITextField) { print("textFieldDidEndEditing \(type(of: self))") switch textField { case txtTimeout: guard let va = Float(txtTimeout.text ?? "") else { sldTimeout.value = Float(timeoutDefaultValue) sldTimeoutChanged(self) return } sldTimeout.value = Float(timeoutFromDouble(Double(va))) sldTimeoutChanged(self) default: break } } // MARK: - WKWebViewDelegate func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else {return} if "file" == url.scheme { decisionHandler(.allow) return } let app = UIApplication.shared if #available(iOS 10.0, *) { app.open(url) } else { app.openURL(url) } decisionHandler(.cancel) } func webView(_ sender:WKWebView, didFinish:WKNavigation!) { // even this late gives a flash sometimes: view.isOpaque = true let semv = AppDelegate.shared.semver let js = "injectVersion('\(semv)');" wwwAbout.evaluateJavaScript(js) { res,err in print(err as Any) } let s = wwwAbout.scrollView.contentSize cellAbout.contentView.bounds = CGRect(origin: .zero, size: s) } }
gpl-3.0
cdb1bdd3423f29c1f96aec22ea9260f3
38.577039
179
0.613817
4.647038
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/TextInputBinding/BindingForNSTextField.swift
1
6112
// // BindingForNSTextField.swift // TextInputKit // // Created by Artem Starosvetskiy on 24/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // #if os(macOS) import Foundation import Cocoa final class BindingForNSTextField<Value: Equatable> : TextInputBinding<Value> { // MARK: TextInputBinding<Value> Overrides override var text: String { get { return withTextField { textField in return textField.stringValue } } set(newText) { withTextField { textField in textField.stringValue = newText } } } override var selectedRange: Range<String.Index>? { get { return withTextField { textField in return textField.currentEditor()?.selectedIndexRange } } set(newSelectedRange) { withTextField { textField in guard let editor = textField.currentEditor() else { fatalError("Can't set the selected range while the bound `NSTextField` isn't editing.") } editor.selectedIndexRange = newSelectedRange } } } override var value: Value? { get { return withTextField { textField in return payload.objectValue(in: textField).value } } set { withTextField { textField in let text: String if let newValue = newValue { text = format.serializer.string(for: newValue) } else { text = "" } textField.objectValue = FormatterObjectValue( value: newValue, text: text) } } } override var eventHandler: EventHandler? { get { return payload.eventNotifier.eventHandler } set(newEventHandler) { payload.eventNotifier.eventHandler = newEventHandler } } public override func unbind() { if let textField = payload.boundTextField { textField.formatter = nil textField.delegate = nil payload.boundTextField = nil } } // MARK: Initializers init( _ format: TextInputFormat<Value>, _ textField: NSTextField) { self.payload = Payload(format, textField) self.responder = Responder(payload) super.init(format) bind(textField) } // MARK: Private Properties private let payload: Payload<Value> private let responder: Responder<Value> // MARK: Private Methods private func bind(_ textField: NSTextField) { textField.objectValue = FormatterObjectValue<Value>() textField.formatter = { var options = FormatterOptions.default() options.tracksCurrentEditorSelection = true return format.toFormatter(options) }() textField.delegate = responder } func withTextField<R>(_ closure: (NSTextField) -> R) -> R { guard let textField = payload.boundTextField else { fatalError("The `NSTextField` was unbound or deallocated.") } return closure(textField) } } private class Payload<Value: Equatable> { let format: TextInputFormat<Value> weak var boundTextField: NSTextField? var eventNotifier = TextInputEventNotifier<Value>() init(_ format: TextInputFormat<Value>, _ boundTextField: NSTextField) { self.format = format self.boundTextField = boundTextField } } extension Payload { func objectValue(in textField: NSTextField) -> FormatterObjectValue<Value> { guard let untypedObjectValue = textField.objectValue else { fatalError("`textField.objectValue` shouldn't be nil.") } guard let objectValue = untypedObjectValue as? FormatterObjectValue<Value> else { fatalError("Unexpected `textField.objectValue` type (expected: \(String(describing: FormatterObjectValue<Value>.self)), actual: \(String(describing: type(of: untypedObjectValue))))") } return objectValue } } private final class Responder<Value: Equatable> : NSObject, NSTextFieldDelegate { // MARK: Initializers init(_ payload: Payload<Value>) { self.payload = payload } // MARK: Control Events func controlTextDidBeginEditing(_ notification: Notification) { let textField = payload.boundTextField! assert(textField.currentEditor()! === notification.userInfo!["NSFieldEditor"] as! NSText) latestEditingState = currentEditingState(of: textField) payload.eventNotifier.on(.editingDidBegin) } func controlTextDidEndEditing(_ notification: Notification) { latestEditingState = nil payload.eventNotifier.on(.editingDidEnd) } func controlTextDidChange(_ notification: Notification) { let textField = payload.boundTextField! assert(textField.currentEditor()! === notification.userInfo!["NSFieldEditor"] as! NSText) let newEditingState = currentEditingState(of: textField) payload.eventNotifier.onEditingChanged(from: latestEditingState!, to: newEditingState) latestEditingState = newEditingState } // MARK: Private Properties private var payload: Payload<Value> private var latestEditingState: TextInputEditingState<Value>? // MARK: Private Methods @nonobjc private func currentEditingState(of textField: NSTextField) -> TextInputEditingState<Value> { guard let selectedRange = textField.currentEditor()!.selectedIndexRange else { fatalError("The selected range in a `UITextField` should be non-nil while editing.") } let objectValue = payload.objectValue(in: textField) return TextInputEditingState( text: objectValue.text, selectedRange: selectedRange, value: objectValue.value) } } #endif
mit
518e0500fa50cabcc9fe62cf22e56ca3
26.90411
194
0.618884
5.236504
false
false
false
false
mateuszfidosBLStream/MFCircleMenu
Example/ViewController.swift
1
2607
// // ViewController.swift // MFCircleMenu // // Created by Mateusz Fidos on 03.05.2016. // Copyright © 2016 mateusz.fidos. All rights reserved. // import UIKit import Foundation import MFCircleMenu class ViewController: UIViewController { var menuController:MFCircleMenu! override func viewDidLoad() { super.viewDidLoad() let mainAction: MainItemActionClosure = { if (self.menuController.menuState == .Closed) { self.menuController.openMenu() } else { self.menuController.closeMenu() } } let itemOneAction: ItemActionClosure = { print("Item One tapped") let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("nextViewController") self.presentViewController(controller, animated: true, completion: nil) } let itemTwoAction: ItemActionClosure = { print("Item Two tapped") } let mainCircle = MFCircleMenuMainItem(action: mainAction, closedStateImage: UIImage(named: "settings")!, openedStateImage: UIImage(named: "soundon")!, text: nil, backgroundColor: UIColor.redColor()) let itemOne = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemTwo = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) let itemThree = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemFour = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) let itemFive = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemSix = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) self.menuController = MFCircleMenu(mainItem: mainCircle, otherItems: [itemOne, itemTwo, itemThree, itemFour, itemFive, itemSix], parent: self.view, adjustToOrientation: false) self.menuController.showAtPosition(MFCircleMenuPosition.TopRight) } @IBAction func showMenu(sender: AnyObject) { self.menuController.showMenu() } @IBAction func hideMenu(sender: AnyObject) { self.menuController.hideMenu() } }
mit
3b9d7569c7c4fa3986445e3a0afd45ff
39.71875
206
0.679969
4.409475
false
false
false
false
justinhester/hacking-with-swift
src/Project11/Project11/GameScene.swift
1
6338
// // GameScene.swift // Project11 // // Created by Justin Lawrence Hester on 1/25/16. // Copyright (c) 2016 Justin Lawrence Hester. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene , SKPhysicsContactDelegate { var scoreLabel: SKLabelNode! var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var editLabel: SKLabelNode! var editingMode: Bool = false { didSet { if editingMode { editLabel.text = "Done" } else { editLabel.text = "Edit" } } } override func didMove(to view: SKView) { let background = SKSpriteNode(imageNamed: "background.jpg") background.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0) background.blendMode = .replace background.zPosition = -1 addChild(background) physicsBody = SKPhysicsBody(edgeLoopFrom: frame) physicsWorld.contactDelegate = self /* Make bouncers spaced evenly at the floor of the scene. */ makeBouncerAt(CGPoint(x: 0, y: 0)) makeBouncerAt(CGPoint(x: size.width / 4.0, y: 0)) makeBouncerAt(CGPoint(x: size.width / 2.0, y: 0)) makeBouncerAt(CGPoint(x: size.width * 3.0 / 4.0, y: 0)) makeBouncerAt(CGPoint(x: size.width, y: 0)) /* Make slots spaced in between bouncers. */ makeSlotAt(CGPoint(x: size.width / 8.0, y: 0), isGood: true) makeSlotAt(CGPoint(x: size.width * 3.0 / 8.0, y: 0), isGood: false) makeSlotAt(CGPoint(x: size.width * 5.0 / 8.0, y: 0), isGood: true) makeSlotAt(CGPoint(x: size.width * 7.0 / 8.0, y: 0), isGood: false) /* Add scoreboard. */ scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = .right scoreLabel.position = CGPoint(x: 980, y: 700) addChild(scoreLabel) /* Add edit label. */ editLabel = SKLabelNode(fontNamed: "Chalkduster") editLabel.text = "Edit" editLabel.position = CGPoint(x: 80, y: 700) addChild(editLabel) } func makeBouncerAt(_ position: CGPoint) { let bouncer = SKSpriteNode(imageNamed: "bouncer") bouncer.position = position bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width / 2.0) bouncer.physicsBody!.contactTestBitMask = bouncer.physicsBody!.collisionBitMask bouncer.physicsBody!.isDynamic = false addChild(bouncer) } func makeSlotAt(_ position: CGPoint, isGood: Bool) { var slotBase: SKSpriteNode var slotGlow: SKSpriteNode if isGood { slotBase = SKSpriteNode(imageNamed: "slotBaseGood") slotGlow = SKSpriteNode(imageNamed: "slotGlowGood") slotBase.name = "good" } else { slotBase = SKSpriteNode(imageNamed: "slotBaseBad") slotGlow = SKSpriteNode(imageNamed: "slotGlowBad") slotBase.name = "bad" } slotBase.position = position slotGlow.position = position /* Add rotation to the slot glow sprites. */ let spin = SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 10) let spinForever = SKAction.repeatForever(spin) slotGlow.run(spinForever) slotBase.physicsBody = SKPhysicsBody(rectangleOf: slotBase.size) slotBase.physicsBody!.isDynamic = false addChild(slotBase) addChild(slotGlow) } func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.node?.name == "ball" { collisionBetweenBall(contact.bodyA.node, object: contact.bodyB.node) } else if contact.bodyB.node?.name == "ball" { collisionBetweenBall(contact.bodyB.node, object: contact.bodyA.node) } } func collisionBetweenBall(_ ball: SKNode?, object: SKNode?) { if object?.name == "good" { destroyBall(ball!) score += 1 } else if object?.name == "bad" { destroyBall(ball!) score -= 1 } } func destroyBall(_ ball: SKNode) { if let fireParticles = SKEmitterNode(fileNamed: "FireParticles") { fireParticles.position = ball.position addChild(fireParticles) } ball.removeFromParent() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { /* Called when a touch begins */ if let touch = touches.first { let location = touch.location(in: self) /* Check if editLabel was clicked by user. */ let objects = nodes(at: location) as [SKNode] if objects.contains(editLabel) { /* Update editLabel with property observer. */ editingMode = !editingMode } else { if editingMode { /* Create a box. */ let size = CGSize( width: GKRandomDistribution(lowestValue: 16, highestValue: 128).nextInt(), height: 16 ) let box = SKSpriteNode(color: RandomColor(), size: size) box.zRotation = RandomCGFloat(min: 0, max: 3) box.position = location box.physicsBody = SKPhysicsBody(rectangleOf: box.size) box.physicsBody!.isDynamic = false addChild(box) } else { /* Create ball sprite. */ let ball = SKSpriteNode(imageNamed: "ballRed") ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0) ball.physicsBody!.contactTestBitMask = ball.physicsBody!.collisionBitMask ball.physicsBody!.restitution = 0.4 ball.position = location ball.name = "ball" addChild(ball) } } } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ } }
gpl-3.0
beb2f3ab8cbfe3447b8fffe0ea60f838
35.217143
98
0.560745
4.569575
false
false
false
false
huynguyencong/DataCache
Sources/DataCache.swift
1
13561
// // Cache.swift // CacheDemo // // Created by Nguyen Cong Huy on 7/4/16. // Copyright © 2016 Nguyen Cong Huy. All rights reserved. // import UIKit public enum ImageFormat { case unknown, png, jpeg } open class DataCache { static let cacheDirectoryPrefix = "com.nch.cache." static let ioQueuePrefix = "com.nch.queue." static let defaultMaxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 // a week public static let instance = DataCache(name: "default") let cachePath: String let memCache = NSCache<AnyObject, AnyObject>() let ioQueue: DispatchQueue let fileManager: FileManager /// Name of cache open var name: String = "" /// Life time of disk cache, in second. Default is a week open var maxCachePeriodInSecond = DataCache.defaultMaxCachePeriodInSecond /// Size is allocated for disk cache, in byte. 0 mean no limit. Default is 0 open var maxDiskCacheSize: UInt = 0 /// Specify distinc name param, it represents folder name for disk cache public init(name: String, path: String? = nil) { self.name = name var cachePath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first! cachePath = (cachePath as NSString).appendingPathComponent(DataCache.cacheDirectoryPrefix + name) self.cachePath = cachePath ioQueue = DispatchQueue(label: DataCache.ioQueuePrefix + name) self.fileManager = FileManager() #if !os(OSX) && !os(watchOS) NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.willTerminateNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.didEnterBackgroundNotification, object: nil) #endif } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: - Store data extension DataCache { /// Write data for key. This is an async operation. public func write(data: Data, forKey key: String) { memCache.setObject(data as AnyObject, forKey: key as AnyObject) writeDataToDisk(data: data, key: key) } private func writeDataToDisk(data: Data, key: String) { ioQueue.async { if self.fileManager.fileExists(atPath: self.cachePath) == false { do { try self.fileManager.createDirectory(atPath: self.cachePath, withIntermediateDirectories: true, attributes: nil) } catch { print("DataCache: Error while creating cache folder: \(error.localizedDescription)") } } self.fileManager.createFile(atPath: self.cachePath(forKey: key), contents: data, attributes: nil) } } /// Read data for key public func readData(forKey key:String) -> Data? { var data = memCache.object(forKey: key as AnyObject) as? Data if data == nil { if let dataFromDisk = readDataFromDisk(forKey: key) { data = dataFromDisk memCache.setObject(dataFromDisk as AnyObject, forKey: key as AnyObject) } } return data } /// Read data from disk for key public func readDataFromDisk(forKey key: String) -> Data? { return self.fileManager.contents(atPath: cachePath(forKey: key)) } // MARK: - Read & write Codable types public func write<T: Encodable>(codable: T, forKey key: String) throws { let data = try JSONEncoder().encode(codable) write(data: data, forKey: key) } public func readCodable<T: Decodable>(forKey key: String) throws -> T? { guard let data = readData(forKey: key) else { return nil } return try JSONDecoder().decode(T.self, from: data) } // MARK: - Read & write primitive types /// Write an object for key. This object must inherit from `NSObject` and implement `NSCoding` protocol. `String`, `Array`, `Dictionary` conform to this method. /// /// NOTE: Can't write `UIImage` with this method. Please use `writeImage(_:forKey:)` to write an image public func write(object: NSCoding, forKey key: String) { let data = NSKeyedArchiver.archivedData(withRootObject: object) write(data: data, forKey: key) } /// Write a string for key public func write(string: String, forKey key: String) { write(object: string as NSCoding, forKey: key) } /// Write a dictionary for key public func write(dictionary: Dictionary<AnyHashable, Any>, forKey key: String) { write(object: dictionary as NSCoding, forKey: key) } /// Write an array for key public func write(array: Array<Any>, forKey key: String) { write(object: array as NSCoding, forKey: key) } /// Read an object for key. This object must inherit from `NSObject` and implement NSCoding protocol. `String`, `Array`, `Dictionary` conform to this method public func readObject(forKey key: String) -> NSObject? { let data = readData(forKey: key) if let data = data { return NSKeyedUnarchiver.unarchiveObject(with: data) as? NSObject } return nil } /// Read a string for key public func readString(forKey key: String) -> String? { return readObject(forKey: key) as? String } /// Read an array for key public func readArray(forKey key: String) -> Array<Any>? { return readObject(forKey: key) as? Array<Any> } /// Read a dictionary for key public func readDictionary(forKey key: String) -> Dictionary<AnyHashable, Any>? { return readObject(forKey: key) as? Dictionary<AnyHashable, Any> } // MARK: - Read & write image /// Write image for key. Please use this method to write an image instead of `writeObject(_:forKey:)` public func write(image: UIImage, forKey key: String, format: ImageFormat? = nil) { var data: Data? = nil if let format = format, format == .png { data = image.pngData() } else { data = image.jpegData(compressionQuality: 0.9) } if let data = data { write(data: data, forKey: key) } } /// Read image for key. Please use this method to write an image instead of `readObject(forKey:)` public func readImage(forKey key: String) -> UIImage? { let data = readData(forKey: key) if let data = data { return UIImage(data: data, scale: 1.0) } return nil } @available(*, deprecated, message: "Please use `readImage(forKey:)` instead. This will be removed in the future.") public func readImageForKey(key: String) -> UIImage? { return readImage(forKey: key) } } // MARK: - Utils extension DataCache { /// Check if has data for key public func hasData(forKey key: String) -> Bool { return hasDataOnDisk(forKey: key) || hasDataOnMem(forKey: key) } /// Check if has data on disk public func hasDataOnDisk(forKey key: String) -> Bool { return self.fileManager.fileExists(atPath: self.cachePath(forKey: key)) } /// Check if has data on mem public func hasDataOnMem(forKey key: String) -> Bool { return (memCache.object(forKey: key as AnyObject) != nil) } } // MARK: - Clean extension DataCache { /// Clean all mem cache and disk cache. This is an async operation. public func cleanAll() { cleanMemCache() cleanDiskCache() } /// Clean cache by key. This is an async operation. public func clean(byKey key: String) { memCache.removeObject(forKey: key as AnyObject) ioQueue.async { do { try self.fileManager.removeItem(atPath: self.cachePath(forKey: key)) } catch { print("DataCache: Error while remove file: \(error.localizedDescription)") } } } public func cleanMemCache() { memCache.removeAllObjects() } public func cleanDiskCache() { ioQueue.async { do { try self.fileManager.removeItem(atPath: self.cachePath) } catch { print("DataCache: Error when clean disk: \(error.localizedDescription)") } } } /// Clean expired disk cache. This is an async operation. @objc public func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } // This method is from Kingfisher /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ open func cleanExpiredDiskCache(completion handler: (()->())? = nil) { // Do things in cocurrent io queue ioQueue.async { var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false) for fileURL in URLsToDelete { do { try self.fileManager.removeItem(at: fileURL) } catch { print("DataCache: Error while removing files \(error.localizedDescription)") } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue { resourceValue1, resourceValue2 -> Bool in if let date1 = resourceValue1.contentAccessDate, let date2 = resourceValue2.contentAccessDate { return date1.compare(date2) == .orderedAscending } // Not valid date information. This should not happen. Just in case. return true } for fileURL in sortedFiles { do { try self.fileManager.removeItem(at: fileURL) } catch { print("DataCache: Error while removing files \(error.localizedDescription)") } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize { diskCacheSize -= UInt(fileSize) } if diskCacheSize < targetSize { break } } } DispatchQueue.main.async(execute: { () -> Void in handler?() }) } } } // MARK: - Helpers extension DataCache { // This method is from Kingfisher fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) { let diskCacheURL = URL(fileURLWithPath: cachePath) let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey] let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond) var cachedFiles = [URL: URLResourceValues]() var urlsToDelete = [URL]() var diskCacheSize: UInt = 0 for fileUrl in (try? fileManager.contentsOfDirectory(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)) ?? [] { do { let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys) // If it is a Directory. Continue to next file URL. if resourceValues.isDirectory == true { continue } // If this file is expired, add it to URLsToDelete if !onlyForCacheSize, let expiredDate = expiredDate, let lastAccessData = resourceValues.contentAccessDate, (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate { urlsToDelete.append(fileUrl) continue } if let fileSize = resourceValues.totalFileAllocatedSize { diskCacheSize += UInt(fileSize) if !onlyForCacheSize { cachedFiles[fileUrl] = resourceValues } } } catch { print("DataCache: Error while iterating files \(error.localizedDescription)") } } return (urlsToDelete, diskCacheSize, cachedFiles) } func cachePath(forKey key: String) -> String { let fileName = key.md5 return (cachePath as NSString).appendingPathComponent(fileName) } }
mit
74907b38d68ecc74137d2adde988da6f
34.873016
165
0.580015
5.150019
false
false
false
false
gradyzhuo/Acclaim
Sources/Procedure/Procedure.swift
1
1552
public enum FlowControl { case `repeat` case nextWith(filter: (Intents)->Intents) case previousWith(filter: (Intents)->Intents) case cancel case finish case jumpTo(other: Step, filter: (Intents)->Intents) public static var next: FlowControl { return .nextWith(filter: { $0 }) } public static var previous: FlowControl{ return .previousWith(filter: { $0 }) } public static func jump(other: Step)->FlowControl{ return .jumpTo(other: other, filter: { $0 }) } } open class Procedure : Step, Flowable, Identitiable{ public private(set) var start: Step public private(set) var end: Step public var previous: Step? public var identifier: String = Utils.Generator.identifier() public var next: Step?{ set{ end.next = newValue } get{ return end.next } } public func run(with intents: Intents = []) { start.run(with: intents) } public lazy var name: String = self.identifier public init(start: Step) { self.start = start self.end = start.last } public func step(at index: Int)->Step?{ var target: Step? = start for _ in 0...index{ target = target?.next } return target } public func extend(with newLastStep: Step){ end.next = newLastStep end = newLastStep.last } public func syncEndStep(){ end = start.last } }
mit
420d0daf8d83aaf20e1cb31bc185a91b
21.823529
64
0.566366
4.252055
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/BrowserPrompts.swift
2
6163
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared @objc protocol JSPromptAlertControllerDelegate: class { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) } /// A simple version of UIAlertController that attaches a delegate to the viewDidDisappear method /// to allow forwarding the event. The reason this is needed for prompts from Javascript is we /// need to invoke the completionHandler passed to us from the WKWebView delegate or else /// a runtime exception is thrown. class JSPromptAlertController: UIAlertController { var alertInfo: JSAlertInfo? weak var delegate: JSPromptAlertControllerDelegate? override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) alertInfo?.alertWillDismiss() delegate?.promptAlertControllerDidDismiss(self) } } /** * An JSAlertInfo is used to store information about an alert we want to show either immediately or later. * Since alerts are generated by web pages and have no upper limit it would be unwise to allocate a * UIAlertController instance for each generated prompt which could potentially be queued in the background. * Instead, the JSAlertInfo structure retains the relevant data needed for the prompt along with a copy * of the provided completionHandler to let us generate the UIAlertController when needed. */ protocol JSAlertInfo { /** * A word about this mutating keyword here. These prompts should be calling their completion handlers when * the prompt is actually dismissed - not when the user selects an option. Ideally this would be handled * inside the JSPromptAlertController subclass in the viewDidDisappear callback but UIAlertController * was built to not be subclassed. Instead, when allocate the JSPromptAlertController we pass along a * reference to the alertInfo structure and manipulate the required state from the action handlers. */ mutating func alertController() -> JSPromptAlertController func alertWillDismiss() func cancel() } struct MessageAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: () -> Void mutating func alertController() -> JSPromptAlertController { let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: Strings.OK, style: UIAlertActionStyle.default, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler() } func cancel() { completionHandler() } } struct ConfirmPanelAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: (Bool) -> Void var didConfirm: Bool = false init(message: String, frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { self.message = message self.frame = frame self.completionHandler = completionHandler } mutating func alertController() -> JSPromptAlertController { // Show JavaScript confirm dialogs. let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.alert) var localSelf = self alertController.addAction(UIAlertAction(title: Strings.OK, style: UIAlertActionStyle.default, handler: { _ in localSelf.didConfirm = true })) alertController.addAction(UIAlertAction(title: Strings.Cancel, style: UIAlertActionStyle.cancel, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler(didConfirm) } func cancel() { completionHandler(false) } } struct TextInputAlert: JSAlertInfo { let message: String let frame: WKFrameInfo let completionHandler: (String?) -> Void let defaultText: String? var input: UITextField! init(message: String, frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void, defaultText: String?) { self.message = message self.frame = frame self.completionHandler = completionHandler self.defaultText = defaultText } mutating func alertController() -> JSPromptAlertController { let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: UIAlertControllerStyle.alert) var localSelf = self alertController.addTextField(configurationHandler: { (textField: UITextField) in localSelf.input = textField localSelf.input.text = localSelf.defaultText }) alertController.addAction(UIAlertAction(title: Strings.OK, style: UIAlertActionStyle.default, handler: nil)) alertController.addAction(UIAlertAction(title: Strings.Cancel, style: UIAlertActionStyle.cancel, handler: nil)) alertController.alertInfo = self return alertController } func alertWillDismiss() { completionHandler(input.text) } func cancel() { completionHandler(nil) } } /// Show a title for a JavaScript Panel (alert) based on the WKFrameInfo. On iOS9 we will use the new securityOrigin /// and on iOS 8 we will fall back to the request URL. If the request URL is nil, which happens for JavaScript pages, /// we fall back to "JavaScript" as a title. private func titleForJavaScriptPanelInitiatedByFrame(_ frame: WKFrameInfo) -> String { var title: String = "JavaScript" title = "\(frame.securityOrigin.`protocol`)://\(frame.securityOrigin.host)" if frame.securityOrigin.port != 0 { title += ":\(frame.securityOrigin.port)" } return title }
mpl-2.0
461e6d0984ddac53a15dd175c0fce2c6
38.76129
172
0.722051
5.331315
false
false
false
false
tinpay/TogglKit
TogglKit/TogglRequest.swift
1
2231
// // TogglRequest.swift // TogglKit // // Created by tinpay on 2015/09/11. // Copyright © 2015年 tinpay. All rights reserved. // import APIKit import Himotoki public protocol TogglRequest: RequestType { } public var togglAPIToken:String = "" public extension TogglRequest { public var baseURL:NSURL { return NSURL(string:"https://www.toggl.com/api/v8")! } func configureURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { let username = togglAPIToken let password = "api_token" let loginString = NSString(format: "%@:%@", username, password) let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)! let base64LoginString = loginData.base64EncodedStringWithOptions([]) URLRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") return URLRequest } } public class TimeEntriesRequest:TogglRequest { let startDate:NSDate let endDate:NSDate public init(startDate:NSDate,endDate:NSDate){ self.startDate = startDate self.endDate = endDate } public typealias Response = [TimeEntry] public var method: HTTPMethod {return .GET} public var path:String {return "/time_entries"} public var parameters: [String: AnyObject] { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+09:00" return [ "start_date": dateFormatter.stringFromDate(startDate), "end_date": dateFormatter.stringFromDate(endDate) ] } public func responseFromObject(object:AnyObject, URLResponse: NSHTTPURLResponse) -> Response? { return try? decodeArray(object) } } public class ProjectsRequest:TogglRequest { let projectId:Int public init(projectId:Int){ self.projectId = projectId } public typealias Response = Project public var method: HTTPMethod {return .GET} public var path:String {return "/projects/\(projectId)"} public func responseFromObject(object:AnyObject, URLResponse: NSHTTPURLResponse) -> Response? { return try? decodeValue(object) } }
mit
0bbaf6e9099d686852ad8bb72bf5d4b8
26.85
99
0.676391
4.546939
false
false
false
false
ifeherva/HSTracker
HSTracker/Logging/Entity.swift
1
4892
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 14/02/16. */ import Foundation import Wrap class Entity { var id: Int var cardId = "" var name: String? var tags: [GameTag: Int] = [:] lazy var info: EntityInfo = { [unowned(unsafe) self] in return EntityInfo(entity: self) }() init() { self.id = -1 } init(id: Int) { self.id = id } subscript(tag: GameTag) -> Int { set { tags[tag] = newValue } get { guard let value = tags[tag] else { return 0 } return value } } func has(tag: GameTag) -> Bool { return self[tag] > 0 } func isPlayer(eventHandler: PowerEventHandler) -> Bool { return self[.player_id] == eventHandler.player.id } var isActiveDeathrattle: Bool { return has(tag: .deathrattle) && self[.deathrattle] == 1 } var isCurrentPlayer: Bool { return has(tag: .current_player) } func isInZone(zone: Zone) -> Bool { return has(tag: .zone) ? self[.zone] == zone.rawValue : false } func isControlled(by controller: Int) -> Bool { return self.has(tag: .controller) ? self[.controller] == controller : false } var isSecret: Bool { return has(tag: .secret) } var isQuest: Bool { return has(tag: .quest) } var isSpell: Bool { return self[.cardtype] == CardType.spell.rawValue } func isOpponent(eventHandler: PowerEventHandler) -> Bool { return !isPlayer(eventHandler: eventHandler) && has(tag: .player_id) } var isMinion: Bool { return has(tag: .cardtype) && self[.cardtype] == CardType.minion.rawValue } var isWeapon: Bool { return has(tag: .cardtype) && self[.cardtype] == CardType.weapon.rawValue } var isHero: Bool { return self[.cardtype] == CardType.hero.rawValue } var isHeroPower: Bool { return self[.cardtype] == CardType.hero_power.rawValue } var isPlayableHero: Bool { return isHero && card.set != .core && card.set != .hero_skins && card.collectible } var isInHand: Bool { return isInZone(zone: .hand) } var isInDeck: Bool { return isInZone(zone: .deck) } var isInPlay: Bool { return isInZone(zone: .play) } var isInGraveyard: Bool { return isInZone(zone: .graveyard) } var isInSetAside: Bool { return isInZone(zone: .setaside) } var isInSecret: Bool { return isInZone(zone: .secret) } var health: Int { return self[.health] - self[.damage] } var attack: Int { return self[.atk] } var hasCardId: Bool { return !cardId.isBlank } private var _cachedCard: Card? var card: Card { if let card = _cachedCard { return card } else if let card = Cards.by(cardId: cardId) { return card } return Card() } func set(cardCount count: Int) { card.count = count } } extension Entity: NSCopying { func copy(with zone: NSZone? = nil) -> Any { let e = Entity(id: id) e.cardId = cardId e.name = name tags.forEach({ e.tags[$0.0] = $0.1 }) e.info.discarded = info.discarded e.info.returned = info.returned e.info.mulliganed = info.mulliganed e.info.created = info.created e.info.hasOutstandingTagChanges = info.hasOutstandingTagChanges e.info.originalController = info.originalController e.info.hidden = info.hidden e.info.turn = info.turn return e } } extension Entity: Hashable { var hashValue: Int { return id.hashValue } static func == (lhs: Entity, rhs: Entity) -> Bool { return lhs.id == rhs.id } } extension Entity: CustomStringConvertible { var description: String { let cardName = Cards.any(byId: cardId)?.name ?? "" let tags = self.tags.map { "\($0.0)=\($0.1)" }.joined(separator: ",") let hide = info.hidden && (isInHand || isInDeck) return "[Entity: id=\(id), cardId=\(hide ? "" : cardId), " + "cardName=\(hide ? "" : cardName), " + "name=\(String(describing: hide ? "" : name)), " + "tags=(\(tags)), " + "info=\(info)]" } } extension Entity: WrapCustomizable { func keyForWrapping(propertyNamed propertyName: String) -> String? { if ["_cachedCard", "card", "description"].contains(propertyName) { return nil } return propertyName.capitalized } }
mit
256406c5f8b26a59e76e79cd415a2a5e
24.34715
89
0.563982
3.919872
false
false
false
false
nlampi/SwiftGridView
Examples/Pretty/PrettyExample/Data/PECountry.swift
1
2094
// PECountry.swift // Copyright (c) 2016 - Present Nathan Lampi (http://nathanlampi.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation class PECountry { var name:String = "" var capital:String = "" var continent:String = "" var currency:String = "" var phone:String = "" var tld:String = "" var population:Int = -1 var area:Float = -1 init(dictionary:[String:Any]) { self.name = dictionary["name"] as! String self.capital = dictionary["capital"] as! String self.continent = dictionary["continent"] as! String self.currency = dictionary["currency"] as! String self.phone = dictionary["phone"] as! String self.tld = dictionary["tld"] as! String let argPopulation = dictionary["population"] as! String if argPopulation != "" { self.population = Int(argPopulation)! } let argArea = dictionary["area"] as! String if argArea != "" { self.area = Float(argArea)! } } }
mit
7f6e08fdce1378bef26cd3e85b972f58
39.269231
81
0.676695
4.380753
false
false
false
false
apple/swift
test/SILGen/capture_resilience.swift
1
4000
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift // RUN: %target-swift-emit-silgen -I %t -enable-library-evolution %s | %FileCheck %s import resilient_struct public struct ResilientStruct { public init() {} } // CHECK-LABEL: sil [ossa] @$s18capture_resilience13hasClosureLetAA15ResilientStructVycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> @out ResilientStruct public func hasClosureLet() -> () -> ResilientStruct { let s = ResilientStruct() // CHECK-LABEL: sil private [ossa] @$s18capture_resilience13hasClosureLetAA15ResilientStructVycyFADycfU_ : $@convention(thin) (ResilientStruct) -> @out ResilientStruct return { s } } // CHECK-LABEL: sil [ossa] @$s18capture_resilience13hasClosureVarAA15ResilientStructVycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> @out ResilientStruct public func hasClosureVar() -> () -> ResilientStruct { var s = ResilientStruct() // CHECK-LABEL: sil private [ossa] @$s18capture_resilience13hasClosureVarAA15ResilientStructVycyFADycfU_ : $@convention(thin) (@guaranteed { var ResilientStruct }) -> @out ResilientStruct return { s } } // CHECK-LABEL: sil [serialized] [ossa] @$s18capture_resilience22hasInlinableClosureLetAA15ResilientStructVycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> @out ResilientStruct @inlinable public func hasInlinableClosureLet() -> () -> ResilientStruct { let s = ResilientStruct() // CHECK-LABEL: sil shared [serialized] [ossa] @$s18capture_resilience22hasInlinableClosureLetAA15ResilientStructVycyFADycfU_ : $@convention(thin) (@in_guaranteed ResilientStruct) -> @out ResilientStruct return { s } } // CHECK-LABEL: sil [serialized] [ossa] @$s18capture_resilience22hasInlinableClosureVarAA15ResilientStructVycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> @out ResilientStruct @inlinable public func hasInlinableClosureVar() -> () -> ResilientStruct { var s = ResilientStruct() // CHECK-LABEL: sil shared [serialized] [ossa] @$s18capture_resilience22hasInlinableClosureVarAA15ResilientStructVycyFADycfU_ : $@convention(thin) (@guaranteed { var ResilientStruct }) -> @out ResilientStruct return { s } } public func consume(_: () -> ResilientStruct) {} // CHECK-LABEL: sil [ossa] @$s18capture_resilience21hasNoEscapeClosureLetyyF : $@convention(thin) () -> () public func hasNoEscapeClosureLet() { let s = ResilientStruct() // CHECK-LABEL: sil private [ossa] @$s18capture_resilience21hasNoEscapeClosureLetyyFAA15ResilientStructVyXEfU_ : $@convention(thin) (ResilientStruct) -> @out ResilientStruct consume { s } } // CHECK-LABEL: sil [ossa] @$s18capture_resilience21hasNoEscapeClosureVaryyF : $@convention(thin) () -> () public func hasNoEscapeClosureVar() { var s = ResilientStruct() // CHECK-LABEL: sil private [ossa] @$s18capture_resilience21hasNoEscapeClosureVaryyFAA15ResilientStructVyXEfU_ : $@convention(thin) (@inout_aliasable ResilientStruct) -> @out ResilientStruct consume { s } } // CHECK-LABEL: sil [serialized] [ossa] @$s18capture_resilience30hasInlinableNoEscapeClosureLetyyF : $@convention(thin) () -> () @inlinable public func hasInlinableNoEscapeClosureLet() { let s = ResilientStruct() // CHECK-LABEL: sil shared [serialized] [ossa] @$s18capture_resilience30hasInlinableNoEscapeClosureLetyyFAA15ResilientStructVyXEfU_ : $@convention(thin) (@in_guaranteed ResilientStruct) -> @out ResilientStruct consume { s } } // CHECK-LABEL: sil [serialized] [ossa] @$s18capture_resilience30hasInlinableNoEscapeClosureVaryyF : $@convention(thin) () -> () @inlinable public func hasInlinableNoEscapeClosureVar() { var s = ResilientStruct() // CHECK-LABEL: sil shared [serialized] [ossa] @$s18capture_resilience30hasInlinableNoEscapeClosureVaryyFAA15ResilientStructVyXEfU_ : $@convention(thin) (@inout_aliasable ResilientStruct) -> @out ResilientStruct consume { s } }
apache-2.0
8c151dc7932fbbd7d99a52c1dce2f11f
51.631579
213
0.75275
3.879728
false
false
false
false
tkach/SimpleRedditClient
SimpleRedditClient/Modules/EntriesList/Interactor/EntriesListInteractorImpl.swift
1
1612
// // Created by Alexander Tkachenko on 9/9/17. // import UIKit final class EntriesListInteractorImpl { weak var output: EntriesListInteractorOutput? fileprivate let entriesListService: EntriesListService fileprivate let entryItemBuilder: EntryItemBuilder fileprivate var loadedCount: Int = 0 init(entriesListService: EntriesListService) { self.entriesListService = entriesListService entryItemBuilder = EntryItemBuilder() } } extension EntriesListInteractorImpl: EntriesListInteractorInput { struct Constants { static let totalToLoad = 50 } func fetchNextEntries() { entriesListService.loadNextEntries() { [weak self] result in switch result { case .success(let response): self?.didLoad(response: response) case .error(let error): self?.didFail(with: error) } } } private func didLoad(response: EntriesListResponse) { let entries = response.list.map { self.entryItemBuilder.build(from: $0) } loadedCount += entries.count let hasNext = loadedCount < Constants.totalToLoad output?.didLoad(page: EntriesPage(entries: entries, hasNext: hasNext)) } private func didFail(with error: NetworkError) { let isFirstPageFailed = loadedCount == 0 let error = EntriesListError(text: "NetworkError".localized()) if (isFirstPageFailed) { output?.didFail(error: error) } else { output?.didFailLoadingNext(error: error) } } }
mit
5f88ba1fd3c8c96f36c882c55c336cb5
29.415094
81
0.645161
4.672464
false
false
false
false
focuspirit/PxDensity
PxDensity/RatioViewController.swift
1
2479
// // RatioViewController.swift // PxDensity // // Created by focuspirit on 05/02/15. // Copyright (c) 2015 focuspirit. All rights reserved. // import UIKit class RatioViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var number1: UITextField! @IBOutlet weak var number2: UITextField! @IBOutlet weak var calculateResult: UILabel! @IBOutlet weak var simpleRatio: UILabel! var ratioCalculator: RatioCalculator! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. ratioCalculator = RatioCalculator() var tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleSingleTap:")) tapGesture.numberOfTapsRequired = 1 tapGesture.delegate = self tapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(tapGesture) number1.text = toString(ratioCalculator.firstNumber) number2.text = toString(ratioCalculator.secondNumber) calculateResult.text = ratioCalculator.calculateResult simpleRatio.text = ratioCalculator.simpleRatio } func handleSingleTap(gesture: UIGestureRecognizer) { UIApplication.sharedApplication().keyWindow?.endEditing(true) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.view.endEditing(true) } override func prefersStatusBarHidden() -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func startEditing(sender: UITextField) { sender.textColor = UIColor.orangeColor() } @IBAction func finishedEditing(sender: UITextField) { sender.textColor = UIColor.lightGrayColor() if !number1.text.isEmpty && !number2.text.isEmpty { if let v1 = number1.text.toInt(), let v2 = number2.text.toInt() where (v1 > 0) && (v2 > 0) { ratioCalculator.firstNumber = v1 ratioCalculator.secondNumber = v2 calculateResult.text = ratioCalculator.calculateResult simpleRatio.text = ratioCalculator.simpleRatio } } } }
mit
145ce5d840adc4a3b627a8c417ba56c3
27.825581
104
0.6309
5.297009
false
false
false
false
hagmas/APNsKit
APNsKit/Connection.swift
1
3211
import Foundation public class Connection: NSObject, URLSessionDelegate { public enum Result { case success case failure(errorCode: Int, message: String) } let adapter: PKCS12Adapter public init(p12FileName: String, passPhrase: String) throws { self.adapter = try PKCS12Adapter(fileName: p12FileName, passPhrase: passPhrase) super.init() } public func send(request: APNsRequest, resultHandler: @escaping (Result) -> Void) { let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) if let urlRequest = request.urlRequest { let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in // The APNs server response for the requst is returned with the data object. // If the error object is not nil, there is more likely a problem with the connection or the network. if let error = error { resultHandler(.failure(errorCode: 0, message: "Unkonwn Error Occured: \(error)")) return } guard let data = data else { resultHandler(.success) return } if data.isEmpty { resultHandler(.success) return } if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: String], let reason = json?["reason"], let httpResponse = response as? HTTPURLResponse { resultHandler(.failure(errorCode: httpResponse.statusCode, message: reason)) return } else { resultHandler(.failure(errorCode: 0, message: "Unkonwn Error Occured")) return } }) task.resume() } } public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { // Nothing to do } #if os(iOS) || os(watchOS) || os(tvOS) public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { // Nothing to do } #endif public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodClientCertificate: let credential = URLCredential(identity: adapter.secIdentity, certificates: [adapter.secCertificate], persistence: .forSession) completionHandler(.useCredential, credential) case NSURLAuthenticationMethodServerTrust: if let serverTrust = challenge.protectionSpace.serverTrust { let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } default: break } } }
mit
6c64a9efd782edd8b11b61aaacc50cdb
40.701299
193
0.588602
5.935305
false
false
false
false
box/box-ios-sdk
Sources/Responses/SharedLink.swift
1
4905
import Foundation /// Defines the level of access to the item by its shared link. public enum SharedLinkAccess: BoxEnum { /// Anyone with the link can access. case open /// People in your company can access. case company /// People in this folder can access. case collaborators /// Custom value for enum values not yet implemented by the SDK case customValue(String) public init(_ value: String) { switch value { case "open": self = .open case "company": self = .company case "collaborators": self = .collaborators default: self = .customValue(value) } } public var description: String { switch self { case .open: return "open" case .company: return "company" case .collaborators: return "collaborators" case let .customValue(value): return value } } } /// Provides direct, read-only access to files or folder on Box using a URL public class SharedLink: BoxModel { /// Permission for a user accessing item by shared link public struct Permissions: BoxInnerModel { /// Whether the shared link allows previewing. For shared links on folders, this also applies to any items in the folder. public let canPreview: Bool? /// Whether the shared link allows downloads. For shared links on folders, this also applies to any items in the folder. public let canDownload: Bool? /// Whether the shared link allows editing of files. public let canEdit: Bool? } // MARK: - BoxModel public private(set) var rawData: [String: Any] // MARK: - Properties /// The URL to access the item on Box. If entered in a browser, this URL will display the item in Box's preview UI. /// If a custom URL is set this field will return the custom URL, but the original URL will also continue to work. public let url: URL? /// The "direct Link" URL to download the item. If entered in a browser, this URL will trigger a download of the item. /// This URL includes the file extension so that the file will be saved with the right file type. public let downloadURL: URL? /// The "Custom URL" that can also be used to preview the item on Box. /// Custom URLs can only be created or modified in the Box Web application. public let vanityURL: URL? /// The custom name of a shared link, as used in the vanityURL field. public let vanityName: String? /// The effective access level for the shared link. This can be lower than the value in the access field /// if the enterprise settings restrict the allowed access levels. public let effectiveAccess: String? /// Actual permissions that are allowed by the shared link, taking into account enterprise and user settings. public let effectivePermission: String? /// Whether the shared link has a password set. public let isPasswordEnabled: Bool? /// The date-time that this link will become disabled. This field can only be set by users with paid accounts. public let unsharedAt: Date? /// The number of times the item has been downloaded. public let downloadCount: Int? /// The number of times the item has been previewed. public let previewCount: Int? /// The access level specified when the shared link was created. public let access: SharedLinkAccess? /// Permissions for download and preview of the item. public let permissions: Permissions? /// Initializer. /// /// - Parameter json: JSON dictionary. /// - Throws: Decoding error. public required init(json: [String: Any]) throws { rawData = json url = try BoxJSONDecoder.optionalDecodeURL(json: json, forKey: "url") downloadURL = try BoxJSONDecoder.optionalDecodeURL(json: json, forKey: "download_url") vanityURL = try BoxJSONDecoder.optionalDecodeURL(json: json, forKey: "vanity_url") vanityName = try BoxJSONDecoder.optionalDecode(json: json, forKey: "vanity_name") effectiveAccess = try BoxJSONDecoder.optionalDecode(json: json, forKey: "effective_access") effectivePermission = try BoxJSONDecoder.optionalDecode(json: json, forKey: "effective_permission") isPasswordEnabled = try BoxJSONDecoder.optionalDecode(json: json, forKey: "is_password_enabled") unsharedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "unshared_at") downloadCount = try BoxJSONDecoder.optionalDecode(json: json, forKey: "download_count") previewCount = try BoxJSONDecoder.optionalDecode(json: json, forKey: "preview_count") access = try BoxJSONDecoder.optionalDecodeEnum(json: json, forKey: "access") permissions = try BoxJSONDecoder.optionalDecode(json: json, forKey: "permissions") } }
apache-2.0
00245394c74b441b565bed6654ffd027
44.416667
129
0.680122
4.622997
false
false
false
false
pisces/SimpleLayout
Example/SimpleLayout/ChainExampleViewController.swift
1
1505
// // ChainExampleViewController.swift // SimpleLayout // // Created by pisces on 02/01/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import SimpleLayout_Swift class ChainExampleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = .bottom let subview1 = label(backgroundColor: .red, text: "subview1") let subview2 = label(backgroundColor: .purple, text: "subview2") let subview3 = label(backgroundColor: .blue, text: "subview3") view.addSubview(subview1) view.addSubview(subview2) view.addSubview(subview3) subview1.layout .leading() .top() .trailing() .height(fixed: 150) subview2.layout .leading(by: subview1) .top(by: subview1, attribute: .bottom) .width(fixed: view.width/2) .bottom(by: view._safeAreaLayoutGuide) subview3.layout .leading(by: subview2, attribute: .trailing) .top(by: subview2) .trailing(by: subview1) .bottom(by: subview2) } private func label(backgroundColor: UIColor, text: String) -> UILabel { let label = UILabel() label.backgroundColor = backgroundColor label.text = text label.textAlignment = .center label.textColor = .white return label } }
mit
5237ac066f16ac5237e0c944b24caaa9
27.377358
75
0.589096
4.502994
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Messages/ZMAssetClientMessageTests+Ephemeral.swift
1
18450
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @testable import WireDataModel class ZMAssetClientMessageTests_Ephemeral: BaseZMAssetClientMessageTests { override func setUp() { super.setUp() deletionTimer?.isTesting = true syncMOC.performGroupedBlockAndWait { self.obfuscationTimer?.isTesting = true } } override func tearDown() { syncMOC.performGroupedBlockAndWait { self.syncMOC.zm_teardownMessageObfuscationTimer() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) uiMOC.performGroupedBlockAndWait { self.uiMOC.zm_teardownMessageDeletionTimer() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) super.tearDown() } var obfuscationTimer: ZMMessageDestructionTimer? { return syncMOC.zm_messageObfuscationTimer } var deletionTimer: ZMMessageDestructionTimer? { return uiMOC.zm_messageDeletionTimer } } // MARK: Sending extension ZMAssetClientMessageTests_Ephemeral { func testThatItInsertsAnEphemeralMessageForAssets() { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) let fileMetadata = createFileMetadata() // when let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage // then guard case .ephemeral? = message.underlyingMessage!.content else { return XCTFail() } XCTAssertTrue(message.underlyingMessage!.hasAsset) XCTAssertTrue(message.underlyingMessage!.ephemeral.hasAsset) XCTAssertEqual(message.underlyingMessage!.ephemeral.expireAfterMillis, Int64(10*1000)) } func assetWithImage() -> WireProtos.Asset { let original = WireProtos.Asset.Original(withSize: 1000, mimeType: "image", name: "foo") let remoteData = WireProtos.Asset.RemoteData(withOTRKey: Data(), sha256: Data(), assetId: "id", assetToken: "token") let imageMetaData = WireProtos.Asset.ImageMetaData(width: 30, height: 40) let preview = WireProtos.Asset.Preview(size: 2000, mimeType: "video", remoteData: remoteData, imageMetadata: imageMetaData) let asset = WireProtos.Asset(original: original, preview: preview) return asset } func thumbnailEvent(for message: ZMAssetClientMessage) -> ZMUpdateEvent { let data = try? message.underlyingMessage?.serializedData().base64String() let payload: [String: Any] = [ "id": UUID.create(), "conversation": conversation.remoteIdentifier!.transportString(), "from": selfUser.remoteIdentifier!.transportString(), "time": Date().transportString(), "data": [ "id": "fooooo", "text": data ?? "" ], "type": "conversation.otr-message-add" ] return ZMUpdateEvent(fromEventStreamPayload: payload as ZMTransportData, uuid: UUID())! } func testThatWhenUpdatingTheThumbnailAssetIDWeReplaceAnEphemeralMessageWithAnEphemeral() { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) let fileMetadata = createFileMetadata() // when let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage let event = thumbnailEvent(for: message) message.update(with: event, initialUpdate: true) // then guard case .ephemeral? = message.underlyingMessage!.content else { return XCTFail() } XCTAssertTrue(message.underlyingMessage!.ephemeral.hasAsset) XCTAssertEqual(message.underlyingMessage!.ephemeral.expireAfterMillis, Int64(10*1000)) } func testThatItStartsTheTimerForMultipartMessagesWhenTheAssetIsUploaded() { self.syncMOC.performGroupedBlockAndWait { // given self.syncConversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) let fileMetadata = self.createFileMetadata() let message = try! self.syncConversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage // when message.update(withPostPayload: [:], updatedKeys: Set([#keyPath(ZMAssetClientMessage.transferState)])) // then XCTAssertEqual(self.obfuscationTimer?.runningTimersCount, 1) XCTAssertEqual(self.obfuscationTimer?.isTimerRunning(for: message), true) } } func testThatItExtendsTheObfuscationTimer() { var oldTimer: ZMTimer? var message: ZMAssetClientMessage! // given self.syncMOC.performGroupedBlockAndWait { // set timeout self.syncConversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) // send file let fileMetadata = self.createFileMetadata() message = try! self.syncConversation.appendFile(with: fileMetadata) as? ZMAssetClientMessage message.update(withPostPayload: [:], updatedKeys: Set([#keyPath(ZMAssetClientMessage.transferState)])) // check a timer was started oldTimer = self.obfuscationTimer?.timer(for: message) XCTAssertNotNil(oldTimer) } // when timer extended by 5 seconds self.syncMOC.performGroupedBlockAndWait { message.extendDestructionTimer(to: Date(timeIntervalSinceNow: 15)) } // then a new timer was created self.syncMOC.performGroupedBlockAndWait { let newTimer = self.obfuscationTimer?.timer(for: message) XCTAssertNotEqual(oldTimer, newTimer) } } func testThatItDoesNotExtendTheObfuscationTimerWhenNewDateIsEarlier() { var oldTimer: ZMTimer? var message: ZMAssetClientMessage! // given self.syncMOC.performGroupedBlockAndWait { // set timeout self.syncConversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) // send file let fileMetadata = self.createFileMetadata() message = try! self.syncConversation.appendFile(with: fileMetadata) as? ZMAssetClientMessage message.update(withPostPayload: [:], updatedKeys: Set([#keyPath(ZMAssetClientMessage.transferState)])) // check a timer was started oldTimer = self.obfuscationTimer?.timer(for: message) XCTAssertNotNil(oldTimer) } // when timer "extended" 5 seconds earlier self.syncMOC.performGroupedBlockAndWait { message.extendDestructionTimer(to: Date(timeIntervalSinceNow: 5)) } // then no new timer created self.syncMOC.performGroupedBlockAndWait { let newTimer = self.obfuscationTimer?.timer(for: message) XCTAssertEqual(oldTimer, newTimer) } } } // MARK: Receiving extension ZMAssetClientMessageTests_Ephemeral { func testThatItStartsATimerForImageAssetMessagesIfTheMessageIsAMessageOfTheOtherUser() throws { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) conversation.lastReadServerTimeStamp = Date() let sender = ZMUser.insertNewObject(in: uiMOC) sender.remoteIdentifier = UUID.create() let fileMetadata = self.createFileMetadata() let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage message.sender = sender try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: Data(), sha256: Data()), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasUploaded) // when XCTAssertTrue(message.startSelfDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 1) XCTAssertEqual(self.deletionTimer?.isTimerRunning(for: message), true) } func testThatItStartsATimerIfTheMessageIsAMessageOfTheOtherUser() throws { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) conversation.lastReadServerTimeStamp = Date() let sender = ZMUser.insertNewObject(in: uiMOC) sender.remoteIdentifier = UUID.create() let nonce = UUID() let message = ZMAssetClientMessage(nonce: nonce, managedObjectContext: uiMOC) message.sender = sender message.visibleInConversation = conversation let imageData = verySmallJPEGData() let assetMessage = GenericMessage(content: WireProtos.Asset(imageSize: .zero, mimeType: "", size: UInt64(imageData.count)), nonce: nonce, expiresAfter: .tenSeconds) try message.setUnderlyingMessage(assetMessage) let uploaded = GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: .randomEncryptionKey(), sha256: .zmRandomSHA256Key()), nonce: message.nonce!, expiresAfter: conversation.activeMessageDestructionTimeoutValue) try message.setUnderlyingMessage(uploaded) // when XCTAssertTrue(message.startSelfDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 1) XCTAssertEqual(self.deletionTimer?.isTimerRunning(for: message), true) } func appendPreviewImageMessage() -> ZMAssetClientMessage { let imageData = verySmallJPEGData() let message = ZMAssetClientMessage(nonce: UUID(), managedObjectContext: uiMOC) conversation.append(message) let imageSize = ZMImagePreprocessor.sizeOfPrerotatedImage(with: imageData) let properties = ZMIImageProperties(size: imageSize, length: UInt(imageData.count), mimeType: "image/jpeg") let keys = ZMImageAssetEncryptionKeys(otrKey: Data.randomEncryptionKey(), macKey: Data.zmRandomSHA256Key(), mac: Data.zmRandomSHA256Key()) let imageMessage = GenericMessage(content: ImageAsset(mediumProperties: properties, processedProperties: properties, encryptionKeys: keys, format: .preview)) do { try message.setUnderlyingMessage(imageMessage) } catch { XCTFail() } return message } func testThatItDoesNotStartsATimerIfTheMessageIsAMessageOfTheOtherUser_NoMediumImage() { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) conversation.lastReadServerTimeStamp = Date() let sender = ZMUser.insertNewObject(in: uiMOC) sender.remoteIdentifier = UUID.create() let message = appendPreviewImageMessage() message.sender = sender // when XCTAssertFalse(message.startSelfDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 0) XCTAssertEqual(self.deletionTimer?.isTimerRunning(for: message), false) } func testThatItDoesNotStartATimerIfTheMessageIsAMessageOfTheOtherUser_NotUploadedYet() { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) conversation.lastReadServerTimeStamp = Date() let sender = ZMUser.insertNewObject(in: uiMOC) sender.remoteIdentifier = UUID.create() let fileMetadata = self.createFileMetadata() let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage message.sender = sender XCTAssertFalse(message.underlyingMessage!.assetData!.hasUploaded) // when XCTAssertFalse(message.startSelfDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 0) XCTAssertEqual(self.deletionTimer?.isTimerRunning(for: message), false) } func testThatItStartsATimerIfTheMessageIsAMessageOfTheOtherUser_UploadCancelled() throws { // given conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) conversation.lastReadServerTimeStamp = Date() let sender = ZMUser.insertNewObject(in: uiMOC) sender.remoteIdentifier = UUID.create() let fileMetadata = self.createFileMetadata() let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage message.sender = sender try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withNotUploaded: .cancelled), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasNotUploaded) // when XCTAssertTrue(message.startSelfDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 1) XCTAssertEqual(self.deletionTimer?.isTimerRunning(for: message), true) } func testThatItDoesNotStartATimerForAMessageOfTheSelfuser() throws { // given conversation.setMessageDestructionTimeoutValue(.custom(0.1), for: .selfUser) let fileMetadata = self.createFileMetadata() let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: Data(), sha256: Data()), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasUploaded) // when XCTAssertFalse(message.startDestructionIfNeeded()) // then XCTAssertEqual(self.deletionTimer?.runningTimersCount, 0) } func testThatItCreatesADeleteForAllMessageWhenTheTimerFires() throws { // given conversation.setMessageDestructionTimeoutValue(.custom(0.1), for: .selfUser) let fileMetadata = self.createFileMetadata() let message = try! conversation.appendFile(with: fileMetadata) as! ZMAssetClientMessage conversation.conversationType = .oneOnOne message.sender = ZMUser.insertNewObject(in: uiMOC) message.sender?.remoteIdentifier = UUID.create() try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: Data(), sha256: Data()), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasUploaded) // when XCTAssertTrue(message.startDestructionIfNeeded()) XCTAssertEqual(self.deletionTimer?.runningTimersCount, 1) spinMainQueue(withTimeout: 0.5) // then guard let deleteMessage = conversation.hiddenMessages.first(where: { $0 is ZMClientMessage }) as? ZMClientMessage else { return XCTFail()} guard let genericMessage = deleteMessage.underlyingMessage, case .deleted? = genericMessage.content else { return XCTFail() } XCTAssertNotEqual(deleteMessage, message) XCTAssertNotNil(message.sender) XCTAssertNil(message.underlyingMessage) XCTAssertEqual(message.dataSet.count, 0) XCTAssertNil(message.destructionDate) } func testThatItExtendsTheDeletionTimer() throws { var oldTimer: ZMTimer? var message: ZMAssetClientMessage! // given self.conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) // send file let fileMetadata = self.createFileMetadata() message = try! self.conversation.appendFile(with: fileMetadata) as? ZMAssetClientMessage message.sender = ZMUser.insertNewObject(in: self.uiMOC) message.sender?.remoteIdentifier = UUID.create() try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: Data(), sha256: Data()), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasUploaded) // check a timer was started XCTAssertTrue(message.startDestructionIfNeeded()) oldTimer = self.deletionTimer?.timer(for: message) XCTAssertNotNil(oldTimer) // when timer extended by 5 seconds message.extendDestructionTimer(to: Date(timeIntervalSinceNow: 15)) // force a wait so timer map is updated _ = wait(withTimeout: 0.5, verificationBlock: { return false }) // then a new timer was created let newTimer = self.deletionTimer?.timer(for: message) XCTAssertNotEqual(oldTimer, newTimer) } func testThatItDoesNotExtendTheDeletionTimerWhenNewDateIsEarlier() throws { var oldTimer: ZMTimer? var message: ZMAssetClientMessage! // given self.conversation.setMessageDestructionTimeoutValue(.tenSeconds, for: .selfUser) // send file let fileMetadata = self.createFileMetadata() message = try! self.conversation.appendFile(with: fileMetadata) as? ZMAssetClientMessage message.sender = ZMUser.insertNewObject(in: self.uiMOC) message.sender?.remoteIdentifier = UUID.create() try message.setUnderlyingMessage(GenericMessage(content: WireProtos.Asset(withUploadedOTRKey: Data(), sha256: Data()), nonce: message.nonce!)) XCTAssertTrue(message.underlyingMessage!.assetData!.hasUploaded) // check a timer was started XCTAssertTrue(message.startDestructionIfNeeded()) oldTimer = self.deletionTimer?.timer(for: message) XCTAssertNotNil(oldTimer) // when timer "extended" by 5 seconds earlier message.extendDestructionTimer(to: Date(timeIntervalSinceNow: 5)) // force a wait so timer map is updated _ = wait(withTimeout: 0.5, verificationBlock: { return false }) // then a new timer was created let newTimer = self.deletionTimer?.timer(for: message) XCTAssertEqual(oldTimer, newTimer) } }
gpl-3.0
f3e6897c6f2b7d006fed19d4f3fadc49
40.742081
226
0.69122
5.03823
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/View/DongtaiDetailHeaderView.swift
1
5861
// // DongtaiDetailHeaderView.swift // News // // Created by 杨蒙 on 2017/12/23. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit import IBAnimatable class DongtaiDetailHeaderView: UIView, NibLoadable { /// 点击了 点赞按钮 var didSelectDiggButton: ((_ dongtai: UserDetailDongtai)->())? /// 点击了 用户名 var didSelectDongtaiUserName: ((_ uid: Int)->())? /// 点击了 话题 var didSelectDongtaiTopic: ((_ cid: Int)->())? /// 点击了覆盖的按钮 var didSelectCoverButton: ((_ userId: Int)->())? var dongtai = UserDetailDongtai() { didSet { theme_backgroundColor = "colors.cellBackgroundColor" avatarButton.kf.setImage(with: URL(string: dongtai.user.avatar_url), for: .normal) nameLabel.text = dongtai.user.screen_name timeLabel.text = "· " + dongtai.createTime descriptionLabel.text = dongtai.user.verified_content readCountLabel.text = dongtai.readCount + "阅读 ·" + dongtai.brand_info + " " + dongtai.position.position commentCountLabel.text = dongtai.commentCount + "评论" zanButton.setTitle(dongtai.diggCount, for: .normal) // 显示 emoji contentLabel.attributedText = dongtai.attributedContent // 点击了用户 contentLabel.userTapped = { [weak self] (userName, range) in for userContent in self!.dongtai.userContents! { if userName.contains(userContent.name) { self!.didSelectDongtaiUserName?(Int(userContent.uid)!) } } } // 点击了话题 contentLabel.topicTapped = {[weak self] (topic, range) in for topicContent in self!.dongtai.topicContents! { if topic.contains(topicContent.name) { self!.didSelectDongtaiTopic?(Int(topicContent.uid)!) } } } /// 防止因为 cell 重用机制,导致数据错乱现象出现 if middleView.contains(postVideoOrArticleView) { postVideoOrArticleView.removeFromSuperview() } if middleView.contains(collectionView) { collectionView.removeFromSuperview() } if middleView.contains(originThreadView) { originThreadView.removeFromSuperview() } switch dongtai.item_type { case .postVideoOrArticle, .postVideo, .answerQuestion, .proposeQuestion, .forwardArticle, .postContentAndVideo: // 发布了文章或者视频 postVideoOrArticleView.frame = CGRect(x: 15, y: 0, width: screenWidth - 30, height: middleView.height) postVideoOrArticleView.group = dongtai.group.title == "" ? dongtai.origin_group : dongtai.group middleView.addSubview(postVideoOrArticleView) case .postContent, .postSmallVideo: // 发布了文字内容 collectionView.isDongtaiDetail = true collectionView.frame = CGRect(x: 15, y: 0, width: dongtai.collectionViewW, height: dongtai.detailConllectionViewH) collectionView.isPostSmallVideo = (dongtai.item_type == .postSmallVideo) collectionView.thumbImages = dongtai.thumb_image_list collectionView.largeImages = dongtai.large_image_list middleView.addSubview(collectionView) case .commentOrQuoteContent, .commentOrQuoteOthers: // 引用或评论 originThreadView.originthread = dongtai.origin_thread originThreadView.originthread.isDongtaiDetail = true originThreadView.frame = CGRect(x: 0, y: 0, width: screenWidth - 30, height: dongtai.origin_thread.detailHeight) middleView.addSubview(originThreadView) } } } /// 懒加载 评论或引用 private lazy var originThreadView = DongtaiOriginThreadView.loadViewFromNib() /// 懒加载 发布视频或者文章 private lazy var postVideoOrArticleView = PostVideoOrArticleView.loadViewFromNib() /// 懒加载 collectionView private lazy var collectionView = DongtaiCollectionView.loadViewFromNib() override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.cellBackgroundColor" separatorView.theme_backgroundColor = "colors.separatorViewColor" nameLabel.theme_textColor = "colors.black" timeLabel.theme_textColor = "colors.grayColor150" descriptionLabel.theme_textColor = "colors.grayColor150" readCountLabel.theme_textColor = "colors.grayColor150" contentLabel.theme_textColor = "colors.black" } /// 头像 @IBOutlet weak var avatarButton: AnimatableButton! /// V 图标 @IBOutlet weak var vImageView: UIImageView! /// 用户名 @IBOutlet weak var nameLabel: UILabel! /// 创建时间 @IBOutlet weak var timeLabel: UILabel! /// 描述 @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var separatorView: UIView! /// 阅读数量 @IBOutlet weak var readCountLabel: UILabel! /// 中间的 view @IBOutlet weak var middleView: UIView! /// 内容 @IBOutlet weak var contentLabel: RichLabel! /// 评论数量 @IBOutlet weak var commentCountLabel: UILabel! /// 赞 @IBOutlet weak var zanButton: UIButton! /// 覆盖的按钮点击 @IBAction func coverButtonClicked() { didSelectCoverButton?(dongtai.user.user_id) } /// 点赞按钮点击 @IBAction func diggButtonClicked(_ sender: UIButton) { didSelectDiggButton?(dongtai) } override func layoutSubviews() { super.layoutSubviews() height = dongtai.detailHeaderHeight } }
mit
f5ef22a1f08a58a05c422e76661ad28a
41.473282
136
0.635155
4.813149
false
false
false
false
yoichitgy/SwinjectPropertyLoader
Tests/Resolver+PropertiesSpec.swift
1
10535
// // Resolver+PropertiesSpec.swift // SwinjectPropertyLoader // // Created by Yoichi Tagaya on 5/8/16. // Copyright © 2016 Swinject Contributors. All rights reserved. // import Foundation import Quick import Nimble import Swinject import SwinjectPropertyLoader class Resolver_PropertiesSpec: QuickSpec { override func spec() { var container: Container! beforeEach { container = Container() } describe("JSON properties") { it("can load properties from a single loader") { let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") try! container.applyPropertyLoader(loader) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! properties.optionalStringValue = r.property("test.string") properties.implicitStringValue = r.property("test.string") properties.intValue = r.property("test.int")! properties.optionalIntValue = r.property("test.int") properties.implicitIntValue = r.property("test.int") properties.doubleValue = r.property("test.double")! properties.optionalDoubleValue = r.property("test.double") properties.implicitDoubleValue = r.property("test.double") properties.arrayValue = r.property("test.array")! properties.optionalArrayValue = r.property("test.array") properties.implicitArrayValue = r.property("test.array") properties.dictValue = r.property("test.dict")! properties.optionalDictValue = r.property("test.dict") properties.implicitDictValue = r.property("test.dict") properties.boolValue = r.property("test.bool")! properties.optionalBoolValue = r.property("test.bool") properties.implicitBoolValue = r.property("test.bool") return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "first" expect(properties.optionalStringValue) == "first" expect(properties.implicitStringValue) == "first" expect(properties.intValue) == 100 expect(properties.optionalIntValue) == 100 expect(properties.implicitIntValue) == 100 expect(properties.doubleValue) == 30.50 expect(properties.optionalDoubleValue) == 30.50 expect(properties.implicitDoubleValue) == 30.50 expect(properties.arrayValue.count) == 2 expect(properties.arrayValue[0]) == "item1" expect(properties.arrayValue[1]) == "item2" expect(properties.optionalArrayValue!.count) == 2 expect(properties.optionalArrayValue![0]) == "item1" expect(properties.optionalArrayValue![1]) == "item2" expect(properties.implicitArrayValue.count) == 2 expect(properties.implicitArrayValue![0]) == "item1" expect(properties.implicitArrayValue![1]) == "item2" expect(properties.dictValue.count) == 2 expect(properties.dictValue["key1"]) == "item1" expect(properties.dictValue["key2"]) == "item2" expect(properties.optionalDictValue!.count) == 2 expect(properties.optionalDictValue!["key1"]) == "item1" expect(properties.optionalDictValue!["key2"]) == "item2" expect(properties.implicitDictValue.count) == 2 expect(properties.implicitDictValue!["key1"]) == "item1" expect(properties.implicitDictValue!["key2"]) == "item2" expect(properties.boolValue) == true expect(properties.optionalBoolValue) == true expect(properties.implicitBoolValue) == true } it("can load properties from multiple loader") { let loader = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") let loader2 = JsonPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second") try! container.applyPropertyLoader(loader) try! container.applyPropertyLoader(loader2) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! // from loader2 properties.intValue = r.property("test.int")! // from loader return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "second" expect(properties.intValue) == 100 } } describe("Plist properties") { it("can load properties from a single loader") { let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") try! container.applyPropertyLoader(loader) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! properties.optionalStringValue = r.property("test.string") properties.implicitStringValue = r.property("test.string") properties.intValue = r.property("test.int")! properties.optionalIntValue = r.property("test.int") properties.implicitIntValue = r.property("test.int") properties.doubleValue = r.property("test.double")! properties.optionalDoubleValue = r.property("test.double") properties.implicitDoubleValue = r.property("test.double") properties.arrayValue = r.property("test.array")! properties.optionalArrayValue = r.property("test.array") properties.implicitArrayValue = r.property("test.array") properties.dictValue = r.property("test.dict")! properties.optionalDictValue = r.property("test.dict") properties.implicitDictValue = r.property("test.dict") properties.boolValue = r.property("test.bool")! properties.optionalBoolValue = r.property("test.bool") properties.implicitBoolValue = r.property("test.bool") return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "first" expect(properties.optionalStringValue) == "first" expect(properties.implicitStringValue) == "first" expect(properties.intValue) == 100 expect(properties.optionalIntValue) == 100 expect(properties.implicitIntValue) == 100 expect(properties.doubleValue) == 30.50 expect(properties.optionalDoubleValue) == 30.50 expect(properties.implicitDoubleValue) == 30.50 expect(properties.arrayValue.count) == 2 expect(properties.arrayValue[0]) == "item1" expect(properties.arrayValue[1]) == "item2" expect(properties.optionalArrayValue!.count) == 2 expect(properties.optionalArrayValue![0]) == "item1" expect(properties.optionalArrayValue![1]) == "item2" expect(properties.implicitArrayValue.count) == 2 expect(properties.implicitArrayValue![0]) == "item1" expect(properties.implicitArrayValue![1]) == "item2" expect(properties.dictValue.count) == 2 expect(properties.dictValue["key1"]) == "item1" expect(properties.dictValue["key2"]) == "item2" expect(properties.optionalDictValue!.count) == 2 expect(properties.optionalDictValue!["key1"]) == "item1" expect(properties.optionalDictValue!["key2"]) == "item2" expect(properties.implicitDictValue.count) == 2 expect(properties.implicitDictValue!["key1"]) == "item1" expect(properties.implicitDictValue!["key2"]) == "item2" expect(properties.boolValue) == true expect(properties.optionalBoolValue) == true expect(properties.implicitBoolValue) == true } it("can load properties from multiple loader") { let loader = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "first") let loader2 = PlistPropertyLoader(bundle: Bundle(for: type(of: self).self), name: "second") try! container.applyPropertyLoader(loader) try! container.applyPropertyLoader(loader2) container.register(Properties.self) { r in let properties = Properties() properties.stringValue = r.property("test.string")! // from loader2 properties.intValue = r.property("test.int")! // from loader return properties } let properties = container.resolve(Properties.self)! expect(properties.stringValue) == "second" expect(properties.intValue) == 100 } } } }
mit
45f22aa315bbb669829c73bee7e44cde
48.924171
107
0.53484
5.585366
false
true
false
false
firebase/quickstart-ios
abtesting/LegacyABTestingQuickstart/ABTestingExample/ViewController.swift
1
5843
// // Copyright (c) Google 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 FirebaseRemoteConfig import FirebaseInstallations import UIKit enum ColorScheme { case light case dark } extension RemoteConfigFetchStatus { var debugDescription: String { switch self { case .failure: return "failure" case .noFetchYet: return "pending" case .success: return "success" case .throttled: return "throttled" } } } class ViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! var colorScheme: ColorScheme = .light { didSet { switchToColorScheme(colorScheme) } } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.tableFooterView = UIView() #if DEBUG NotificationCenter.default.addObserver(self, selector: #selector(printInstallationsID), name: .InstallationIDDidChange, object: nil) #endif } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) RemoteConfig.remoteConfig().fetch(withExpirationDuration: 0) { status, error in if let error = error { print("Error fetching config: \(error)") } print("Config fetch completed with status: \(status.debugDescription)") self.setAppearance() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setAppearance() } func setAppearance() { RemoteConfig.remoteConfig().activate { activated, error in let configValue = RemoteConfig.remoteConfig()["color_scheme"] print("Config value: \(configValue.stringValue ?? "null")") DispatchQueue.main.async { if configValue.stringValue == "dark" { self.colorScheme = .dark } else { self.colorScheme = .light } } } } @objc func printInstallationsID() { #if DEBUG Installations.installations().authTokenForcingRefresh(true) { token, error in if let error = error { print("Error fetching token: \(error)") return } guard let token = token else { return } print("Installation auth token: \(token.authToken)") } Installations.installations().installationID { identifier, error in if let error = error { print("Error fetching installations ID: \(error)") } else if let identifier = identifier { print("Remote installations ID: \(identifier)") } } #endif } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - UI Colors func switchToColorScheme(_ scheme: ColorScheme) { switch scheme { case .light: navigationController?.navigationBar.barTintColor = ViewController.lightColors.primary navigationController?.navigationBar.barStyle = .default navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.black, ] tableView.separatorColor = .gray tableView.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.94, alpha: 1) case .dark: navigationController?.navigationBar.barTintColor = ViewController.darkColors.primary navigationController?.navigationBar.barStyle = .black navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.white, ] tableView.separatorColor = .lightGray tableView.backgroundColor = ViewController.darkColors.secondary } tableView.reloadData() } static let darkColors = ( primary: UIColor(red: 0x61 / 0xFF, green: 0x61 / 0xFF, blue: 0x61 / 0xFF, alpha: 1), secondary: UIColor(red: 0x42 / 0xFF, green: 0x42 / 0xFF, blue: 0x42 / 0xFF, alpha: 1) ) static let lightColors = ( primary: UIColor(red: 0xFF / 0xFF, green: 0xC1 / 0xFF, blue: 0x07 / 0xFF, alpha: 1), secondary: UIColor(red: 0xFF / 0xFF, green: 0xC1 / 0xFF, blue: 0x07 / 0xFF, alpha: 1) ) // MARK: - UITableViewDataSource let data = [ ("Getting Started with Firebase", "An Introduction to Firebase"), ("Google Firestore", "Powerful Querying and Automatic Scaling"), ("Analytics", "Simple App Insights"), ("Remote Config", "Parameterize App Behavior"), ] func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "GenericSubtitleCell", for: indexPath) cell.textLabel?.text = data[indexPath.row].0 cell.detailTextLabel?.text = data[indexPath.row].1 cell.detailTextLabel?.alpha = 0.8 switch colorScheme { case .light: cell.backgroundColor = UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: 1) cell.textLabel?.textColor = .black cell.detailTextLabel?.textColor = .black case .dark: cell.backgroundColor = ViewController.darkColors.secondary cell.textLabel?.textColor = .white cell.detailTextLabel?.textColor = .white } return cell } }
apache-2.0
0e5cf0cc1dceb1fc5bbf65d12569b495
30.583784
99
0.663871
4.564844
false
true
false
false
WickedColdfront/Slide-iOS
Pods/reddift/reddift/Model/Paginator.swift
1
1628
// // Paginator.swift // reddift // // Created by sonson on 2015/04/14. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Paginator object for paiging listing object. */ public struct Paginator { let after: String let before: String let modhash: String public init() { self.after = "" self.before = "" self.modhash = "" } public func hasMore() -> Bool { return !(after == nil || after.isEmpty) } public init(after: String, before: String, modhash: String) { self.after = after self.before = before self.modhash = modhash } public var isVacant: Bool { if (!after.isEmpty) || (!before.isEmpty) { return false } return true } /** Generate dictionary to add query parameters to URL. If paginator is vacant, returns vacant dictionary as [String:String]. - returns: Dictionary object for paging. */ public var parameterDictionary: [String:String] { get { var dict: [String:String] = [:] if after.characters.count > 0 { dict["after"] = after } if before.characters.count > 0 { dict["before"] = before } return dict } } public func dictionaryByAdding(parameters dict: [String:String]) -> [String:String] { var newDict = dict if after.characters.count > 0 { newDict["after"] = after } if before.characters.count > 0 { newDict["before"] = before } return newDict } }
apache-2.0
b2072b1f3d447a511625abb9fb43b01f
21.901408
89
0.559656
4.147959
false
false
false
false
viitech/VIIFirebaseNotificationsHandler
VIIFirebaseNotificationsHandler.swift
1
7003
// // VIIFirebaseNotificationsHandler.swift // VII Tech Solutions // // Created by VII Tech Solutions on 8/17/17. // Copyright © 2017 VII Tech Solutions. All rights reserved. // import Foundation import Firebase import FirebaseMessaging import UserNotifications // Type Alias typealias notificationAction = ((_ application: UIApplication, _ userInfo: [String: AnyObject], _ completionHandler: @escaping (UIBackgroundFetchResult) -> Void)->Void) class VIIFirebaseNotificationsHandler { // Variables static var topics: [String] = [] static var notificationTypes: [String: notificationAction] = [:] private static var badgeCount = 0 { didSet { if (badgeCount == 0) { let ln = UILocalNotification() ln.applicationIconBadgeNumber = -1 UIApplication.shared.presentLocalNotificationNow(ln) } else { UIApplication.shared.applicationIconBadgeNumber = badgeCount } } } static let shared = VIIFirebaseNotificationsHandler() //This prevents others from using the default '()' initializer for this class. private init() { } @objc private func connectToFCM() { // Won't connect unless there is a token if (UIApplication.shared.isRegisteredForRemoteNotifications) { if let _ = FIRInstanceID.instanceID().token() { // Disconnect previous FCM connection if it exists. FIRMessaging.messaging().disconnect() FIRMessaging.messaging().connect(completion: { (error) in if error != nil { } else { self.firebaseSubscription() } }) } } } internal func firebaseSubscription() { for topic in VIIFirebaseNotificationsHandler.topics { print("SUBSCRIBING TO = \(topic)") FIRMessaging.messaging().subscribe(toTopic: "/topics/\(topic)") } } internal func firebaseUnsubscription() { for topic in VIIFirebaseNotificationsHandler.topics { print("UNSUBSCRIBING FROM = \(topic)") FIRMessaging.messaging().unsubscribe(fromTopic: "/topics/\(topic)") } } internal func refreshFirebaseSubscribing() { firebaseUnsubscription() firebaseSubscription() } @objc private func disconnectFromFCM() { if (UIApplication.shared.isRegisteredForRemoteNotifications) { // Unsubscribe from registered topics firebaseUnsubscription() // Disconnnect FIRMessaging.messaging().disconnect() } } static func setBadgeCountExplicitly(count: Int) { badgeCount = count } static func incrementBadgeCount() { badgeCount += 1 } static func setBadgeCountWithFunction(function: ()->Int) { badgeCount = function() // Returns Int } static func didFinishLaunchingWithOptions(application: UIApplication, isLoggedIn: Bool) { // Connect or Disconnect to FCM // Check if logged in and registered for notifications if (isLoggedIn) { // Connect to Firebase VIIFirebaseNotificationsHandler.shared.connectToFCM() } else if (!isLoggedIn) { // If not registered for notifications or logged out VIIFirebaseNotificationsHandler.shared.disconnectFromFCM() } } static func didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: Data) { FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox) FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .prod) // Connect to FCM. NotificationCenter.default.addObserver(self, selector: #selector(connectToFCM), name: NSNotification.Name(rawValue: "firInstanceIDTokenRefresh"), object: nil) VIIFirebaseNotificationsHandler.shared.connectToFCM() } static func didReceiveRemoteNotificationWithCompletion(application: UIApplication, userInfo: [String : AnyObject], completionHandler: @escaping (UIBackgroundFetchResult) -> Void = {_ in}, isLoggedIn: Bool) { FIRMessaging.messaging().appDidReceiveMessage(userInfo) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReceivedNotification"), object:userInfo) VIIFirebaseNotificationsHandler.handleNotifications(application: application, userInfo: userInfo, completionHandler: completionHandler, isLoggedIn: isLoggedIn) } static func didReceiveRemoteNotification(application: UIApplication, userInfo: [String : AnyObject], isLoggedIn: Bool) { FIRMessaging.messaging().appDidReceiveMessage(userInfo) if (application.applicationState != UIApplicationState.active) { VIIFirebaseNotificationsHandler.handleNotifications(application: application, userInfo: userInfo, isLoggedIn: isLoggedIn) } } static func setupNotifications() { // Override point for customization after application launch. if #available(iOS 10.0, *) { let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in }) // For iOS 10 data message (sent via FCM) FIRMessaging.messaging().remoteMessageDelegate = appDelegate UNUserNotificationCenter.current().delegate = appDelegate } else { let userNotificationTypes: UIUserNotificationType = [.alert, .badge, .sound] let settings = UIUserNotificationSettings(types: userNotificationTypes, categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) } if (!UIApplication.shared.isRegisteredForRemoteNotifications) { UIApplication.shared.registerForRemoteNotifications() } else { NotificationCenter.default.addObserver(self, selector: #selector(connectToFCM), name: NSNotification.Name(rawValue: "firInstanceIDTokenRefresh"), object: nil) VIIFirebaseNotificationsHandler.shared.connectToFCM() } } static func handleNotifications(application: UIApplication, userInfo: [String : AnyObject]?, completionHandler: @escaping (UIBackgroundFetchResult) -> Void = {_ in}, isLoggedIn: Bool) { if (!isLoggedIn) { return } if let userInfo = userInfo { let type = userInfo["type"] if let type = type as? String { for key in notificationTypes.keys { if (type.lowercased() == key.lowercased()) { notificationTypes[key]!(application, userInfo, completionHandler) } } } } } }
mit
6ccf05570b7224c561e30110f50fb9e5
39.947368
211
0.641388
5.583732
false
false
false
false
Sephiroth87/C-swifty4
C64/Files/SaveState.swift
1
1114
// // SaveState.swift // C64 // // Created by Fabio Ritrovato on 07/06/2016. // Copyright © 2016 orange in a day. All rights reserved. // public final class SaveState { private(set) public var data: [UInt8] private(set) internal var cpuState: CPUState private(set) internal var memoryState: C64MemoryState private(set) internal var cia1State: CIAState private(set) internal var cia2State: CIAState private(set) internal var vicState: VICState internal init(c64: C64) { cpuState = c64.cpu.state memoryState = c64.memory.state cia1State = c64.cia1.state cia2State = c64.cia2.state vicState = c64.vic.state let states: [BinaryConvertible] = [cpuState, memoryState, cia1State, cia2State, vicState] data = states.flatMap { $0.dump() } } public init(data: [UInt8]) { self.data = data let dump = BinaryDump(data: data) cpuState = dump.next() memoryState = dump.next() cia1State = dump.next() cia2State = dump.next() vicState = dump.next() } }
mit
4de59417459b0a6e86f91ceb794ba960
28.289474
97
0.627134
3.393293
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Discover/ViewModel/CourseViewModel.swift
1
912
// // CourseViewModel.swift // GYJTV // // Created by zcm_iOS on 2017/6/19. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class CourseViewModel { lazy var courseArray : [CourseModel] = [CourseModel]() func loadCourseData( _ complection : @escaping() -> ()){ NetworkTool.requestData(.get, URLString: kDiscoverScrollUrl) { (result : Any) in self.courseArray.removeAll() guard let resultDic = result as? [String : Any] else { return } guard let message = resultDic["message"] as? [String : Any] else { return } guard let banners = message["banners"] as? [[String : Any]] else { return } for dict in banners{ let model = CourseModel(dic: dict) self.courseArray.append(model) } complection() } } }
mit
491b2c4800cae13b6d106a2a409535e0
28.322581
88
0.557756
4.287736
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift
2
2021
import Foundation import WordPressShared /// This class renders a view with top and bottom separators, meant to be used as UITableView section /// header in NotificationsViewController. /// class NoteTableHeaderView: UIView { // MARK: - Public Properties var title: String? { set { // For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height! let unwrappedTitle = newValue?.localizedUppercase ?? String() let attributes = Style.sectionHeaderRegularStyle titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes) setNeedsLayout() } get { return titleLabel.text } } var separatorColor: UIColor? { set { contentView.bottomColor = newValue ?? UIColor.clear contentView.topColor = newValue ?? UIColor.clear } get { return contentView.bottomColor } } class func makeFromNib() -> NoteTableHeaderView { return Bundle.main.loadNibNamed("NoteTableHeaderView", owner: self, options: nil)?.first as! NoteTableHeaderView } // MARK: - Convenience Initializers override func awakeFromNib() { super.awakeFromNib() // Make sure the Outlets are loaded assert(contentView != nil) assert(imageView != nil) assert(titleLabel != nil) // Background + Separators backgroundColor = UIColor.clear contentView.backgroundColor = Style.sectionHeaderBackgroundColor contentView.bottomVisible = true contentView.topVisible = true } // MARK: - Aliases typealias Style = WPStyleGuide.Notifications // MARK: - Static Properties static let estimatedHeight = CGFloat(26) // MARK: - Outlets @IBOutlet fileprivate var contentView: SeparatorsView! @IBOutlet fileprivate var imageView: UIImageView! @IBOutlet fileprivate var titleLabel: UILabel! }
gpl-2.0
6bb57037c8667440bcebd817a68ff98a
30.578125
120
0.656111
5.582873
false
false
false
false
vamsikvk915/fusion
Fusion/Fusion/MapViewModel.swift
2
1928
// // MapViewModel.swift // Fusion // // Created by Abhishek Jaykrishna Khapare on 8/14/17. // Copyright © 2017 Mohammad Irteza Khan. All rights reserved. // import Foundation import Alamofire class MapViewModel{ var theatreDetails = [[String:String]]() func NetworkCall(urlString:String, compHandler:@escaping([[String:String]])->Void){ Alamofire.request(urlString).responseJSON{ response in let json = response.result.value as! [String:Any] print(json) if let query = json["query"] as? [String : Any]{ print(query) if let results = query["results"] as? [String : Any]{ let result = results["Result"] as! [[String : Any]] for theatre in result{ let title = theatre["Title"] as! String let address = theatre["Address"] as! String let city = theatre["City"] as! String let state = theatre["State"] as! String let phone = theatre["Phone"] as! String print(phone) let latitude = theatre["Latitude"] as! String let longitude = theatre["Longitude"] as! String let url = theatre["Url"] as! String let rating = theatre["Rating"] as! [String: Any] let averageRating = rating["AverageRating"] as! String self.theatreDetails.append(["Title":title,"Address":address,"City":city,"State":state,"Phone":phone,"Latitude":latitude,"Longitude":longitude,"Url":url,"AverageRating":averageRating]) } } } compHandler(self.theatreDetails) } } }
apache-2.0
bef798906ecb02e10439bf7bdb85300c
36.057692
203
0.501297
4.781638
false
false
false
false
MengQuietly/MQDouYuTV
MQDouYuTV/MQDouYuTV/Classes/Main/ViewModel/MQBaseAnchorViewModel.swift
1
1316
// // MQBaseAnchorViewModel.swift // MQDouYuTV // // Created by mengmeng on 17/1/16. // Copyright © 2017年 mengQuietly. All rights reserved. // MQBaseAnchorViewModel:推荐/娱乐 viewModel 基类 import UIKit class MQBaseAnchorViewModel { // MQAnchorGroupModel 数组(所有数据组) lazy var anchorGroupList: [MQAnchorGroupModel] = [MQAnchorGroupModel]() } extension MQBaseAnchorViewModel{ func getAnchorData(urlString: String, parameters:[String:Any]?=nil,finishCallBack:@escaping ()->()) { MQNetworkingTool.sendRequest(url: urlString, parameters:parameters, succeed: { [unowned self] (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") guard let resultDict = responseObject as? [String:NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return} for dict in dataArray { let groupModel = MQAnchorGroupModel(dict: dict) guard (groupModel.anchorList.count > 0) else {continue} self.anchorGroupList.append(groupModel) } finishCallBack() }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } } }
mit
d05ed3873f2772778f47fae537b7d77d
35.657143
132
0.641465
4.454861
false
false
false
false
TheIronYard--Orlando/iOS--CC--Swift
TailoredSwift.playground/Contents.swift
1
1941
/*: ![Remote Image](http://theironyard.com/images/home/tiy-logo.png) ## Intro to Swift Playgrounds ### Resources - [The Iron Yard](http://www.theironyard.com) - [Iron Yard Meetups](http://www.meetup.com/The-Iron-Yard-Orlando/) - [Playgrounds via Ray Wenderlich](http://www.raywenderlich.com/115253/swift-2-tutorial-a-quick-start) - [XCPlaygrounds via NSHipster](http://nshipster.com/xcplayground/) */ //: As tradition dictates, any exploration of a new language needs to start with "hello, world" //: Semi-colons, not required, unless you place multiple instructions on the same line //: Identifiers, first character A-Z or a-z or _, followed by any of these plus 0-9 let 你好 = "你好世界" print(你好) //: Constants are declared with 'let' keyword //: Variables are declared with 'var' keyword //: Above values determined implicitly, below shows explicit types //: Data types in Swift //: Type safety: once a var's data type is set, it cannot hold a value of any other type //: Types are never automatically converted //: String interpolation and concatenation //: Literals, just a value //: Operators //: Collections: Arrays //: Collections: Dictionaries //: for loop //: switch //: Testing a UIKit component in a playground //import UIKit // //class TestDataSource : NSObject, UITableViewDataSource //{ // let sortedCaptains = moreCaptains.sort() // // func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int // { // return sortedCaptains.count // } // // func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell // { // let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) // // let captainsName = sortedCaptains[indexPath.row] // cell.textLabel?.text = "\(captainsName)" // return cell // } //}
cc0-1.0
bbe48ea36b6626cedb39f43e1a0a937a
17.509615
109
0.687792
3.857715
false
false
false
false
turingcorp/gattaca
gattaca/View/Home/VHomeMark.swift
1
945
import UIKit class VHomeMark:View<VHome, MHome, CHome> { private weak var imageView:UIImageView! required init(controller:CHome) { super.init(controller:controller) isUserInteractionEnabled = false backgroundColor = UIColor.white alpha = 0 let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center self.imageView = imageView addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: internal func updateMark(action:MHomeActionProtocol) { imageView.image = action.display } }
mit
1fdb189230bc2b6ab6d644339e305916
23.230769
67
0.625397
5.625
false
false
false
false
kylef/Stencil
Sources/Filters.swift
1
3653
func capitalise(_ value: Any?) -> Any? { if let array = value as? [Any?] { return array.map { stringify($0).capitalized } } else { return stringify(value).capitalized } } func uppercase(_ value: Any?) -> Any? { if let array = value as? [Any?] { return array.map { stringify($0).uppercased() } } else { return stringify(value).uppercased() } } func lowercase(_ value: Any?) -> Any? { if let array = value as? [Any?] { return array.map { stringify($0).lowercased() } } else { return stringify(value).lowercased() } } func defaultFilter(value: Any?, arguments: [Any?]) -> Any? { // value can be optional wrapping nil, so this way we check for underlying value if let value = value, String(describing: value) != "nil" { return value } for argument in arguments { if let argument = argument { return argument } } return nil } func joinFilter(value: Any?, arguments: [Any?]) throws -> Any? { guard arguments.count < 2 else { throw TemplateSyntaxError("'join' filter takes at most one argument") } let separator = stringify(arguments.first ?? "") if let value = value as? [Any] { return value .map(stringify) .joined(separator: separator) } return value } func splitFilter(value: Any?, arguments: [Any?]) throws -> Any? { guard arguments.count < 2 else { throw TemplateSyntaxError("'split' filter takes at most one argument") } let separator = stringify(arguments.first ?? " ") if let value = value as? String { return value.components(separatedBy: separator) } return value } func indentFilter(value: Any?, arguments: [Any?]) throws -> Any? { guard arguments.count <= 3 else { throw TemplateSyntaxError("'indent' filter can take at most 3 arguments") } var indentWidth = 4 if !arguments.isEmpty { guard let value = arguments[0] as? Int else { throw TemplateSyntaxError(""" 'indent' filter width argument must be an Integer (\(String(describing: arguments[0]))) """) } indentWidth = value } var indentationChar = " " if arguments.count > 1 { guard let value = arguments[1] as? String else { throw TemplateSyntaxError(""" 'indent' filter indentation argument must be a String (\(String(describing: arguments[1])) """) } indentationChar = value } var indentFirst = false if arguments.count > 2 { guard let value = arguments[2] as? Bool else { throw TemplateSyntaxError("'indent' filter indentFirst argument must be a Bool") } indentFirst = value } let indentation = [String](repeating: indentationChar, count: indentWidth).joined() return indent(stringify(value), indentation: indentation, indentFirst: indentFirst) } func indent(_ content: String, indentation: String, indentFirst: Bool) -> String { guard !indentation.isEmpty else { return content } var lines = content.components(separatedBy: .newlines) let firstLine = (indentFirst ? indentation : "") + lines.removeFirst() let result = lines.reduce(into: [firstLine]) { result, line in result.append(line.isEmpty ? "" : "\(indentation)\(line)") } return result.joined(separator: "\n") } func filterFilter(value: Any?, arguments: [Any?], context: Context) throws -> Any? { guard let value = value else { return nil } guard arguments.count == 1 else { throw TemplateSyntaxError("'filter' filter takes one argument") } let attribute = stringify(arguments[0]) let expr = try context.environment.compileFilter("$0|\(attribute)") return try context.push(dictionary: ["$0": value]) { try expr.resolve(context) } }
bsd-2-clause
66dedd92a792ea896ee8d9c7c077c357
27.317829
98
0.659732
4.058889
false
false
false
false
dpricha89/DrApp
Pods/SwiftIconFont/SwiftIconFont/Classes/FontLoader.swift
1
1631
// // FontLoader.swift // SwiftIconFont // // Created by Sedat Ciftci on 18/03/16. // Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved. // import UIKit import Foundation import CoreText class FontLoader: NSObject { class func loadFont(_ fontName: String) { let bundle = Bundle(for: FontLoader.self) let paths = bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) var fontURL = URL(string: "") var error: Unmanaged<CFError>? paths.forEach { guard let filename = NSURL(fileURLWithPath: $0).lastPathComponent, filename.lowercased().range(of: fontName.lowercased()) != nil else { return } fontURL = NSURL(fileURLWithPath: $0) as URL } guard let unwrappedFontURL = fontURL, let data = try? Data(contentsOf: unwrappedFontURL), let provider = CGDataProvider(data: data as CFData) else { return } let font = CGFont.init(provider) guard let unwrappedFont = font, !CTFontManagerRegisterGraphicsFont(unwrappedFont, &error), let unwrappedError = error, let nsError = (unwrappedError.takeUnretainedValue() as AnyObject) as? NSError else { return } let errorDescription: CFString = CFErrorCopyDescription(unwrappedError.takeUnretainedValue()) NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } }
apache-2.0
d75e540197f6237d66964e0545dc7fe5
29.185185
101
0.620859
5
false
false
false
false
samnm/material-components-ios
components/AppBar/examples/AppBarModalPresentationExample.swift
2
5507
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents class AppBarModalPresentationSwiftExamplePresented: UITableViewController { let appBar = MDCAppBar() init() { super.init(nibName: nil, bundle: nil) self.title = "Modal Presentation (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor(white: 0.2, alpha:1) appBar.headerViewController.headerView.backgroundColor = color let mutator = MDCAppBarTextColorAccessibilityMutator() mutator.mutate(appBar) self.modalPresentationStyle = .formSheet self.modalTransitionStyle = .coverVertical } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() appBar.headerViewController.headerView.trackingScrollView = self.tableView self.tableView.delegate = appBar.headerViewController appBar.addSubviewsToParent() self.tableView.layoutMargins = UIEdgeInsets.zero self.tableView.separatorInset = UIEdgeInsets.zero self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Touch", style: .done, target: nil, action: nil) self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Dismiss", style: .done, target: self, action: #selector(dismissSelf)) } override var childViewControllerForStatusBarHidden: UIViewController? { return appBar.headerViewController } override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell!.layoutMargins = UIEdgeInsets.zero return cell! } @objc func dismissSelf() { self.dismiss(animated: true, completion: nil) } } class AppBarModalPresentationSwiftExample: UITableViewController { let appBar = MDCAppBar() init() { super.init(nibName: nil, bundle: nil) self.title = "Modal Presentation (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor(white: 0.2, alpha:1) appBar.headerViewController.headerView.backgroundColor = color let mutator = MDCAppBarTextColorAccessibilityMutator() mutator.mutate(appBar) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() appBar.headerViewController.headerView.trackingScrollView = self.tableView self.tableView.delegate = appBar.headerViewController appBar.addSubviewsToParent() self.tableView.layoutMargins = UIEdgeInsets.zero self.tableView.separatorInset = UIEdgeInsets.zero self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Detail", style: .done, target: self, action: #selector(presentModal)) } override var childViewControllerForStatusBarHidden: UIViewController? { return appBar.headerViewController } override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } @objc func presentModal() { let modalVC = AppBarModalPresentationSwiftExamplePresented() self.present(modalVC, animated: true, completion: nil) } } // MARK: Catalog by convention extension AppBarModalPresentationSwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["App Bar", "Modal Presentation (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } @objc class func catalogIsPresentable() -> Bool { return true } } // MARK: - Typical application code (not Material-specific) // MARK: UITableViewDataSource extension AppBarModalPresentationSwiftExample { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell!.layoutMargins = UIEdgeInsets.zero return cell! } }
apache-2.0
dfc4a50455442b8580ff47c225f36bd3
27.984211
99
0.743962
4.988225
false
false
false
false
ktustanowski/gravityfallsdeciphered
GravityFalls_Decrypted.playground/Contents.swift
1
4224
// Gravity Falls - deciphered import Foundation class Decryptor { fileprivate var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] func decrypt(_ input: String) -> String? { var output = "" for character in input.characters { output += substitute(String(character).lowercased()) } return output } func substitute(_ string: String) -> String { assertionFailure("Override!") return "" } } /// Works for episodes 1 - 6. Three letters back - you can hear this when you play Gravity Falls intro backwards. class ShiftLettersDecryptor: Decryptor { fileprivate let shift: Int init(shift: Int) { self.shift = shift super.init() } override func substitute(_ string: String) -> String { guard let index = alphabet.index(of: string) else { return string } var movedIndex = index + shift if movedIndex < 0 { movedIndex = alphabet.count + movedIndex } else if movedIndex > alphabet.count - 1 { movedIndex = movedIndex - (alphabet.count - 1) } return alphabet[movedIndex] } } /// Works for episodes 7 - 13. The clue to this was 6th episode cipher - "mr. ceasarian will be out next week mr. atbash will substitute". Ceasar cipher changed to atbash (both are substitution ciphers) class AtbashDecryptor: Decryptor { override func substitute(_ string: String) -> String { guard let index = alphabet.index(of: string) else { return string } return alphabet[alphabet.count - index - 1] } } // Works for episodes 14 - 19 + note on a map from episode 20. class NumbersDecryptor: Decryptor { fileprivate var cipherDictionary = [String : String]() override func decrypt(_ input: String) -> String? { cipherDictionary.removeAll() // The most annoying part of this is to properly replace characters in message // so when we do .separatedBy we just get strings we can change to numbers. // This may break depending on what text you will use and whether you are using characters // that are currently supported or not. I even noticed that – is not the same as -. let numbers = input.replacingOccurrences(of: " ", with: "-") .replacingOccurrences(of: ":", with: "") .replacingOccurrences(of: "\"", with: "") .replacingOccurrences(of: ",", with: "") .replacingOccurrences(of: "`", with: "") .replacingOccurrences(of: ".", with: "") .replacingOccurrences(of: "'", with: "-") .replacingOccurrences(of: "?", with: "") .replacingOccurrences(of: "!", with: "") .replacingOccurrences(of: "'", with: "-") .replacingOccurrences(of: "–", with: "-") .replacingOccurrences(of: "“", with: "") .replacingOccurrences(of: "”", with: "") .components(separatedBy: "-") for number in numbers { guard Int(number) != nil else { assertionFailure("Unsupported character found in _\(number)_. Please remove it or add another .replacingOccurrences(of:") break } guard cipherDictionary[number] == nil else { continue } cipherDictionary[number] = substitute(number) } var output = input let allNumbers = cipherDictionary.keys.sorted { Int($0)! > Int($1)! } for number in allNumbers { guard let text = cipherDictionary[number] else { continue } output = output.replacingOccurrences(of: number, with: text) } return output.replacingOccurrences(of: "-", with: "") .replacingOccurrences(of: "–", with: "") } override func substitute(_ string: String) -> String { guard let index = Int(string), index > 0, index < alphabet.count else { return "?" } return alphabet[index - 1].isEmpty ? string : alphabet[index - 1] } }
mit
22d4139041135a329fb3cf2fab2f6290
38.018519
202
0.573564
4.565547
false
false
false
false
tattn/SPAJAM2017-Final
SPAJAM2017Final/Utility/Extension/Dictionary+.swift
1
640
// // Dictionary+.swift // HackathonStarter // // Created by 田中 達也 on 2016/07/13. // Copyright © 2016年 tattn. All rights reserved. // import Foundation extension Dictionary { // See http://ericasadun.com/2015/07/08/swift-merging-dictionaries/ mutating func merge<S: Sequence>(_ other: S) where S.Iterator.Element == (key: Key, value: Value) { for (key, value) in other { self[key] = value } } func merged<S: Sequence>(_ other: S) -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value) { var dic = self dic.merge(other) return dic } }
mit
1d532c537588c035f531c9c75c3d04b8
25.125
111
0.602871
3.370968
false
false
false
false
sjtu-meow/iOS
Meow/CommentViewController.swift
1
2734
// // CommentViewController.swift // Meow // // Created by 林武威 on 2017/7/18. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit class CommentViewController: UITableViewController { var item: ItemProtocol! var comments: [Comment] { switch item.type! { case .answer: return (item as! Answer).comments case .article: return (item as! Article).comments default: return [] } } override func viewDidLoad() { tableView.rowHeight = UITableViewAutomaticDimension tableView.register(R.nib.commentTableViewCell) tableView.estimatedRowHeight = 44 tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.allowsSelection = false tableView.separatorInset = .init(top: 0, left: 16, bottom: 0, right: 16) } func configure(model: ItemProtocol) { self.item = model self.tableView.reloadData() } func reloadComments(model: ItemProtocol) { switch item.type! { case .article: MeowAPIProvider.shared.request(.article(id: item.id)) .mapTo(type: Article.self) .subscribe(onNext:{ [weak self] (article) in self?.item = article self?.tableView.reloadData() }) case .answer: MeowAPIProvider.shared.request(.answer(id: item.id)) .mapTo(type: Answer.self) .subscribe(onNext:{ [weak self] (answer) in self?.item = answer self?.tableView.reloadData() }) default: break } } override func viewWillAppear(_ animated: Bool) { reloadComments(model: item) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let comment = comments[indexPath.row] let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.commentTableViewCell)! view.configure(model: comment) return view } @IBAction func showPostCommentView(_ sender: Any) { let vc = R.storyboard.postPages.postCommentController()! vc.configure(model: self.item) navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
715c46db8e3c5ac6d8f1777acb1f3dc6
29.483146
109
0.579432
4.968864
false
false
false
false
scoremedia/Fisticuffs
Samples/CollectionViewSample.swift
1
6041
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Fisticuffs class CollectionViewSampleViewModel { let items = Observable(Array(1...100)) let selections = Observable<[Int]>([]) lazy var sum: Computed<Int> = Computed { [selections = self.selections] in selections.value.reduce(0) { total, value in total + value } } lazy var sumDisplayString: Computed<String> = Computed { [sum = self.sum] in sum.value > 0 ? "Sum: \(sum.value)" : "Try selecting some items!" } func clearSelection() { selections.value = [] } } class CollectionViewSampleController: UIViewController { @IBOutlet var collectionView: UICollectionView! @IBOutlet var clearButton: UIBarButtonItem! //MARK: - let viewModel = CollectionViewSampleViewModel() let spacing: CGFloat = 10 let itemsPerRow = 4 //MARK: - override func viewDidLoad() { super.viewDidLoad() collectionView.register(CollectionViewSampleCell.self, forCellWithReuseIdentifier: "Cell") collectionView.allowsMultipleSelection = true let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing) layout.minimumInteritemSpacing = spacing layout.minimumLineSpacing = spacing if #available(iOS 9, *) { let reorderGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(CollectionViewSampleController.handleReorderGestureRecognizer(_:))) collectionView.addGestureRecognizer(reorderGestureRecognizer) } collectionView.b_configure(viewModel.items) { config in config.allowsMoving = true config.selections = viewModel.selections config.deselectOnSelection = false config.useCell(reuseIdentifier: "Cell") { item, cell in (cell as! CollectionViewSampleCell).label.text = "\(item)" } } _ = clearButton.b_onTap.subscribe(viewModel.clearSelection) _ = viewModel.sumDisplayString.subscribe { [navigationItem = navigationItem] _, displayString in navigationItem.prompt = displayString } } override func viewDidLayoutSubviews() { let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemWidth = (view.frame.size.width - spacing * CGFloat(2 + itemsPerRow - 1)) / CGFloat(itemsPerRow) layout.itemSize = CGSize(width: itemWidth, height: itemWidth) super.viewDidLayoutSubviews() } @objc @available(iOS 9, *) func handleReorderGestureRecognizer(_ gestureRecognizer: UILongPressGestureRecognizer) { switch gestureRecognizer.state { case .began: let touchLocation = gestureRecognizer.location(in: collectionView) if let indexPath = collectionView.indexPathForItem(at: touchLocation) { collectionView.beginInteractiveMovementForItem(at: indexPath) } case .changed: let touchLocation = gestureRecognizer.location(in: collectionView) collectionView.updateInteractiveMovementTargetPosition(touchLocation) case .ended: collectionView.endInteractiveMovement() case .cancelled: collectionView.cancelInteractiveMovement() default: break } } } class CollectionViewSampleCell: UICollectionViewCell { var label: UILabel! override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setup() { label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(label) backgroundView = UIView() backgroundView?.backgroundColor = UIColor(red: 0.565, green: 0.831, blue: 0.800, alpha: 1.0) selectedBackgroundView = UIView() selectedBackgroundView?.backgroundColor = UIColor(red: 1.0, green: 0.867, blue: 0.0, alpha: 1.0) let centerX = NSLayoutConstraint( item: label!, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0 ) let centerY = NSLayoutConstraint( item: label!, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0 ) NSLayoutConstraint.activate([centerX, centerY]) } }
mit
457c4295d3f24c9bb6a74f21c80d0394
34.958333
171
0.649065
5.225779
false
false
false
false
dymx101/Gamers
Gamers/ViewModels/YTVideoListCell.swift
1
1839
// // YTVideoListCell.swift // Gamers // // Created by 虚空之翼 on 15/9/11. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit class YTVideoListCell: UITableViewCell { @IBOutlet weak var videoImage: UIImageView! @IBOutlet weak var videoTitle: UILabel! @IBOutlet weak var videoChannel: UILabel! @IBOutlet weak var videoViews: UILabel! var delegate: MyCellDelegate! @IBAction func clickShare(sender: AnyObject) { self.delegate.clickCellButton!(self) } override func awakeFromNib() { super.awakeFromNib() // 视频标题自动换行以及超出省略号 videoTitle.numberOfLines = 0 videoTitle.lineBreakMode = NSLineBreakMode.ByCharWrapping videoTitle.lineBreakMode = NSLineBreakMode.ByTruncatingTail } func setVideo(video: YTVideo) { videoChannel.text = video.channelTitle videoTitle.text = video.title //videoViews.text = BasicFunction.formatViewsTotal(0) + " • " + BasicFunction.formatDateString(video.publishedAt) videoViews.text = BasicFunction.formatDateString(video.publishedAt) let imageUrl = video.thumbnailMedium.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) videoImage.hnk_setImageFromURL(NSURL(string: imageUrl)!, placeholder: UIImage(named: "placeholder.png")) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() videoImage.hnk_cancelSetImage() videoImage.image = nil } }
apache-2.0
a536684a5088e34c5f98f9b40ed4ba85
29.982759
164
0.66778
4.817694
false
false
false
false
lelandjansen/fatigue
ios/fatigue/LegalCell.swift
1
3519
import UIKit class LegalCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } weak var delegate: OnboardingDelegate? let titleLabel: UILabel = { let label = UILabel() label.text = "A few formalities" label.font = .systemFont(ofSize: 22) label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.textColor = .dark return label }() let legalTextView: UITextView = { let view = UITextView() if let path = Bundle.main.path(forResource: "LEGAL", ofType: String()) { let fileManager = FileManager() let contents = fileManager.contents(atPath: path) let fileText = NSString(data: contents!, encoding: String.Encoding.utf8.rawValue)! as String view.text = fileText.trimmingCharacters(in: .whitespacesAndNewlines) } view.isEditable = false view.font = .systemFont(ofSize: 14) view.textColor = .dark view.backgroundColor = .clear view.textAlignment = .justified return view }() let agreeButton: UIButton = { let button = UIButton.createStyledSelectButton(withColor: .violet) button.setTitle("I Agree", for: .normal) return button }() func handleAgreeButton() { if self.agreeButton.isSelected { self.delegate?.moveToNextPage() return } let alertController = UIAlertController(title: "Confirmation", message: String(), preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "I Agree", style: .default, handler: { _ in self.agreeButton.isSelected = true self.delegate?.addNextPage() self.delegate?.moveToNextPage() })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) delegate?.presentViewController(alertController) } func setupViews() { addSubview(titleLabel) addSubview(agreeButton) addSubview(legalTextView) let padding: CGFloat = 16 titleLabel.anchorWithConstantsToTop( topAnchor, left: leftAnchor, right: rightAnchor, topConstant: 3 * padding, leftConstant: padding, rightConstant: padding ) let buttonBottomPadding: CGFloat = 2 * padding agreeButton.anchorWithConstantsToTop( topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: frame.height - UIConstants.buttonHeight - buttonBottomPadding, leftConstant: (frame.width - UIConstants.buttonWidth) / 2, bottomConstant: buttonBottomPadding, rightConstant: (frame.width - UIConstants.buttonWidth) / 2 ) agreeButton.addTarget(self, action: #selector(handleAgreeButton), for: .touchUpInside) legalTextView.anchorWithConstantsToTop( titleLabel.bottomAnchor, left: leftAnchor, bottom: agreeButton.topAnchor, right: rightAnchor, topConstant: padding, leftConstant: padding / 2, bottomConstant: padding, rightConstant: padding / 2 ) } }
apache-2.0
319e2bbb5d7f5407a09de13dca542cd4
34.545455
113
0.608127
5.190265
false
false
false
false
aslanyanhaik/Quick-Chat
QuickChat/Models/ObjectConversation.swift
1
2443
// MIT License // Copyright (c) 2019 Haik Aslanyan // 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 class ObjectConversation: FireCodable { var id = UUID().uuidString var userIDs = [String]() var timestamp = Int(Date().timeIntervalSince1970) var lastMessage: String? var isRead = [String: Bool]() func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(userIDs, forKey: .userIDs) try container.encode(timestamp, forKey: .timestamp) try container.encodeIfPresent(lastMessage, forKey: .lastMessage) try container.encode(isRead, forKey: .isRead) } init() {} public required convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) userIDs = try container.decode([String].self, forKey: .userIDs) timestamp = try container.decode(Int.self, forKey: .timestamp) lastMessage = try container.decodeIfPresent(String.self, forKey: .lastMessage) isRead = try container.decode([String: Bool].self, forKey: .isRead) } } extension ObjectConversation { private enum CodingKeys: String, CodingKey { case id case userIDs case timestamp case lastMessage case isRead } }
mit
4bfbfd441f379fa3adf8a8d1e3ec1c8a
37.777778
82
0.733115
4.293497
false
false
false
false
AlexChekanov/Gestalt
Gestalt/NavigationCoordinators/RootNavigationCoordinator.swift
1
2054
import UIKit import Firebase protocol NavigationCoordinator: class { func next(arguments: Dictionary<String, Any>?) func movingBack() } class RootNavigationCoordinatorImpl: NavigationCoordinator { var registry: DependencyRegistry var rootViewController: UIViewController enum NavigationState { case atFeed case atDetails } var navState: NavigationState init(with rootViewController: UIViewController, registry: DependencyRegistry) { FirebaseCrashMessage("RootNavigationCoordinatorImpl Init Error") self.rootViewController = rootViewController self.registry = registry self.navState = .atFeed } func movingBack() { switch navState { case .atFeed: //not possible to move back - do nothing break case .atDetails: navState = .atFeed } } func next(arguments: Dictionary<String, Any>?) { switch navState { case .atFeed: showDetails(arguments: arguments) case .atDetails: //example - do nothing showFeed() } } func showDetails(arguments: Dictionary<String, Any>?) { guard let task = arguments?["task"] as? TaskDTO else { notifyNilArguments(); return } FirebaseCrashMessage("RootNavigationCoordinatorImpl.showDetails \(arguments as Any) Error") let detailViewController = registry.makeDetailViewController(with: task) rootViewController.navigationController?.showDetailViewController(UINavigationController(rootViewController: detailViewController), sender: self) navState = .atDetails } func showFeed() { FirebaseCrashMessage("RootNavigationCoordinatorImpl.showFeed() Error") rootViewController.navigationController?.popToRootViewController(animated: true) navState = .atFeed } func notifyNilArguments() { print("notify user of error") } }
apache-2.0
65a7b3817d3d8aee58d15f957cfafd6e
27.929577
153
0.64703
5.551351
false
false
false
false
melling/ios_topics
GameClock/GameClock/ViewController.swift
1
1886
// // ViewController.swift // GameClock // // Created by Michael Mellinger on 11/24/17. // Copyright © 2017 h4labs. All rights reserved. // import UIKit class ViewController: UIViewController { private let timerLabel = UILabel() private let stopButton = UIButton() private var isRunning = true private var gameClock = GameClock() private func buildView() { let views = [timerLabel,stopButton] views.forEach{$0.translatesAutoresizingMaskIntoConstraints = false} views.forEach(self.view.addSubview) NSLayoutConstraint.activate([ timerLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), timerLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), stopButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), stopButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant:100), ]) timerLabel.font = UIFont.systemFont(ofSize: 36) timerLabel.text = "00:00" stopButton.setTitle("Stop", for: .normal) stopButton.addTarget(self, action: #selector(stopClock), for: .touchUpInside) } @objc func stopClock() { switch isRunning { case true: isRunning = false gameClock.pauseClock() stopButton.setTitle("Restart", for: .normal) case false: isRunning = true gameClock.resetClock() gameClock.startClock() stopButton.setTitle("Stop", for: .normal) } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(named: "AppleVideosColor") buildView() gameClock.setLabel(label: timerLabel) gameClock.startClock() } }
cc0-1.0
59a4a869976505a4d97f04032b091d6d
27.560606
96
0.617507
4.934555
false
false
false
false
yuByte/SwiftGo
Examples/Examples.playground/Pages/18. Fliping Coins.xcplaygroundpage/Contents.swift
4
536
import SwiftGo import Darwin var channelA: Channel<String>? = Channel<String>() var channelB: Channel<String>? = Channel<String>() if arc4random_uniform(2) == 0 { channelA = nil print("disabled channel a") } else { channelB = nil print("disabled channel b") } go(channelA <- "a") go(channelB <- "b") select { when in when.receiveFrom(channelA) { value in print("received \(value) from channel a") } when.receiveFrom(channelB) { value in print("received \(value) from channel b") } }
mit
3f4718c4102a16841bae508ee4234db4
19.615385
50
0.63806
3.414013
false
false
false
false
jopamer/swift
stdlib/public/core/ContiguousArray.swift
1
54517
//===--- ContiguousArray.swift --------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `ContiguousArray<Element>` is a fast, contiguous array of `Element` with // a known backing store. // //===----------------------------------------------------------------------===// /// A contiguously stored array. /// /// The `ContiguousArray` type is a specialized array that always stores its /// elements in a contiguous region of memory. This contrasts with `Array`, /// which can store its elements in either a contiguous region of memory or an /// `NSArray` instance if its `Element` type is a class or `@objc` protocol. /// /// If your array's `Element` type is a class or `@objc` protocol and you do /// not need to bridge the array to `NSArray` or pass the array to Objective-C /// APIs, using `ContiguousArray` may be more efficient and have more /// predictable performance than `Array`. If the array's `Element` type is a /// struct or enumeration, `Array` and `ContiguousArray` should have similar /// efficiency. /// /// For more information about using arrays, see `Array` and `ArraySlice`, with /// which `ContiguousArray` shares most properties and methods. @_fixed_layout public struct ContiguousArray<Element>: _DestructorSafeContainer { @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } extension ContiguousArray: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<ContiguousArray> /// The position of the first element in a nonempty array. /// /// For an instance of `ContiguousArray`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array, in which case /// writing is O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { // This call may be hoisted or eliminated by the optimizer. If // there is an inout violation, this value may be stale so needs to be // checked again below. let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() // Make sure the index is in range and wasNativeTypeChecked is // still valid. let token = _checkSubscript( index, wasNativeTypeChecked: wasNativeTypeChecked) return _getElement( index, wasNativeTypeChecked: wasNativeTypeChecked, matchingSubscriptCheck: token) } mutableAddressWithPinnedNativeOwner { _makeMutableAndUniqueOrPinned() // makes the array native, too _checkSubscript_native(index) return (_getElementAddress(index), Builtin.tryPin(_getOwner_native())) } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } } //===--- private helpers---------------------------------------------------===// extension ContiguousArray { /// Returns `true` if the array is native and does not need a deferred /// type check. May be hoisted by the optimizer, which means its /// results may be stale by the time they are used if there is an /// inout violation in user code. @inlinable @_semantics("array.props.isNativeTypeChecked") public // @testable func _hoistableIsNativeTypeChecked() -> Bool { return _buffer.arrayPropertyIsNativeTypeChecked } @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.count } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.capacity } /// - Precondition: The array has a native buffer. @inlinable @_semantics("array.owner") internal func _getOwnerWithSemanticLabel_native() -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(_buffer.nativeOwner) } /// - Precondition: The array has a native buffer. @inlinable @inline(__always) internal func _getOwner_native() -> Builtin.NativeObject { #if _runtime(_ObjC) if _isClassOrObjCExistential(Element.self) { // We are hiding the access to '_buffer.owner' behind // _getOwner() to help the compiler hoist uniqueness checks in // the case of class or Objective-C existential typed array // elements. return _getOwnerWithSemanticLabel_native() } #endif // In the value typed case the extra call to // _getOwnerWithSemanticLabel_native hinders optimization. return Builtin.unsafeCastToNativeObject(_buffer.owner) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _buffer = _Buffer(copying: _buffer) } } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUniqueOrPinned() { if _slowPath(!_buffer.isMutableAndUniquelyReferencedOrPinned()) { _buffer = _Buffer(copying: _buffer) } } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _buffer._checkValidSubscript(index) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @_semantics("array.check_subscript") public // @testable func _checkSubscript( _ index: Int, wasNativeTypeChecked: Bool ) -> _DependenceToken { #if _runtime(_ObjC) _buffer._checkValidSubscript(index) #else _buffer._checkValidSubscript(index) #endif return _DependenceToken() } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "ContiguousArray index is out of range") _precondition(index >= startIndex, "Negative ContiguousArray index is out of range") } @_semantics("array.get_element") @inline(__always) public // @testable func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _DependenceToken ) -> Element { #if false return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked) #else return _buffer.getElement(index) #endif } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.subscriptBaseAddress + index } } extension ContiguousArray: ExpressibleByArrayLiteral { /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new array by using an array /// literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding only /// strings: /// /// let ingredients: ContiguousArray = /// ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self.init(_buffer: ContiguousArray(elements)._buffer) } } extension ContiguousArray: RangeReplaceableCollection, ArrayProtocol { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = ContiguousArray( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = ContiguousArray._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a ContiguousArray of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct ContiguousArray with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = ContiguousArray._allocateBufferUninitialized(minimumCapacity: count) _buffer.count = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a ContiguousArray of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (ContiguousArray, UnsafeMutablePointer<Element>) { let result = ContiguousArray(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 12 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } @inlinable internal var _baseAddress: UnsafeMutablePointer<Element> { return _buffer.firstElementAddress } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: minimumCapacity) == nil { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: minimumCapacity) _buffer._copyContents( subRange: _buffer.indices, initializing: newBuffer.firstElementAddress) _buffer = _Buffer( _buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex) } _sanityCheck(capacity >= minimumCapacity) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate( &newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _copyToNewBuffer(oldCount: _buffer.count) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // This is a performance optimization. This code used to be in an || // statement in the _sanityCheck below. // // _sanityCheck(_buffer.capacity == 0 || // _buffer.isMutableAndUniquelyReferenced()) // // SR-6437 let capacity = _buffer.capacity == 0 // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that preceeds this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. _sanityCheck(capacity || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > _buffer.capacity) { _copyToNewBuffer(oldCount: oldCount) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: Element ) { _sanityCheck(_buffer.isMutableAndUniquelyReferenced()) _sanityCheck(_buffer.capacity >= _buffer.count + 1) _buffer.count = oldCount + 1 (_buffer.firstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: Element) { _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _getCount() _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: S) where S.Element == Element { let newElementsCount = newElements.underestimatedCount reserveCapacityForAppend(newElementsCount: newElementsCount) let oldCount = self.count let startNewElements = _buffer.firstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: self.capacity - oldCount) let (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate _buffer.count += writtenCount if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode _buffer._arrayAppendSequence(IteratorSequence(remainder)) } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { let oldCount = self.count let oldCapacity = self.capacity let newCount = oldCount + newElementsCount // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. self.reserveCapacity( newCount > oldCapacity ? Swift.max(newCount, _growArrayCapacity(oldCapacity)) : newCount) } @inlinable public mutating func _customRemoveLast() -> Element? { let newCount = _getCount() - 1 _precondition(newCount >= 0, "Can't removeLast from an empty ContiguousArray") _makeUniqueAndReserveCapacityIfNotUnique() let pointer = (_buffer.firstElementAddress + newCount) let element = pointer.move() _buffer.count = newCount return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult public mutating func remove(at index: Int) -> Element { _precondition(index < endIndex, "Index out of range") _precondition(index >= startIndex, "Index out of range") _makeUniqueAndReserveCapacityIfNotUnique() let newCount = _getCount() - 1 let pointer = (_buffer.firstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.count = newCount return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(_buffer) } } extension ContiguousArray: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension ContiguousArray: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription(for: self, withTypeName: nil) } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return _makeCollectionDescription(for: self, withTypeName: "ContiguousArray") } } extension ContiguousArray { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension ContiguousArray { /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { let count = self.count // Ensure unique storage _buffer._outlinedMakeUniqueBuffer(bufferCount: count) // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. // NOTE: The stack promotion optimization that keys of the // "array.withUnsafeMutableBufferPointer" semantics annotation relies on the // array buffer not being able to escape in the closure. It can do this // because we swap the array buffer in self with an empty buffer here. Any // escape via the address of self in the closure will therefore escape the // empty array. var work = ContiguousArray() (work, self) = (self, work) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.firstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "ContiguousArray withUnsafeMutableBufferPointer: replacing the buffer is not allowed") (work, self) = (self, work) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension ContiguousArray { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "ContiguousArray replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "ContiguousArray replace: subrange extends past the end") let oldCount = _buffer.count let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: oldCount + growth) != nil { _buffer.replaceSubrange( subrange, with: insertCount, elementsOf: newElements) } else { _buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount) } } } extension ContiguousArray: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _sanityCheck(lhs.startIndex == 0 && rhs.startIndex == 0) _sanityCheck(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } /// Returns a Boolean value indicating whether two arrays are not equal. /// /// Two arrays are equal if they contain the same elements in the same order. /// You can use the not-equal-to operator (`!=`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func !=(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool { return !(lhs == rhs) } } extension ContiguousArray: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension ContiguousArray { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...] /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } }
apache-2.0
fa0c0a5f63566099ca720a0bbdee7bc6
37.440762
99
0.661267
4.436315
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/General/JS/WalletUpgradeJSService.swift
1
3792
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import CombineSchedulers import DIKit import Localization import ToolKit protocol WalletUpgradeJSServicing: AnyObject { /// Upgrades the wallet to V3 and emits "V3" /// Fails with `WalletUpgradeError.failedV3Upgrade` if anything went wrong. func upgradeToV3() -> AnyPublisher<String, WalletUpgradeJSError> /// Upgrades the wallet to V4 and emits "V4" /// Fails with `WalletUpgradeError.failedV4Upgrade` if anything went wrong. func upgradeToV4() -> AnyPublisher<String, WalletUpgradeJSError> } enum WalletUpgradeJSError: Error { case failedV3Upgrade case failedV4Upgrade } final class WalletUpgradeJSService: WalletUpgradeJSServicing { // MARK: Types private enum JSCallback { enum V3Payload: NSString { case didUpgrade = "objc_upgrade_V3_success" case didFail = "objc_upgrade_V3_error" } enum V4Payload: NSString { case didUpgrade = "objc_upgrade_V4_success" case didFail = "objc_upgrade_V4_error" } } private enum JSFunction { enum V3Payload { static func upgrade(with newWalletName: String) -> String { "MyWalletPhone.upgradeToV3(\"\(newWalletName)\")" } } enum V4Payload: String { case upgrade = "MyWalletPhone.upgradeToV4()" } } // MARK: Private Properties private let contextProvider: JSContextProviderAPI private let queue: AnySchedulerOf<DispatchQueue> // MARK: Init init( contextProvider: JSContextProviderAPI = resolve(), queue: AnySchedulerOf<DispatchQueue> = .main ) { self.contextProvider = contextProvider self.queue = queue } // MARK: WalletUpgradeJSServicing func upgradeToV3() -> AnyPublisher<String, WalletUpgradeJSError> { Deferred { [contextProvider] in Future<String, WalletUpgradeJSError> { promise in let context = contextProvider.jsContext let walletName = LocalizationConstants.Account.myWallet context.invokeOnce( functionBlock: { promise(.success("V3")) }, forJsFunctionName: JSCallback.V3Payload.didUpgrade.rawValue ) context.invokeOnce( functionBlock: { promise(.failure(WalletUpgradeJSError.failedV3Upgrade)) }, forJsFunctionName: JSCallback.V3Payload.didFail.rawValue ) context.evaluateScriptCheckIsOnMainQueue(JSFunction.V3Payload.upgrade(with: walletName)) } } .subscribe(on: queue) .eraseToAnyPublisher() } func upgradeToV4() -> AnyPublisher<String, WalletUpgradeJSError> { Deferred { [contextProvider] in Future<String, WalletUpgradeJSError> { promise in let context = contextProvider.jsContext context.invokeOnce( functionBlock: { promise(.success("V4")) }, forJsFunctionName: JSCallback.V4Payload.didUpgrade.rawValue ) context.invokeOnce( functionBlock: { promise(.failure(WalletUpgradeJSError.failedV4Upgrade)) }, forJsFunctionName: JSCallback.V4Payload.didFail.rawValue ) context.evaluateScriptCheckIsOnMainQueue(JSFunction.V4Payload.upgrade.rawValue) } } .subscribe(on: queue) .eraseToAnyPublisher() } }
lgpl-3.0
af7478a7b0e763d93824159a18262c45
31.965217
104
0.596149
4.916991
false
false
false
false
bumpersfm/handy
Components/WindowManager.swift
1
660
// // Created by Dani Postigo on 11/24/16. // import Foundation import UIKit public class WindowManager: NSObject { public static let shared = WindowManager() private var windows = [UIWindow]() public func show(window: UIWindow) { self.windows.append(window) window.hidden = false } public func makeKeyAndVisible(window window: UIWindow) { self.windows.append(window) window.makeKeyAndVisible() } public func remove(window window: UIWindow) { window.hidden = true guard let index = self.windows.indexOf(window) else { return } self.windows.removeAtIndex(index) } }
mit
12382abd84f962c43d5f16c89db1277c
21.758621
70
0.659091
4.370861
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/SettingsGeneral.swift
1
10178
// // SettingsGeneral.swift // Slide for Reddit // // Created by Carlos Crane on 1/11/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit import reddift class SettingsGeneral: UITableViewController { var viewType: UITableViewCell = UITableViewCell() var hideFAB: UITableViewCell = UITableViewCell() var postSorting: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "post") var commentSorting: UITableViewCell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "comment") var viewTypeSwitch = UISwitch() var hideFABSwitch = UISwitch() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: "") navigationController?.navigationBar.tintColor = UIColor.white } func switchIsChanged(_ changed: UISwitch) { if(changed == viewTypeSwitch){ SettingValues.viewType = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_viewType) } else if(changed == hideFABSwitch){ SettingValues.hiddenFAB = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_hiddenFAB) } UserDefaults.standard.synchronize() } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let label : UILabel = UILabel() label.textColor = ColorUtil.fontColor label.font = FontGenerator.boldFontOfSize(size: 20, submission: true) let toReturn = label.withPadding(padding: UIEdgeInsets.init(top: 0, left: 12, bottom: 0, right: 0)) toReturn.backgroundColor = ColorUtil.backgroundColor switch(section) { case 0: label.text = "Display" break case 1: label.text = "Sorting" break default: label.text = "" break } return toReturn } override func loadView() { super.loadView() self.view.backgroundColor = ColorUtil.backgroundColor // set the title self.title = "General" viewTypeSwitch = UISwitch() viewTypeSwitch.isOn = SettingValues.viewType viewTypeSwitch.addTarget(self, action: #selector(SettingsGeneral.switchIsChanged(_:)), for: UIControlEvents.valueChanged) self.viewType.textLabel?.text = "Subreddit tabs" self.viewType.accessoryView = viewTypeSwitch self.viewType.backgroundColor = ColorUtil.foregroundColor self.viewType.textLabel?.textColor = ColorUtil.fontColor viewType.selectionStyle = UITableViewCellSelectionStyle.none hideFABSwitch = UISwitch() hideFABSwitch.isOn = SettingValues.hiddenFAB hideFABSwitch.addTarget(self, action: #selector(SettingsGeneral.switchIsChanged(_:)), for: UIControlEvents.valueChanged) self.hideFAB.textLabel?.text = "Hide posts FAB" self.hideFAB.accessoryView = hideFABSwitch self.hideFAB.backgroundColor = ColorUtil.foregroundColor self.hideFAB.textLabel?.textColor = ColorUtil.fontColor hideFAB.selectionStyle = UITableViewCellSelectionStyle.none self.postSorting.textLabel?.text = "Default post sorting" self.postSorting.detailTextLabel?.text = SettingValues.defaultSorting.description self.postSorting.backgroundColor = ColorUtil.foregroundColor self.postSorting.textLabel?.textColor = ColorUtil.fontColor self.commentSorting.textLabel?.text = "Default comment sorting" self.commentSorting.detailTextLabel?.text = SettingValues.defaultCommentSorting.description self.commentSorting.backgroundColor = ColorUtil.foregroundColor self.commentSorting.textLabel?.textColor = ColorUtil.fontColor } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 70 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch(indexPath.section) { case 0: switch(indexPath.row) { case 0: return self.viewType case 1: return self.hideFAB default: fatalError("Unknown row in section 0") } case 1: switch(indexPath.row) { case 0: return self.postSorting case 1: return self.commentSorting default: fatalError("Unknown row in section 1") } default: fatalError("Unknown section") } } func showTimeMenu(s: LinkSortType){ if(s == .hot || s == .new){ SettingValues.defaultSorting = s UserDefaults.standard.set(s.path, forKey: SettingValues.pref_defaultSorting) UserDefaults.standard.synchronize() return } else { let actionSheetController: UIAlertController = UIAlertController(title: "Time Period", message: "", preferredStyle: .actionSheet) let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in print("Cancel") } actionSheetController.addAction(cancelActionButton) for t in TimeFilterWithin.cases { let saveActionButton: UIAlertAction = UIAlertAction(title: t.param, style: .default) { action -> Void in SettingValues.defaultSorting = s UserDefaults.standard.set(s.path, forKey: SettingValues.pref_defaultSorting) SettingValues.defaultTimePeriod = t UserDefaults.standard.set(t.param, forKey: SettingValues.pref_defaultTimePeriod) UserDefaults.standard.synchronize() } actionSheetController.addAction(saveActionButton) } actionSheetController.modalPresentationStyle = .popover if let presenter = actionSheetController.popoverPresentationController { presenter.sourceView = timeMenuView presenter.sourceRect = timeMenuView.bounds } self.present(actionSheetController, animated: true, completion: nil) } } var timeMenuView: UIView = UIView() override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.timeMenuView = self.tableView.cellForRow(at: indexPath)!.contentView if(indexPath.section == 1 && indexPath.row == 0){ let actionSheetController: UIAlertController = UIAlertController(title: "Default post sorting", message: "", preferredStyle: .actionSheet) let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in print("Cancel") } actionSheetController.addAction(cancelActionButton) for link in LinkSortType.cases { let saveActionButton: UIAlertAction = UIAlertAction(title: link.description, style: .default) { action -> Void in self.showTimeMenu(s: link) } actionSheetController.addAction(saveActionButton) } actionSheetController.modalPresentationStyle = .popover if let presenter = actionSheetController.popoverPresentationController { presenter.sourceView = timeMenuView presenter.sourceRect = timeMenuView.bounds } self.present(actionSheetController, animated: true, completion: nil) } else if(indexPath.section == 1 && indexPath.row == 1){ let actionSheetController: UIAlertController = UIAlertController(title: "Default comment sorting", message: "", preferredStyle: .actionSheet) let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in print("Cancel") } actionSheetController.addAction(cancelActionButton) for c in CommentSort.cases { let saveActionButton: UIAlertAction = UIAlertAction(title: c.description, style: .default) { action -> Void in SettingValues.defaultCommentSorting = c UserDefaults.standard.set(c.type, forKey: SettingValues.pref_defaultCommentSorting) UserDefaults.standard.synchronize() } actionSheetController.addAction(saveActionButton) } actionSheetController.modalPresentationStyle = .popover if let presenter = actionSheetController.popoverPresentationController { presenter.sourceView = timeMenuView presenter.sourceRect = timeMenuView.bounds } self.present(actionSheetController, animated: true, completion: nil) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section) { case 0: return 2 // section 0 has 2 rows case 1: return 2 // section 1 has 1 row default: fatalError("Unknown number of sections") } } }
apache-2.0
a4bb162872f9e6523feb1e0025d92250
41.404167
153
0.642036
5.582556
false
false
false
false
usharif/GrapeVyne
GrapeVyne/CoreDataManager.swift
1
6714
// // CoreDataManager.swift // StoryApp // // Created by Umair Sharif on 2/5/17. // Copyright © 2017 usharif. All rights reserved. // import UIKit import Foundation import CoreData class CoreDataManager { static func addStoryToCategory(category: Category, story: Story) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let categoryObject = fetchObject(entity: "CDCategory", title: category.title) as! CDCategory let storyObject = CDStory(context: context) storyObject.title = story.title storyObject.fact = story.fact storyObject.urlString = story.url categoryObject.addToStories(storyObject) do { try context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } static func removeStoryFromCategory(_ story: Story) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let storyObject = fetchObject(entity: "CDStory", title: story.title) as! CDStory storyObject.category?.removeFromStories(storyObject) do { try context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } static func writeToModel(_ story: Story) -> Story? { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext var retStory: Story? let argStory = story let _story = CDStory(context: context) _story.title = argStory.title _story.fact = argStory.fact _story.urlString = argStory .url do { try context.save() if let title = _story.title, let url = _story.urlString { retStory = Story(title: title, url: url, fact: _story.fact, id: _story.objectID) } } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return retStory } static func writeToModel(_ category: Category) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let _category = CDCategory(context: context) _category.title = category.title _category.urlString = category.url do { try context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } static func writeMetricToModel(entity: String, value: Bool) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: entity, in: context) let metric = NSManagedObject(entity: entity!, insertInto: context) metric.setValue(value, forKey: "hasViewedAll") do { try context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } static func fetchModel(entity: String) -> [NSManagedObject] { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext var managedObject = [NSManagedObject]() let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) do { let results = try context.fetch(fetchRequest) managedObject = results as! [NSManagedObject] } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return managedObject } static func fetchObject(entity: String, title: String) -> NSManagedObject? { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext var managedObject: NSManagedObject? let fetchPredicate = NSPredicate(format: "title == %@", title) let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) fetchRequest.predicate = fetchPredicate do { let results = try context.fetch(fetchRequest) as! [NSManagedObject] if !results.isEmpty { managedObject = results[0] } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return managedObject } static func fetchObjectBy(id: NSManagedObjectID) -> NSManagedObject? { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext var managedObject: NSManagedObject? do { let result = try context.existingObject(with: id) managedObject = result } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return managedObject } static func deleteObjectBy(id: NSManagedObjectID) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext do { //let result = context.object(with: id) let result = try context.existingObject(with: id) context.delete(result) try context.save() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } static func deleteObject(entity: String, title: String) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let fetchPredicate = NSPredicate(format: "title == %@", title) let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) fetchRequest.predicate = fetchPredicate do { let results = try context.fetch(fetchRequest) as! [NSManagedObject] for object in results { context.delete(object) } try context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } }
mit
364c365c980ded2d83e254e119c6242d
36.294444
100
0.608372
5.199845
false
false
false
false
jverdi/Gramophone
Source/Model/Comment.swift
1
1908
// // Comment.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import protocol Decodable.Decodable import Decodable public struct Comment { public let ID: String public let creationDate: Date public let text: String public let user: User public init(ID: String, creationDate: Date, text: String, user: User) { self.ID = ID self.creationDate = creationDate self.text = text self.user = user } } // MARK: Decodable extension Comment: Decodable { public static func decode(_ json: Any) throws -> Comment { return try Comment( ID: json => "id", creationDate: json => "created_time", text: json => "text", user: json => "from" ) } }
mit
2ea3078d186e95411505e2ce45b87658
33.690909
82
0.689727
4.346241
false
false
false
false
hammy-dev-world/OnebyteSwiftNetwork
Example/OnebyteSwiftNetworkCycle/swift-api-cycle/Classes/AppDelegate/Navigation/AppDelegate+Navigation.swift
1
828
// // AppDelegate+Navigation.swift // swift-api-cycle // // Created by Humayun Sohail on 12/1/16. // Copyright © 2016 Humayun Sohail. All rights reserved. // import Foundation import UIKit extension AppDelegate { // MARK: Init func initAppWindow() -> Void{ self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIColor.white self.window!.makeKeyAndVisible() } // MARK: Public Methods public func configureRootViewController() -> Void{ let firstViewController : ViewController = ViewController(nibName: "ViewController", bundle: nil) let rootNavigationController : UINavigationController = UINavigationController(rootViewController:firstViewController) self.window!.rootViewController = rootNavigationController } }
mit
8b6a09ff45dfd1399e050d9dff037055
30.807692
126
0.713422
4.836257
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/TimeZone.swift
1
13006
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// internal func __NSTimeZoneIsAutoupdating(_ timezone: NSTimeZone) -> Bool { return false } internal func __NSTimeZoneAutoupdating() -> NSTimeZone { return NSTimeZone.local._nsObject } internal func __NSTimeZoneCurrent() -> NSTimeZone { return NSTimeZone.system._nsObject } /** `TimeZone` defines the behavior of a time zone. Time zone values represent geopolitical regions. Consequently, these values have names for these regions. Time zone values also represent a temporal offset, either plus or minus, from Greenwich Mean Time (GMT) and an abbreviation (such as PST for Pacific Standard Time). `TimeZone` provides two static functions to get time zone values: `current` and `autoupdatingCurrent`. The `autoupdatingCurrent` time zone automatically tracks updates made by the user. Note that time zone database entries such as “America/Los_Angeles” are IDs, not names. An example of a time zone name is “Pacific Daylight Time”. Although many `TimeZone` functions include the word “name”, they refer to IDs. Cocoa does not provide any API to change the time zone of the computer, or of other applications. */ public struct TimeZone : Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSTimeZone internal var _wrapped : NSTimeZone internal var _autoupdating : Bool /// The time zone currently used by the system. public static var current : TimeZone { return TimeZone(adoptingReference: __NSTimeZoneCurrent(), autoupdating: false) } /// The time zone currently used by the system, automatically updating to the user's current preference. /// /// If this time zone is mutated, then it no longer tracks the system time zone. /// /// The autoupdating time zone only compares equal to itself. public static var autoupdatingCurrent : TimeZone { return NSTimeZone.local } // MARK: - // /// Returns a time zone initialized with a given identifier. /// /// An example identifier is "America/Los_Angeles". /// /// If `identifier` is an unknown identifier, then returns `nil`. public init?(identifier: String) { if let r = NSTimeZone(name: identifier) { _wrapped = r _autoupdating = false } else { return nil } } @available(*, unavailable, renamed: "init(secondsFromGMT:)") public init(forSecondsFromGMT seconds: Int) { fatalError() } /// Returns a time zone initialized with a specific number of seconds from GMT. /// /// Time zones created with this never have daylight savings and the offset is constant no matter the date. The identifier and abbreviation do NOT follow the POSIX convention (of minutes-west). /// /// - parameter seconds: The number of seconds from GMT. /// - returns: A time zone, or `nil` if a valid time zone could not be created from `seconds`. public init?(secondsFromGMT seconds: Int) { // Seconds boundaries check should actually be placed in NSTimeZone.init(forSecondsFromGMT:) which should return // nil if the check fails. However, NSTimeZone.init(forSecondsFromGMT:) is not a failable initializer, so it // cannot return nil. // It is not a failable initializer because we want to have parity with Darwin's NSTimeZone, which is // Objective-C and has a wrong _Nonnull annotation. if (seconds < -18 * 3600 || 18 * 3600 < seconds) { return nil } _wrapped = NSTimeZone(forSecondsFromGMT: seconds) _autoupdating = false } /// Returns a time zone identified by a given abbreviation. /// /// In general, you are discouraged from using abbreviations except for unique instances such as “GMT”. Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings—for example, “EST” refers to Eastern Time in both the United States and Australia /// /// - parameter abbreviation: The abbreviation for the time zone. /// - returns: A time zone identified by abbreviation determined by resolving the abbreviation to a identifier using the abbreviation dictionary and then returning the time zone for that identifier. Returns `nil` if there is no match for abbreviation. public init?(abbreviation: String) { if let r = NSTimeZone(abbreviation: abbreviation) { _wrapped = r _autoupdating = false } else { return nil } } internal init(reference: NSTimeZone) { if __NSTimeZoneIsAutoupdating(reference) { // we can't copy this or we lose its auto-ness (27048257) // fortunately it's immutable _autoupdating = true _wrapped = reference } else { _autoupdating = false _wrapped = reference.copy() as! NSTimeZone } } internal init(adoptingReference reference: NSTimeZone, autoupdating: Bool) { // this path is only used for types we do not need to copy (we are adopting the ref) _wrapped = reference _autoupdating = autoupdating } // MARK: - // @available(*, unavailable, renamed: "identifier") public var name: String { fatalError() } /// The geopolitical region identifier that identifies the time zone. public var identifier: String { return _wrapped.name } @available(*, unavailable, message: "use the identifier instead") public var data: Data { fatalError() } /// The current difference in seconds between the time zone and Greenwich Mean Time. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func secondsFromGMT(for date: Date = Date()) -> Int { return _wrapped.secondsFromGMT(for: date) } /// Returns the abbreviation for the time zone at a given date. /// /// Note that the abbreviation may be different at different dates. For example, during daylight saving time the US/Eastern time zone has an abbreviation of “EDT.” At other times, its abbreviation is “EST.” /// - parameter date: The date to use for the calculation. The default value is the current date. public func abbreviation(for date: Date = Date()) -> String? { return _wrapped.abbreviation(for: date) } /// Returns a Boolean value that indicates whether the receiver uses daylight saving time at a given date. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func isDaylightSavingTime(for date: Date = Date()) -> Bool { return _wrapped.isDaylightSavingTime(for: date) } /// Returns the daylight saving time offset for a given date. /// /// - parameter date: The date to use for the calculation. The default value is the current date. public func daylightSavingTimeOffset(for date: Date = Date()) -> TimeInterval { return _wrapped.daylightSavingTimeOffset(for: date) } /// Returns the next daylight saving time transition after a given date. /// /// - parameter date: A date. /// - returns: The next daylight saving time transition after `date`. Depending on the time zone, this function may return a change of the time zone's offset from GMT. Returns `nil` if the time zone of the receiver does not observe daylight savings time as of `date`. public func nextDaylightSavingTimeTransition(after date: Date) -> Date? { return _wrapped.nextDaylightSavingTimeTransition(after: date) } /// Returns an array of strings listing the identifier of all the time zones known to the system. public static var knownTimeZoneIdentifiers : [String] { return NSTimeZone.knownTimeZoneNames } /// Returns the mapping of abbreviations to time zone identifiers. public static var abbreviationDictionary : [String : String] { get { return NSTimeZone.abbreviationDictionary } set { NSTimeZone.abbreviationDictionary = newValue } } /// Returns the time zone data version. public static var timeZoneDataVersion : String { return NSTimeZone.timeZoneDataVersion } /// Returns the date of the next (after the current instant) daylight saving time transition for the time zone. Depending on the time zone, the value of this property may represent a change of the time zone's offset from GMT. Returns `nil` if the time zone does not currently observe daylight saving time. public var nextDaylightSavingTimeTransition: Date? { return _wrapped.nextDaylightSavingTimeTransition } @available(*, unavailable, renamed: "localizedName(for:locale:)") public func localizedName(_ style: NSTimeZone.NameStyle, locale: Locale?) -> String? { fatalError() } /// Returns the name of the receiver localized for a given locale. public func localizedName(for style: NSTimeZone.NameStyle, locale: Locale?) -> String? { return _wrapped.localizedName(style, locale: locale) } // MARK: - public func hash(into hasher: inout Hasher) { if _autoupdating { hasher.combine(false) } else { hasher.combine(true) hasher.combine(_wrapped) } } public static func ==(lhs: TimeZone, rhs: TimeZone) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } } extension TimeZone : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { private var _kindDescription : String { if (self == TimeZone.current) { return "current" } else { return "fixed" } } public var customMirror : Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "identifier", value: identifier)) c.append((label: "kind", value: _kindDescription)) c.append((label: "abbreviation", value: abbreviation() as Any)) c.append((label: "secondsFromGMT", value: secondsFromGMT())) c.append((label: "isDaylightSavingTime", value: isDaylightSavingTime())) return Mirror(self, children: c, displayStyle: .struct) } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription : String { return "\(identifier) (\(_kindDescription))" } } extension TimeZone : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSTimeZone { // _wrapped is immutable return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(NSTimeZone.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) -> Bool { result = TimeZone(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSTimeZone?) -> TimeZone { var result: TimeZone? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension TimeZone : Codable { private enum CodingKeys : Int, CodingKey { case identifier } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifier = try container.decode(String.self, forKey: .identifier) guard let timeZone = TimeZone(identifier: identifier) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Invalid TimeZone identifier.")) } self = timeZone } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.identifier, forKey: .identifier) } }
apache-2.0
ff1a5f2ab1e4419e74316b0e8b160672
41.12987
319
0.657753
5.060842
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/URIFixup.swift
1
2854
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class URIFixup { static func getURL(_ entry: String) -> URL? { if let url = URL(string: entry), InternalURL.isValid(url: url) { return URL(string: entry) } let trimmed = entry.trimmingCharacters(in: .whitespacesAndNewlines) guard var escaped = trimmed.addingPercentEncoding(withAllowedCharacters: .URLAllowed) else { return nil } escaped = replaceBrackets(url: escaped) // Then check if the URL includes a scheme. This will handle // all valid requests starting with "http://", "about:", etc. // However, we ensure that the scheme is one that is listed in // the official URI scheme list, so that other such search phrases // like "filetype:" are recognised as searches rather than URLs. if let url = punycodedURL(escaped), url.schemeIsValid { return url } // If there's no scheme, we're going to prepend "http://". First, // make sure there's at least one "." in the host. This means // we'll allow single-word searches (e.g., "foo") at the expense // of breaking single-word hosts without a scheme (e.g., "localhost"). if trimmed.range(of: ".") == nil { return nil } if trimmed.range(of: " ") != nil { return nil } // If there is a ".", prepend "http://" and try again. Since this // is strictly an "http://" URL, we also require a host. if let url = punycodedURL("http://\(escaped)"), url.host != nil { return url } return nil } static func punycodedURL(_ string: String) -> URL? { var string = string if string.filter({ $0 == "#" }).count > 1 { string = replaceHashMarks(url: string) } guard let url = URL(string: string) else { return nil } var components = URLComponents(url: url, resolvingAgainstBaseURL: false) if AppConstants.MOZ_PUNYCODE { let host = components?.host?.utf8HostToAscii() components?.host = host } return components?.url } static func replaceBrackets(url: String) -> String { return url.replacingOccurrences(of: "[", with: "%5B").replacingOccurrences(of: "]", with: "%5D") } static func replaceHashMarks(url: String) -> String { guard let firstIndex = url.firstIndex(of: "#") else { return String() } let start = url.index(firstIndex, offsetBy: 1) return url.replacingOccurrences(of: "#", with: "%23", range: start..<url.endIndex) } }
mpl-2.0
a8edce17cd546692f4ffb34e62af61f8
37.053333
104
0.597407
4.343988
false
false
false
false
nathawes/swift
test/Interop/Cxx/operators/non-member-out-of-line.swift
7
676
// RUN: %empty-directory(%t) // RUN: %target-clang -c %S/Inputs/non-member-out-of-line.cpp -I %S/Inputs -o %t/non-member-out-of-line.o -std=c++17 // RUN: %target-build-swift %s -I %S/Inputs -o %t/non-member-out-of-line %t/non-member-out-of-line.o -Xfrontend -enable-cxx-interop // RUN: %target-codesign %t/non-member-out-of-line // RUN: %target-run %t/non-member-out-of-line // // REQUIRES: executable_test import NonMemberOutOfLine import StdlibUnittest var OperatorsTestSuite = TestSuite("Operators") OperatorsTestSuite.test("plus") { let lhs = IntBox(value: 42) let rhs = IntBox(value: 23) let result = lhs + rhs expectEqual(65, result.value) } runAllTests()
apache-2.0
6be50e69818a2664c55579bc82112b9c
28.391304
131
0.702663
2.804979
false
true
false
false
WangYang-iOS/YiDeXuePin_Swift
DiYa/DiYa/Class/Home/Model/HomeModel.swift
1
3489
// // HomeModel.swift // DiYa // // Created by wangyang on 2017/11/8. // Copyright © 2017年 wangyang. All rights reserved. // import Foundation @objcMembers class HomeModel: NSObject { var categoryName = "" var category = "" var goodsList = [GoodsModel]() var announcement = AnnouncementModel() override var description: String { return self.yy_modelDescription() } /// MJExtension中解析嵌套数组类型需要加上该方法 /// /// - Returns: returns override static func mj_objectClassInArray() -> [AnyHashable : Any]! { return ["goodsList":GoodsModel.self] } /// yymodel中解析嵌套数组类型需要加上该方法 /// /// - Returns: returns static func modelContainerPropertyGenericClass() -> [AnyHashable : Any]! { return ["goodsList":GoodsModel.self] } } @objcMembers class GoodsModel: NSObject { var category = "" var id = "" var marketPrice = "" var picture = "" var price = "" var title = "" var sales = "" var inventory = "" var cartId = "" var skuId = "" var discountPrice = "" var skuName = "" var skuValue = "" var skuState = "" var number = "" var isInvalid : Bool = false var name = "" var isHot = "" var sort = "" var parentId = "" var isSelected : Bool = false override var description: String { return self.yy_modelDescription() } } @objcMembers class AnnouncementModel: NSObject { var goodsId = "" var id = "" var jumpUrl = "" var picture = "" var type = "" var title = "" override var description: String { return self.yy_modelDescription() } } @objcMembers class CategoryModelList: NSObject { var id = "" var isHot = "" var sort = "" var name = "" var picture = "" var isSelected : Bool = false override var description: String { return self.yy_modelDescription() } } @objcMembers class CategoryModel:NSObject { var id = "" var parentId = "" var name = "" var goodsCategoryList = [GoodsModel]() override var description: String { return self.yy_modelDescription() } override static func mj_objectClassInArray() -> [AnyHashable : Any]! { return ["goodsList":GoodsModel.self] } static func modelContainerPropertyGenericClass() -> [AnyHashable : Any]! { return ["goodsCategoryList":GoodsModel.self] } } @objcMembers class SkuCategoryModel: NSObject { var value = "" var name = "" override var description: String { return self.yy_modelDescription() } } @objcMembers class GoodsSkuModel: NSObject { var goodsId = "" var id = "" var discount = "" var discountPrice = "" var inventory = "" var price = "" var skuName = "" var skuValue = "" override var description: String { return self.yy_modelDescription() } } @objcMembers class ShopcartModel: NSObject { var cartGoodsFormList = [GoodsModel]() var categoryId = "" var categoryName = "" var type = "" var isSelected : Bool = false var isEditing : Bool = false var isHidden : Bool = false override var description: String { return self.yy_modelDescription() } static func modelContainerPropertyGenericClass() -> [AnyHashable : Any]! { return ["cartGoodsFormList":GoodsModel.self] } }
mit
dc8695831aeb0e4a9a9ce6e7e5aeb508
22.278912
78
0.601403
4.198773
false
false
false
false
cuappdev/tcat-ios
TCAT/Views/WhatsNewHeaderView.swift
1
11347
// // WhatsNewPopupView.swift // TCAT // // Created by Omar Rasheed on 9/26/18. // Copyright © 2018 cuappdev. All rights reserved. // import SnapKit import UIKit protocol WhatsNewDelegate: class { func dismissView(card: WhatsNewCard) func getCurrentHomeViewController() -> HomeMapViewController } class WhatsNewHeaderView: UIView { private var card: WhatsNewCard private weak var whatsNewDelegate: WhatsNewDelegate? /// Whether a promotion is being used for the card var isPromotion: Bool /// e.g. "New In Ithaca Transit" blue label private var descriptionLabel: UILabel! private var smallHeaderLabel: UILabel! private var titleLabel: UILabel! private var buttonContainerView: UIView! private var dismissButton: UIButton! private var primaryButton: UIButton? private var secondaryButton: UIButton? private var buttonToBottom: Constraint? private var buttonToUpdateDesc: Constraint? private var titleToTop: Constraint? private var updateDescToUpdateName: Constraint? private var updateDescriptionHeight: Constraint? private var updateNameToTitle: Constraint? private let containerPadding = UIEdgeInsets(top: 16, left: 16, bottom: 0, right: 16) init(card: WhatsNewCard, isPromotion: Bool = false) { self.card = card self.isPromotion = isPromotion super.init(frame: .zero) backgroundColor = Colors.white layer.cornerRadius = 16 clipsToBounds = true createWhatsNewHeader() createDismissButton() createUpdateTitle(title: card.title) createUpdateDescription(desc: card.description) createButtonContainerView() createPrimaryActionButton() createSecondaryActionButton() setupConstraints() } func createWhatsNewHeader() { smallHeaderLabel = UILabel() smallHeaderLabel.text = card.label.uppercased() smallHeaderLabel.font = .getFont(.semibold, size: 12) smallHeaderLabel.textColor = Colors.tcatBlue addSubview(smallHeaderLabel) } func createDismissButton() { dismissButton = LargeTapTargetButton(extendBy: 32) dismissButton.setImage(UIImage(named: "x"), for: .normal) dismissButton.tintColor = Colors.metadataIcon dismissButton.addTarget(self, action: #selector(dismissButtonPressed), for: .touchUpInside) addSubview(dismissButton) } func createUpdateTitle(title: String) { titleLabel = UILabel() titleLabel.text = card.title titleLabel.font = .getFont(.bold, size: 18) addSubview(titleLabel) } func createUpdateDescription(desc: String) { descriptionLabel = UILabel() descriptionLabel.text = card.description descriptionLabel.font = .getFont(.regular, size: 14) descriptionLabel.textColor = Colors.metadataIcon descriptionLabel.numberOfLines = 0 descriptionLabel.textAlignment = .center descriptionLabel.isUserInteractionEnabled = true addSubview(descriptionLabel) } func createButtonContainerView() { buttonContainerView = UIView() addSubview(buttonContainerView) } func createPrimaryActionButton() { guard let title = card.primaryActionTitle else { return } let primaryButton = UIButton() primaryButton.setTitle(title, for: .normal) primaryButton.titleLabel?.font = .getFont(.semibold, size: 14) primaryButton.addTarget(self, action: #selector(primaryButtonTapped), for: .touchUpInside) primaryButton.backgroundColor = Colors.tcatBlue primaryButton.setTitleColor(Colors.white, for: .normal) primaryButton.layer.cornerRadius = primaryButton.intrinsicContentSize.height / 2 primaryButton.clipsToBounds = true buttonContainerView.addSubview(primaryButton) self.primaryButton = primaryButton } func createSecondaryActionButton() { guard let title = card.secondaryActionTitle else { return } let secondaryButton = UIButton() secondaryButton.setTitle(title, for: .normal) secondaryButton.titleLabel?.font = .getFont(.medium, size: 14) secondaryButton.addTarget(self, action: #selector(secondaryButtonTapped), for: .touchUpInside) secondaryButton.backgroundColor = Colors.metadataIcon secondaryButton.setTitleColor(Colors.white, for: .normal) secondaryButton.layer.cornerRadius = secondaryButton.intrinsicContentSize.height / 2 secondaryButton.clipsToBounds = true buttonContainerView.addSubview(secondaryButton) self.secondaryButton = secondaryButton } func setupConstraints() { let titleToTopPadding: CGFloat = 16 smallHeaderLabel.snp.makeConstraints { (make) in titleToTop = make.top.equalToSuperview().offset(titleToTopPadding).constraint make.centerX.equalToSuperview() make.height.equalTo(smallHeaderLabel.intrinsicContentSize.height) make.width.equalTo(smallHeaderLabel.intrinsicContentSize.width) } let labelToTitlePadding: CGFloat = 8 titleLabel.snp.makeConstraints { (make) in updateNameToTitle = make.top.equalTo(smallHeaderLabel.snp.bottom).offset(labelToTitlePadding).constraint make.centerX.equalToSuperview() make.height.equalTo(titleLabel.intrinsicContentSize.height) make.width.equalTo(titleLabel.intrinsicContentSize.width) } let titletoDescriptionPadding: CGFloat = 6 let descriptionInset: CGFloat = 32 descriptionLabel.snp.makeConstraints { (make) in updateDescToUpdateName = make.top.equalTo(titleLabel.snp.bottom).offset(titletoDescriptionPadding).constraint make.leading.trailing.equalToSuperview().inset(descriptionInset) if let description = descriptionLabel.text { // Take total width and subtract various insets used in layout let headerViewCardPadding = containerPadding.left + containerPadding.right let widthValue = UIScreen.main.bounds.width - headerViewCardPadding - (descriptionInset * 2) let heightValue = ceil(description.heightWithConstrainedWidth(width: widthValue, font: descriptionLabel.font)) updateDescriptionHeight = make.height.equalTo(ceil(heightValue)).constraint } } let descriptionToButtonPadding: CGFloat = 12 let buttonToBottomPadding: CGFloat = 16 buttonContainerView.snp.makeConstraints { (make) in buttonToUpdateDesc = make.top.equalTo(descriptionLabel.snp.bottom).offset(descriptionToButtonPadding).constraint buttonToBottom = make.bottom.equalToSuperview().inset(buttonToBottomPadding).constraint make.centerX.equalToSuperview() } dismissButton.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(titleToTopPadding) make.right.equalToSuperview().inset(titleToTopPadding) make.width.height.equalTo(14) } // Padding for space between buttons let buttonWidthPadding: CGFloat = (secondaryButton != nil) ? 16 : 0 let buttonWidth: CGFloat = 80 primaryButton?.snp.makeConstraints { (make) in make.centerY.top.bottom.right.equalToSuperview() make.width.equalTo(buttonWidth) if secondaryButton == nil { make.left.equalToSuperview() } } secondaryButton?.snp.makeConstraints { (make) in make.centerY.top.bottom.left.equalToSuperview() make.width.equalTo(buttonWidth) if let primaryButton = primaryButton { make.right.equalTo(primaryButton.snp.left).offset(-buttonWidthPadding) } else { make.right.equalToSuperview() } } } func calculateCardHeight() -> CGFloat { guard let titleToTop = titleToTop, let updateNameToTitle = updateNameToTitle, let updateDescToUpdateName = updateDescToUpdateName, let updateDescriptionHeight = updateDescriptionHeight, let actionButtonToUpdateDesc = buttonToUpdateDesc, let actionButtonToBottom = buttonToBottom else { return 0 } let titleToTopVal = titleToTop.layoutConstraints[0].constant let titleHeight = smallHeaderLabel.intrinsicContentSize.height let titleSpace = titleToTopVal + titleHeight let updateNameToTitleVal = updateNameToTitle.layoutConstraints[0].constant let updateNameHeight = titleLabel.intrinsicContentSize.height let updateNameSpace = updateNameToTitleVal + updateNameHeight let updateDescToUpdateNameVal = updateDescToUpdateName.layoutConstraints[0].constant let updateDescHeight = updateDescriptionHeight.layoutConstraints[0].constant let updateDescSpace = updateDescToUpdateNameVal + updateDescHeight let actionButtonToUpdateDescVal = actionButtonToUpdateDesc.layoutConstraints[0].constant let buttonHeight = primaryButton?.intrinsicContentSize.height ?? secondaryButton?.intrinsicContentSize.height ?? 0 let actionButtonSpace = actionButtonToUpdateDescVal + buttonHeight let bottomOffset = -actionButtonToBottom.layoutConstraints[0].constant return ceil(titleSpace + updateNameSpace + updateDescSpace + actionButtonSpace + bottomOffset) } @objc func primaryButtonTapped() { if let homeViewController = whatsNewDelegate?.getCurrentHomeViewController(), let primaryAction = card.primaryActionHandler { primaryAction(homeViewController) let payload = PrimaryActionTappedPayload(actionDescription: card.title) Analytics.shared.log(payload) } if !isPromotion { self.whatsNewDelegate?.dismissView(card: card) } } @objc func secondaryButtonTapped() { if let homeViewController = whatsNewDelegate?.getCurrentHomeViewController(), let secondaryAction = card.secondaryActionHandler { secondaryAction(homeViewController) let payload = SecondaryActionTappedPayload(actionDescription: card.title) Analytics.shared.log(payload) } if !isPromotion { self.whatsNewDelegate?.dismissView(card: card) } } func open(_ link: String, optionalAppLink: String?, linkOpened: @escaping (() -> Void)) { if let appLink = optionalAppLink, let appURL = URL(string: appLink), UIApplication.shared.canOpenURL(appURL) { // Open link in an installed app. UIApplication.shared.open(appURL, options: [:]) { _ in linkOpened() } } else if let webURL = URL(string: link) { // Open link in Safari. UIApplication.shared.open(webURL, options: [:]) { _ in linkOpened() } } } @objc func dismissButtonPressed() { whatsNewDelegate?.dismissView(card: card) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
56e39b175f3ae672e833fc6b964a8bfb
37.591837
126
0.681033
5.257646
false
false
false
false
sebastiangoetz/slr-toolkit
ios-client/SLR Toolkit/Views/Actions/FilterEntriesView.swift
1
4295
import SwiftUI /// View to let users filter all entries for which they haven't made a decision yet. struct FilterEntriesView: View { /// The list of entries with an outstanding decision. private let entries: [Entry] @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.presentationMode) private var presentationMode /// Horizontal drag amount. @State private var dragAmount: CGFloat = 0 /// Vertical card offset. Used to move next card from the bottom into view. @State private var verticalOffset: CGFloat = 0 /// The decided entries of this session. Used for undoing. @State private var undoStack = [Entry]() init(entries: [Entry]) { self.entries = entries } var body: some View { NavigationView { HStack { Spacer() VStack { ZStack { if let entry = entries.first { // to prevent crash after last unfiltered entry is removed EntryCard(entry: entry) // TODO make sure ScrollView scrolls } Color.red.opacity(Double(-dragAmount) / 2500) Color.green.opacity(Double(dragAmount) / 2500) } .cornerRadius(20) .zIndex(1) .offset(x: 1.5 * dragAmount, y: verticalOffset) .rotationEffect(Angle(degrees: Double(dragAmount / 40))) .gesture( DragGesture() .onChanged { dragAmount = $0.translation.width } .onEnded { _ in dragGestureEnded() } ) HStack { Text("← Discard") Spacer() Text(entries.first?.citationKey ?? "") Spacer() Text("Keep →") } .padding(EdgeInsets(top: 8, leading: 12, bottom: 20, trailing: 12)) .font(.footnote) .foregroundColor(.secondary) } .frame(maxWidth: 512) .padding([.top, .leading, .trailing], 24) Spacer() } .background(Color(.systemGroupedBackground).ignoresSafeArea()) .navigationBarTitle("Filter (\(entries.count) to go)", displayMode: .inline) .toolbar { ToolbarItem(placement: .navigationBarLeading) { if !undoStack.isEmpty { Button("Undo") { undoStack.popLast()?.decision = .outstanding } } else { EmptyView() // Workaround: if statements not allowed in ToolbarContentBuilder } } ToolbarItem(placement: .confirmationAction) { Button("Done") { presentationMode.wrappedValue.dismiss() } } } } } private func dragGestureEnded() { let screenSize = UIScreen.main.bounds if abs(dragAmount) < screenSize.width / 3 { withAnimation { dragAmount = 0 } } else { guard let entry = entries.first else { return } // Modify entry entry.decision = dragAmount > 0 ? .keep : .discard managedObjectContext.saveAndLogError() // Animate card out of the screen withAnimation { dragAmount = (dragAmount > 0 ? 1 : -1) * screenSize.width } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { if entries.count <= 1 { presentationMode.wrappedValue.dismiss() } else { // Prepare next card dragAmount = 0 verticalOffset = screenSize.height withAnimation(.spring()) { verticalOffset = 0 } } } undoStack.append(entry) } } }
epl-1.0
e9f4cb53ee64308e1c5bb5995c79ba01
36.313043
114
0.474481
5.775236
false
false
false
false
SwiftKit/Reactant
Tests/Core/Styling/StyleableTest.swift
2
2309
// // StyleableTest.swift // ReactantTests // // Created by Filip Dolnik on 18.10.16. // Copyright © 2016 Brightify. All rights reserved. // import Quick import Nimble import Reactant class StyleableTest: QuickSpec { override func spec() { var view: UIView! beforeEach { view = UIView() } describe("applyStyle") { it("applies style") { view.apply(style: Styles.background) view.apply(style: Styles.tint) self.assert(view: view) } } describe("applyStyles") { it("applies styles") { view.apply(styles: [Styles.background, Styles.tint]) self.assert(view: view) } it("applies styles with vararg") { view.apply(styles: Styles.background, Styles.tint) self.assert(view: view) } } describe("styled") { it("applies styles") { let styledView = view.styled(using: [Styles.background, Styles.tint]) self.assert(view: styledView) } it("applies styles with vararg") { let styledView = view.styled(using: Styles.background, Styles.tint) self.assert(view: styledView) } } describe("with") { it("applies style") { let styledView = view.with { $0.backgroundColor = UIColor.blue $0.tintColor = UIColor.black } self.assert(view: styledView) } } } private func assert(view: UIView, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(UIColor.blue, view.backgroundColor, file: file, line: line) XCTAssertEqual(UIColor.black, view.tintColor, file: file, line: line) } } extension StyleableTest { fileprivate struct Styles { static func background(_ view: UIView) { view.backgroundColor = UIColor.blue } static func tint(_ view: UIView) { view.tintColor = UIColor.black } } }
mit
d079477bee140bed9d33b9a13a39e68e
27.146341
87
0.498267
4.858947
false
false
false
false
Hidebush/McBlog
McBlog/McBlog/Classes/Model/UserAccount.swift
1
3976
// // UserAccount.swift // McBlog // // Created by admin on 16/4/28. // Copyright © 2016年 郭月辉. All rights reserved. // import UIKit class UserAccount: NSObject, NSCoding { class var userLogon: Bool { return loadAccount() != nil } var access_token: String? //过期时间 var expireDate: NSDate? var expires_in: NSTimeInterval = 0 { didSet { expireDate = NSDate(timeIntervalSinceNow: expires_in) } } var uid: String? // 用户头像 var avatar_large: String? // 显示名字 var name: String? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) // expireDate = NSDate(timeIntervalSinceNow: expires_in!) } // MARK: - 归档&解裆 static private let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist") // MARK - 保存 func saveAccount() { NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath) } // MARK - 读取 private static var userAccount: UserAccount? //私有变量记录 class func loadAccount() -> UserAccount? { // if userAccount == nil { // if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount { // // 判断账户是否过期 // if account.expireDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending { // return account // } // // } // } else { // if userAccount!.expireDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending { // return userAccount // } // } if userAccount == nil { userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount } if let date = userAccount?.expireDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending { userAccount = nil } return userAccount } func loadUserInfo(finished: (error: NSError?) -> ()) { NetWorkTools.shareTools.loadUserInfo(uid!) { (result, error) in if error != nil { finished(error: error) return } self.name = result!["name"] as? String self.avatar_large = result!["avatar_large"] as? String self.saveAccount() finished(error: nil) } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeObject(expireDate, forKey: "expireDate") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expireDate = aDecoder.decodeObjectForKey("expireDate") as? NSDate expires_in = aDecoder.decodeDoubleForKey("expires_in") uid = aDecoder.decodeObjectForKey("uid") as? String name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String { let perporties = ["access_token", "expires_in", "expireDate", "uid", "name", "avatar_large"] return "\(dictionaryWithValuesForKeys(perporties))" } }
mit
fa747a002d8d2a2668ea09bb318e6fad
30.959016
226
0.594768
4.941698
false
false
false
false
fespinoza/linked-ideas-osx
LinkedIdeas/UI/StateManager.swift
1
8213
// // StateManager.swift // LinkedIdeas // // Created by Felipe Espinoza Castillo on 02/10/2016. // Copyright © 2016 Felipe Espinoza Dev. All rights reserved. // import Foundation import LinkedIdeas_Shared enum CanvasTransitionError: Error { case invalidTransition(message: String) } protocol StateManagerDelegate: class { func transitionSuccesfull() func transitionedToNewConcept(fromState: CanvasState) func transitionedToCanvasWaiting(fromState: CanvasState) func transitionedToCanvasWaitingSavingConcept(fromState: CanvasState, point: CGPoint, text: NSAttributedString) func transitionedToCanvasWaitingDeletingElements(fromState: CanvasState) func transitionedToSelectedElement(fromState: CanvasState) func transitionedToSelectedElementSavingChanges(fromState: CanvasState) func transitionedToEditingElement(fromState: CanvasState) func transitionedToMultipleSelectedElements(fromState: CanvasState) func transitionedToResizingConcept(fromState: CanvasState) } enum CanvasState { case canvasWaiting case newConcept(point: CGPoint) case selectedElement(element: Element) case editingElement(element: Element) case multipleSelectedElements(elements: [Element]) case resizingConcept(concept: Concept, withHandler: Handler, initialArea: CGRect) func isSimilar(to state: CanvasState) -> Bool { return state.description == self.description } } extension CanvasState: CustomStringConvertible { var description: String { switch self { case .canvasWaiting: return "canvasWaiting" case .editingElement(let element): return "editingElement: \(element.debugDescription)" case .multipleSelectedElements(let elements): return "multipleSelectedElements: \(elements)" case .newConcept(let point): return "newConcept: at \(point)" case .resizingConcept: return "resizingConcept" case .selectedElement(let element): return "selectedElement: \(element.debugDescription)" } } } extension CanvasState: Equatable { static func == (lhs: CanvasState, rhs: CanvasState) -> Bool { switch (lhs, rhs) { case (.newConcept(let a), .newConcept(let b)) where a == b: return true case (.canvasWaiting, .canvasWaiting): return true case (.selectedElement(let a), .selectedElement(let b)): return a.identifier == b.identifier case (.editingElement(let a), .editingElement(let b)): return a.identifier == b.identifier case (.multipleSelectedElements(let a), .multipleSelectedElements(let b)): return a.map { $0.identifier } == b.map { $0.identifier } case (.resizingConcept(let a1, _, _), .resizingConcept(let a2, _, _)): return a1.identifier == a2.identifier default: return false } } } class StateManager { var currentState: CanvasState { didSet { print(">>>>>>> Transitioned to \(currentState)") } } weak var delegate: StateManagerDelegate? init(initialState: CanvasState) { currentState = initialState } public func toNewConcept(atPoint point: CGPoint) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .canvasWaiting, .newConcept, .selectedElement: return true default: return false } } try transition(toState: .newConcept(point: point), withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToNewConcept(fromState: oldState) } } public func toCanvasWaiting() throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .canvasWaiting, .newConcept, .editingElement, .selectedElement, .multipleSelectedElements: return true default: return false } } try transition(toState: .canvasWaiting, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToCanvasWaiting(fromState: oldState) } } public func toCanvasWaiting(savingConceptWithText text: NSAttributedString) throws { let oldState = currentState switch currentState { case .newConcept(let point): currentState = .canvasWaiting delegate?.transitionedToCanvasWaitingSavingConcept(fromState: oldState, point: point, text: text) delegate?.transitionSuccesfull() default: throw CanvasTransitionError.invalidTransition( message: "there is no transition from \(currentState) to 'canvasWaiting' saving concept" ) } } public func toCanvasWaiting(deletingElements elements: [Element]) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .selectedElement, .multipleSelectedElements: return true default: return false } } try transition(toState: .canvasWaiting, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToCanvasWaitingDeletingElements(fromState: oldState) } } public func toSelectedElement(element: Element) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .canvasWaiting, .newConcept, .selectedElement, .editingElement, .multipleSelectedElements, .resizingConcept: return true } } let state = CanvasState.selectedElement(element: element) try transition(toState: state, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToSelectedElement(fromState: oldState) } } public func toSelectedElementSavingChanges(element: Element) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .editingElement: return true default: return false } } let state = CanvasState.selectedElement(element: element) try transition(toState: state, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToSelectedElementSavingChanges(fromState: oldState) } } public func toMultipleSelectedElements(elements: [Element]) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .canvasWaiting, .selectedElement, .multipleSelectedElements: return true default: return false } } let state = CanvasState.multipleSelectedElements(elements: elements) try transition(toState: state, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToMultipleSelectedElements(fromState: oldState) } } public func toEditingElement(element: Element) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .selectedElement: return true default: return false } } let state = CanvasState.editingElement(element: element) try transition(toState: state, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToEditingElement(fromState: oldState) } } public func toResizingConcept(concept: Concept, handler: Handler) throws { func isValidTransition(fromState: CanvasState) -> Bool { switch fromState { case .selectedElement: return true default: return false } } let newState = CanvasState.resizingConcept( concept: concept, withHandler: handler, initialArea: concept.area ) try transition(toState: newState, withValidtransitions: isValidTransition) { (oldState) in delegate?.transitionedToResizingConcept(fromState: oldState) } } private func transition( toState: CanvasState, withValidtransitions isValidTransition: (CanvasState) -> Bool, onSuccess: (CanvasState) -> Void ) throws { let fromState = currentState guard isValidTransition(fromState) else { throw CanvasTransitionError.invalidTransition( message: "there is no transition from \(fromState) to '\(toState)'" ) } currentState = toState onSuccess(fromState) delegate?.transitionSuccesfull() } }
mit
82eff0f3ff2b353f67d5dd7ddd1923b9
30.463602
113
0.702874
4.66326
false
false
false
false
sammyd/Concurrency-VideoSeries
prototyping/GCD.playground/Pages/Barriers.xcplaygroundpage/Contents.swift
1
3192
//: [Previous](@previous) import Foundation import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true class Person { private var firstName: String private var lastName: String init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } func changeName(firstName firstName: String, lastName: String) { randomDelay(0.1) self.firstName = firstName randomDelay(1) self.lastName = lastName } var name: String { return "\(firstName) \(lastName)" } } let nameList = [("Brian", "Biggles"), ("Charlie", "Cheesecake"), ("Delia", "Dingle"), ("Eva", "Evershed"), ("Freddie", "Frost")] let workerQueue = dispatch_queue_create("com.raywenderlich.worker", DISPATCH_QUEUE_CONCURRENT) let nameChangeGroup = dispatch_group_create() let nameChangingPerson = Person(firstName: "Anna", lastName: "Adams") for name in nameList { dispatch_group_async(nameChangeGroup, workerQueue) { nameChangingPerson.changeName(firstName: name.0, lastName: name.1) print(nameChangingPerson.name) } } dispatch_group_notify(nameChangeGroup, dispatch_get_main_queue()) { print("Final name: \(nameChangingPerson.name)") } let threadSafeNameGroup = dispatch_group_create() class ThreadSafePerson: Person { let isolationQueue = dispatch_queue_create("com.raywenderlich.person.isolation", DISPATCH_QUEUE_CONCURRENT) override func changeName(firstName firstName: String, lastName: String) { dispatch_barrier_async(isolationQueue) { super.changeName(firstName: firstName, lastName: lastName) } } override var name: String { var result = "" dispatch_sync(isolationQueue) { result = super.name } return result } } let threadSafePerson = ThreadSafePerson(firstName: "Anna", lastName: "Adams") for name in nameList { dispatch_group_async(threadSafeNameGroup, workerQueue) { threadSafePerson.changeName(firstName: name.0, lastName: name.1) print(threadSafePerson.name) } } dispatch_group_notify(threadSafeNameGroup, dispatch_get_main_queue()) { print("Final threadsafe name: \(threadSafePerson.name)") //XCPlaygroundPage.currentPage.finishExecution() } // Challenge? // Make the following threadsafe class Number { var value: Int var name: String init(value: Int, name: String) { self.value = value self.name = name } func changeNumber(value: Int, name: String) { randomDelay(0.1) self.value = value randomDelay(0.5) self.name = name } var number: String { return "\(value) :: \(name)" } } let numberGroup = dispatch_group_create() let numberArray = [(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"), (6, "six")] let changingNumber = Number(value: 0, name: "zero") for pair in numberArray { dispatch_group_async(numberGroup, workerQueue) { changingNumber.changeNumber(pair.0, name: pair.1) print("Current number: \(changingNumber.number)") } } dispatch_group_notify(threadSafeNameGroup, dispatch_get_main_queue()) { print("Final number: \(changingNumber.number)") XCPlaygroundPage.currentPage.finishExecution() } //: [Next](@next)
mit
2d0c7117e6fea7d1877234a8f28834f8
22.820896
128
0.698622
3.728972
false
false
false
false
MukeshKumarS/Swift
test/Parse/foreach.swift
3
1334
// RUN: %target-parse-verify-swift struct IntRange<Int> : SequenceType, GeneratorType { typealias Element = (Int, Int) func next() -> (Int, Int)? {} typealias Generator = IntRange<Int> func generate() -> IntRange<Int> { return self } } func for_each(r: Range<Int>, iir: IntRange<Int>) { var sum = 0 // Simple foreach loop, using the variable in the body for i in r { sum = sum + i } // Check scoping of variable introduced with foreach loop i = 0 // expected-error{{use of unresolved identifier 'i'}} // For-each loops with two variables and varying degrees of typedness for (i, j) in iir { sum = sum + i + j } for (i, j) in iir { sum = sum + i + j } for (i, j) : (Int, Int) in iir { sum = sum + i + j } // Parse errors for i r { // expected-error 2{{expected ';' in 'for' statement}} expected-error {{use of unresolved identifier 'i'}} } for i in r sum = sum + i; // expected-error{{expected '{' to start the body of for-each loop}} for let x in 0..<10 {} // expected-error {{'let' pattern is already in an immutable context}} {{7-11=}} // FIXME: rdar://problem/23378003 // This will eventually become an error. for var x in 0..<10 {} // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{7-11=}} }
apache-2.0
e713d1c4dcb749fe063cf3d1ee23a5f3
31.536585
147
0.630435
3.473958
false
false
false
false
harungunaydin/Agenda-Master
FoldingCell/ViewController/FilterViewController.swift
1
5433
// // FilterViewController.swift // Agenda Master // // Created by Harun Gunaydin on 5/17/16. import UIKit class FilterViewController: UIViewController { @IBOutlet weak var agendaMasterImage: UIImageView! @IBOutlet weak var googleImage: UIImageView! @IBOutlet weak var appleImage: UIImageView! @IBAction func resetButtonDidTapped(sender: AnyObject) { let alert = UIAlertController(title: "RESET", message: "Do you want to bring all deleted events back?", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "YES", style: .Default, handler: { (action) -> Void in print("Chose - YES") self.bringDeletedEventsBack() self.dismissViewControllerAnimated(true, completion: nil) })) alert.addAction(UIAlertAction(title: "NO", style: .Default, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } func bringDeletedEventsBack() { print("geldim") if let deletedItems = NSUserDefaults.standardUserDefaults().objectForKey("deletedItems") as? [String] { print("girdim") for event in deletedItems { NSUserDefaults.standardUserDefaults().setObject(false, forKey: "deletedEventForId_" + event) } NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "deletedItems") dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } } func changeStateOfAgendaMaster() { dispatch_async(dispatch_get_main_queue() , { if self.agendaMasterImage.alpha < 1 { self.agendaMasterImage.alpha = 1 NSUserDefaults.standardUserDefaults().setObject(true, forKey: "Agenda Master_filtered") } else { self.agendaMasterImage.alpha = 0.15 NSUserDefaults.standardUserDefaults().setObject(false, forKey: "Agenda Master_filtered") } }) dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } func changeStateOfGoogle() { dispatch_async(dispatch_get_main_queue() , { if self.googleImage.alpha < 1 { self.googleImage.alpha = 1 NSUserDefaults.standardUserDefaults().setObject(true, forKey: "Google_filtered") } else { self.googleImage.alpha = 0.15 NSUserDefaults.standardUserDefaults().setObject(false, forKey: "Google_filtered") } }) dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } func changeStateOfApple() { dispatch_async(dispatch_get_main_queue() , { if self.appleImage.alpha < 1 { self.appleImage.alpha = 1 NSUserDefaults.standardUserDefaults().setObject(true, forKey: "Apple_filtered") } else { self.appleImage.alpha = 0.15 NSUserDefaults.standardUserDefaults().setObject(false, forKey: "Apple_filtered") } }) dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } override func viewDidLoad() { super.viewDidLoad() if ( NSUserDefaults.standardUserDefaults().objectForKey("Agenda Master_filtered") as! Bool ) == true { self.agendaMasterImage.alpha = 1 } else { self.agendaMasterImage.alpha = 0.15 } if ( NSUserDefaults.standardUserDefaults().objectForKey("Google_filtered") as! Bool ) == true { self.googleImage.alpha = 1 } else { self.googleImage.alpha = 0.15 } if ( NSUserDefaults.standardUserDefaults().objectForKey("Apple_filtered") as! Bool ) == true { self.appleImage.alpha = 1 } else { self.appleImage.alpha = 0.15 } let agendaMasterImageTap = UITapGestureRecognizer(target: self, action: #selector(self.changeStateOfAgendaMaster)) agendaMasterImage.addGestureRecognizer(agendaMasterImageTap) let googleImageTap = UITapGestureRecognizer(target: self, action: #selector(self.changeStateOfGoogle)) googleImage.addGestureRecognizer(googleImageTap) let appleImageTap = UITapGestureRecognizer(target: self, action: #selector(self.changeStateOfApple)) appleImage.addGestureRecognizer(appleImageTap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
9e48acd8b195f6045dffd54944588544
32.128049
157
0.565433
5.411355
false
false
false
false
stevenygd/Trace
Trace/GameViewController.swift
1
4176
// // GameViewController.swift // Trace // // Created by Grendel Yang on 11/7/15. // Copyright (c) 2015 Grendel Yang. All rights reserved. // import UIKit import SpriteKit import AVFoundation extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { let sceneData = try! NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe) let 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 { var backgroundMusicPlayer:AVAudioPlayer = AVAudioPlayer() let pan : UIPanGestureRecognizer = UIPanGestureRecognizer(); var scene : GameScene? = GameScene(fileNamed:"GameScene"); override func viewDidLoad() { super.viewDidLoad() if (self.scene != nil) { // 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) // set up the pan gesture recognizer // pan.addTarget(self, action: "panOnView:") // self.view.addGestureRecognizer(pan); } } // func panOnView(sender:UIPanGestureRecognizer){ // switch sender.state { // case UIGestureRecognizerState.Possible : // print("possible"); // case UIGestureRecognizerState.Began : // print("began"); // scene!.gameStart(); // break; // case UIGestureRecognizerState.Changed: // print("changed %@", sender.locationInView(self.view)); // break; // case UIGestureRecognizerState.Ended: // print("ended"); // // end game // scene!.gameOver(); // break; // // case UIGestureRecognizerState.Cancelled: // print("canceled"); // // end game // scene!.gameOver(); // break; // case UIGestureRecognizerState.Failed: // print("failed"); // // end game // scene!.gameOver(); // break; // case UIGestureRecognizerState.Recognized: // print("recognized"); // break; // } // } override func viewWillLayoutSubviews() { let bgmURL:NSURL = NSBundle.mainBundle().URLForResource("bgmusic", withExtension: "mp3")! backgroundMusicPlayer = try! AVAudioPlayer(contentsOfURL: bgmURL) backgroundMusicPlayer.numberOfLoops = -1 backgroundMusicPlayer.prepareToPlay() backgroundMusicPlayer.play() let skView:SKView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true let scene:SKScene = GameScene(size: skView.bounds.size) scene.scaleMode = SKSceneScaleMode.AspectFill skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
apache-2.0
63fd48a069b32897e4e505c70f043b61
30.636364
97
0.585249
5.416342
false
false
false
false
gregomni/swift
SwiftCompilerSources/Sources/SIL/Argument.swift
2
2459
//===--- Argument.swift - Defines the Argument classes --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 Basic import SILBridging /// A basic block argument. /// /// Maps to both, SILPhiArgument and SILFunctionArgument. public class Argument : Value, Equatable { public var definingInstruction: Instruction? { nil } public var block: BasicBlock { return SILArgument_getParent(bridged).block } var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) } public var index: Int { return block.arguments.firstIndex(of: self)! } public static func ==(lhs: Argument, rhs: Argument) -> Bool { lhs === rhs } } final public class FunctionArgument : Argument { public var isExclusiveIndirectParameter: Bool { SILArgument_isExclusiveIndirectParameter(bridged) != 0 } } final public class BlockArgument : Argument { public var isPhiArgument: Bool { block.predecessors.allSatisfy { let term = $0.terminator return term is BranchInst || term is CondBranchInst } } public var incomingPhiOperands: LazyMapSequence<PredecessorList, Operand> { assert(isPhiArgument) let idx = index return block.predecessors.lazy.map { switch $0.terminator { case let br as BranchInst: return br.operands[idx] case let condBr as CondBranchInst: if condBr.trueBlock == self.block { assert(condBr.falseBlock != self.block) return condBr.trueOperands[idx] } else { assert(condBr.falseBlock == self.block) return condBr.falseOperands[idx] } default: fatalError("wrong terminator for phi-argument") } } } public var incomingPhiValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> { incomingPhiOperands.lazy.map { $0.value } } } // Bridging utilities extension BridgedArgument { var argument: Argument { obj.getAs(Argument.self) } var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) } }
apache-2.0
26c81ff5d95ee470e10da0119acd0e61
28.987805
99
0.664091
4.45471
false
false
false
false
MrPudin/Skeem
IOS/Prevoir/TaskEditVC.swift
1
15316
// // TaskEditVC.swift // Skeem // // Created by Zhu Zhan Yan on 2/11/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit /* * public enum TaskType:Int * - Defines task type */ public enum TaskType:Int { case oneshot = 0 case repetitive = 1 } class TaskEditVC: UIViewController,UITextViewDelegate,UITextFieldDelegate { //Properties //UI Elements @IBOutlet weak var bbtn_finish: UIBarButtonItem! @IBOutlet weak var segctl_type: UISegmentedControl! @IBOutlet weak var textfield_name: UITextField! @IBOutlet weak var textview_descript: UITextView! @IBOutlet weak var datepick_deadline: UIDatePicker! @IBOutlet weak var datepick_duration: UIDatePicker! @IBOutlet weak var switch_drsn_affinity: UISwitch! @IBOutlet weak var datepick_drsn_affinity: UIDatePicker! @IBOutlet weak var cnstrt_label_deadline: NSLayoutConstraint! @IBOutlet weak var cnstrt_datepick_deadline: NSLayoutConstraint! @IBOutlet weak var cnstrt_datepick_drsn_affinity: NSLayoutConstraint! //Link var DBC:SKMDataController! //Data var task_name:String! var task_subject:String! var task_descript:String! var task_deadline:Date! var task_duration:Int! var task_drsn_affinity:Int! var rpttask_repeat_loop:[TimeInterval]! var rpttask_deadline:Date? //Status var edit:Bool! var repeat_data:Bool! var task_type:TaskType! //Functions //Setup /* * public func loadAddTask() * - Setup View Controller for add task */ public func loadAddTask() { //Update Status self.edit = false self.repeat_data = false self.task_type = TaskType.oneshot self.resetData() self.updateUI() } /* * public loadEditTask(task:SKMTask) * - Setup View Controller for editing SKMTask specifed by task * [Arguments] * task - The task to edit */ public func loadEditTask(task:SKMTask) { //Update Status self.edit = true self.repeat_data = false if let rpttask = (task as? SKMRepeatTask) { //Task is repetitive self.task_type = TaskType.repetitive //Load Data self.task_name = task.name self.task_subject = task.subject self.task_deadline = (task.deadline as Date) self.task_duration = task.duration self.task_drsn_affinity = task.duration_affinity self.rpttask_repeat_loop = rpttask.repeat_loop self.rpttask_deadline = rpttask.repeat_deadline as Date? } else { //Task is oneshot self.task_type = TaskType.oneshot self.task_name = task.name self.task_subject = task.subject self.task_deadline = (task.deadline as Date) self.task_duration = task.duration self.task_drsn_affinity = task.duration_affinity } //Update UI self.updateUI() } //Data /* * public func resetData() * - Reset Data to default values */ public func resetData() { self.task_name = "" self.task_subject = "" self.task_descript = "" self.task_deadline = Date() self.task_duration = 0 self.task_drsn_affinity = 0 self.rpttask_repeat_loop = Array<TimeInterval>() self.rpttask_deadline = Date() //Init to current date } /* * public func vaildateData() -> Bool * - Vaildates the current data * [Reuturn] * Bool - Returns true if data is vaild, false otherwise. */ public func vaildateData() -> Bool { let date = Date() //Init to current date //Vaidate Data if self.task_name.characters.count <= 0 { return false } //Subject //if self.task_subject.characters.count <= 0 //{ // return false //} //Task Descirption: No vaildation needed. if self.task_deadline.compare(date) != ComparisonResult.orderedDescending && self.task_type == TaskType.oneshot { //task_deadline >= date return false } if self.task_duration <= 0 { return false } if self.switch_drsn_affinity.isOn == true && self.task_drsn_affinity <= 0 { return false } return true } /* * public func commitData() * - Commit data to datebase * [Return] * Bool - Returns true if database commit is succesful, false otherwise. */ public func commitData() -> Bool { if self.vaildateData() == false { abort() } var rst:Bool! if self.task_type == TaskType.oneshot { if self.edit == false { rst = self.DBC.createOneshotTask(name: self.task_name, subject: self.task_subject, description: self.task_descript, deadline: self.task_deadline as NSDate , duration:self.task_duration , duration_affinity: self.task_drsn_affinity) } else { rst = self.DBC.updateOneshotTask(name: self.task_name, subject: self.task_subject, description: self.task_descript, deadline: self.task_deadline as NSDate , duration:self.task_duration , duration_affinity: self.task_drsn_affinity) } } else if self.task_type == TaskType.repetitive && self.repeat_data == true { if self.edit == false { rst = self.DBC.createRepeativeTask(name: self.task_name, subject: self.task_subject, description: self.task_descript, repeat_loop: self.rpttask_repeat_loop, duration: self.task_duration, duration_affinity: self.task_drsn_affinity, deadline: (self.rpttask_deadline as NSDate?)!) } else { rst = self.DBC.updateRepeativeTask(name: self.task_name, subject: self.task_subject, description: self.task_descript, repeat_loop: self.rpttask_repeat_loop, duration: self.task_duration, duration_affinity: self.task_drsn_affinity, deadline: self.rpttask_deadline as NSDate?) } } else { abort() } return rst } //UI /* * public func updateUI() * - Update UI to current data */ public func updateUI() { if self.task_type == TaskType.oneshot { self.segctl_type.selectedSegmentIndex = TaskType.oneshot.rawValue self.textfield_name.text = self.task_name self.textview_descript.text = self.task_descript self.datepick_deadline.date = self.task_deadline self.datepick_duration.countDownDuration = TimeInterval(self.task_duration) self.datepick_drsn_affinity.countDownDuration = TimeInterval(self.task_drsn_affinity) //Show Deadline controls self.cnstrt_label_deadline.constant = 21.0 self.cnstrt_datepick_deadline.constant = 200.0 //Finish Button Label self.bbtn_finish.title = "Done" } else if self.task_type == TaskType.repetitive { self.segctl_type.selectedSegmentIndex = TaskType.repetitive.rawValue self.textfield_name.text = self.task_name self.textview_descript.text = self.task_descript self.datepick_duration.countDownDuration = TimeInterval(self.task_duration) self.datepick_drsn_affinity.countDownDuration = TimeInterval(self.task_drsn_affinity) //Hide Deadline controls self.cnstrt_label_deadline.constant = 0.0 self.cnstrt_datepick_deadline.constant = 0.0 //Finish Bar Button Label if self.repeat_data == false && self.task_type == TaskType.repetitive { self.bbtn_finish.title = "Next" } else { self.bbtn_finish.title = "Done" } } else { abort() } } //Events override func viewDidLoad() { super.viewDidLoad() self.task_type = TaskType.oneshot self.edit = false self.repeat_data = false //Init Task let appdelegate = (UIApplication.shared.delegate as! AppDelegate) self.DBC = appdelegate.DBC //Reset UI self.resetData() self.updateUI() //Update UI self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))) //Dismiss Keyboard On Outside Tap } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //Reset UI self.resetData() self.updateUI() } //UI Events @IBAction func sgectl_type_action(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == VoidDurationType.oneshot.rawValue { self.task_type = TaskType.oneshot self.updateUI() } else if sender.selectedSegmentIndex == VoidDurationType.repetitive.rawValue { self.task_type = TaskType.repetitive self.updateUI() } else { abort() } } @IBAction func textfield_name_action(_ sender: UITextField) { if let txt = sender.text { self.task_name = txt } } @IBAction func datepick_deadline_action(_ sender: UIDatePicker) { self.task_deadline = sender.date } @IBAction func datepick_duration(_ sender: UIDatePicker) { self.task_duration = Int(round(sender.countDownDuration)) } @IBAction func switch_drsn_affinity_action(_ sender: UISwitch) { if sender.isOn == true { self.cnstrt_datepick_drsn_affinity.constant = 200.0 } else { self.cnstrt_datepick_drsn_affinity.constant = 0.0 } } @IBAction func datepick_drsn_affinity_action(_ sender: UIDatePicker) { self.task_drsn_affinity = Int(round(sender.countDownDuration)) } @IBAction func bbtn_finish_action(_ sender: UIBarButtonItem) { if self.vaildateData() == true { if self.task_type == TaskType.oneshot { //Commit Data let rst = self.commitData() if rst == false { //Warn user of database error let artctl = UIAlertController(title: "Database Error", message: "Database Failed to save. \n Check if another void duration with the same name already exists.", preferredStyle: UIAlertControllerStyle.alert) artctl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{(artact:UIAlertAction) in self.dismiss(animated: true, completion: nil) })) self.present(artctl, animated: true, completion: nil) } else { //Segue to ListVC self.performSegue(withIdentifier: "uisge.task.list.unwind", sender: self) } } else if self.task_type == TaskType.repetitive { if self.repeat_data == false { //Segue to RepeatEditVC self.performSegue(withIdentifier: "uisge.rpt.edit", sender: self) } else { //Commit Data let rst = self.commitData() if rst == false { //Warn user of database error let artctl = UIAlertController(title: "Database Error", message: "Database Failed to save. \n Check if another void duration with the same name already exists.", preferredStyle: UIAlertControllerStyle.alert) artctl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{(artact:UIAlertAction) in self.dismiss(animated: true, completion: nil) })) self.present(artctl, animated: true, completion: nil) } else { //Segue to ListVC self.performSegue(withIdentifier: "uisge.task.list.unwind", sender: self) } } } else { abort() } } else { //Warn user of invaild data. let alertctl = UIAlertController(title: "Invaild Data", message: "Please correct invaild data", preferredStyle: UIAlertControllerStyle.alert) alertctl.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: {(alertact:UIAlertAction) in self.dismiss(animated: true, completion: nil)})) self.present(alertctl, animated: true, completion: nil) } } //UITextViewDelegate Methods func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } return true } //UITextFieldDelegate Methods func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } //Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let sge_idf = segue.identifier { switch sge_idf { case "uisge.rpt.edit": let rpteditvc = (segue.destination as! RepeatEditVC) let _ = rpteditvc.view //Force Load View //Push Data Into View Controller rpteditvc.repeat_deadline = self.rpttask_deadline rpteditvc.repeat_time = self.task_deadline rpteditvc.computeDay(rpt_lp: self.rpttask_repeat_loop) rpteditvc.source_vc = self rpteditvc.updateUI() case "uisge.task.list.unwind": break default: abort() } } else { abort() } } @IBAction func unwind_taskEditVC(sge:UIStoryboardSegue) { if let sge_idf = sge.identifier { switch sge_idf { case "uisge.task.edit.unwind": let rpteditvc = (sge.source as! RepeatEditVC) self.rpttask_deadline = rpteditvc.repeat_deadline self.task_deadline = rpteditvc.repeat_time self.rpttask_repeat_loop = rpteditvc.computeTimeInterval() //Update UI self.repeat_data = true self.updateUI() default: abort() } } else { abort() } } }
mit
27d6ccab4ddf9186eeb47c89ec2dfb6b
30.447639
293
0.562129
4.405926
false
false
false
false
CallMeDaKing/DouYuAPP
DouYuProject/DouYuProject/Classes/Home/View/CommendGameView.swift
1
2301
// // CommendGameView.swift // DouYuProject // // Created by li king on 2017/11/24. // Copyright © 2017年 li king. All rights reserved. // import UIKit private let gameCellID = "gameCellID" private let kEdgeInsetMargin :CGFloat = 10 class CommendGameView: UIView { //定义数据的属性 var groups :[AnchorGroup]?{ didSet{ //由于数组中的热门和颜值 两项是没有的,我们需要在使用前将数组中的前两组数据删除掉 groups?.removeFirst() groups?.removeFirst() //添加更多组元素 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups?.append(moreGroup) //2 .刷新表格 collectionView.reloadData() } } //控件属性 @IBOutlet weak var collectionView: UICollectionView! //系统回调 override func awakeFromNib() { super.awakeFromNib() //注册cell // collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: gameCellID) //注册nib cell collectionView.register(UINib(nibName: "recommendGameCell", bundle: nil), forCellWithReuseIdentifier: gameCellID) //给collectionVewi 添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } //MARK -- 提供一个快速创建的类方法 extension CommendGameView { class func recommendGameView() -> CommendGameView{ return Bundle.main.loadNibNamed("CommendGameView", owner: nil, options: nil)?.first as! CommendGameView } } // MARK -- 遵守UIcolectionViewDataSource 的数据协议 extension CommendGameView :UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: gameCellID, for: indexPath) as! recommendGameCell //取出group cell.baseGame = groups![indexPath.item] return cell } }
mit
7ddc9bb4dde26cb17ef0e40e504ce215
31.338462
124
0.663178
4.76644
false
false
false
false
hintoz/DTZFloatingActionButton
DTZFloatingActionButton/Classes/DTZFloatingActionButton.swift
1
12640
// // DTZFloatingActionButton.swift // DTZFloatingActionButton // // Created by hintoz on 02.02.17. // Copyright © 2017 Evgeny Dats. All rights reserved. // import UIKit public enum DTZFABAnimationType { case scale case none } open class DTZFloatingActionButton: UIView { // MARK: - Properties // Button size open var size: CGFloat = 56 { didSet { self.setNeedsDisplay() } } // Padding from buttom right of superview open var paddingX: CGFloat = 14 { didSet { self.setNeedsDisplay() } } open var paddingY: CGFloat = 14 { didSet { self.setNeedsDisplay() } } open var animationSpeed: Double = 0.1 open var buttonColor: UIColor = UIColor(red: 239 / 255, green: 72 / 255, blue: 54 / 255, alpha: 1) open var buttonImage: UIImage? = nil { didSet { self.setNeedsDisplay() } } open var plusColor: UIColor = UIColor.white open var animationType: DTZFABAnimationType = .scale // Shadow open var isAddShadow: Bool = false open var shadowCircleColor: UIColor = UIColor.black open var shadowCircleOpacity: Float = 0.5 open var shadowCircleOffSet: CGSize = CGSize(width: 0, height: 2) open var shadowCircleRadius: CGFloat = 1 // Set true if you use tableView etc open var isScrollView: Bool = false // Handler for touch up inside button open var handler: ((DTZFloatingActionButton) -> Void)? = nil // Button shape layer fileprivate var circleLayer: CAShapeLayer = CAShapeLayer() // Plus icon shape layer fileprivate var plusLayer: CAShapeLayer = CAShapeLayer() // Button image view fileprivate var buttonImageView: UIImageView = UIImageView() // If you created button from storyboard, set true fileprivate var isCustomFrame: Bool = false // MARK: - Initialize // Init with default property public init() { super.init(frame: CGRect(x: 0, y: 0, width: size, height: size)) backgroundColor = UIColor.clear setObserver() } // Init with custom size public init(size: CGFloat) { self.size = size super.init(frame: CGRect(x: 0, y: 0, width: size, height: size)) backgroundColor = UIColor.clear setObserver() } // Init with custom frame public override init(frame: CGRect) { super.init(frame: frame) size = min(frame.size.width, frame.size.height) backgroundColor = UIColor.clear isCustomFrame = true setObserver() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.clear isCustomFrame = true setObserver() } // MARK: - Method // Set size and frame open override func draw(_ rect: CGRect) { super.draw(rect) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale if isCustomFrame { size = min(frame.size.width, frame.size.height) } else { setRightButtomFrame() } setCircleLayer() if isAddShadow { setShadow() } guard buttonImage == nil else { setButtonImage() return } setPlusLayer() } // Button tapped open func tap() { switch animationType { case .scale: scaleAnimation() case .none: noneAnimation() } } fileprivate func setCircleLayer() { circleLayer.removeFromSuperlayer() circleLayer.frame = CGRect(x: 0, y: 0, width: size, height: size) circleLayer.backgroundColor = buttonColor.cgColor circleLayer.cornerRadius = size / 2 layer.zPosition = 1 layer.addSublayer(circleLayer) } fileprivate func setPlusLayer() { plusLayer.removeFromSuperlayer() plusLayer.frame = CGRect(x: 0, y: 0, width: size, height: size) plusLayer.lineCap = CAShapeLayerLineCap.round plusLayer.strokeColor = plusColor.cgColor plusLayer.lineWidth = 2.0 plusLayer.path = plusBezierPath().cgPath layer.addSublayer(plusLayer) } fileprivate func setButtonImage() { buttonImageView.removeFromSuperview() buttonImageView = UIImageView(image: buttonImage) buttonImageView.tintColor = plusColor buttonImageView.frame = CGRect(x: circleLayer.frame.origin.x + (size / 2 - buttonImageView.frame.size.width / 2), y: circleLayer.frame.origin.y + (size / 2 - buttonImageView.frame.size.height / 2), width: buttonImageView.frame.size.width, height: buttonImageView.frame.size.height ) addSubview(buttonImageView) } fileprivate func setRightButtomFrame(_ keyboardSize: CGFloat = 0) { guard let superview = superview else { return } if #available(iOS 11.0, *) { frame = CGRect(x: (superview.frame.size.width - size - superview.safeAreaInsets.right) - paddingX, y: (superview.frame.size.height - size - superview.safeAreaInsets.bottom) - paddingY, width: size, height: size ) } else { frame = CGRect(x: (superview.frame.size.width - size) - paddingX, y: (superview.frame.size.height - size) - paddingY, width: size, height: size ) } // frame.size.width += paddingX // frame.size.height += paddingY } fileprivate func plusBezierPath() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(x: size / 2, y: size / 3)) path.addLine(to: CGPoint(x: size / 2, y: size - size / 3)) path.move(to: CGPoint(x: size / 3, y: size / 2)) path.addLine(to: CGPoint(x: size - size / 3, y: size / 2)) return path } fileprivate func setShadow() { circleLayer.shadowColor = shadowCircleColor.cgColor circleLayer.shadowOpacity = shadowCircleOpacity circleLayer.shadowOffset = shadowCircleOffSet circleLayer.shadowRadius = shadowCircleRadius circleLayer.shadowPath = UIBezierPath(roundedRect: circleLayer.bounds, cornerRadius: size / 2).cgPath circleLayer.shouldRasterize = true circleLayer.rasterizationScale = UIScreen.main.scale } fileprivate func setObserver() { NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) tap() } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) handler?(self) } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if object as? UIView == superview && keyPath == "frame" { if isCustomFrame { size = min(frame.size.width, frame.size.height) } else { setRightButtomFrame() } } else if object as? UIScrollView == superview && keyPath == "contentOffset" { let scrollView = object as! UIScrollView frame.origin.x = ((self.superview!.bounds.size.width - size) - paddingX) + scrollView.contentOffset.x frame.origin.y = ((self.superview!.bounds.size.height - size) - paddingY) + scrollView.contentOffset.y } } open override func willMove(toSuperview newSuperview: UIView?) { superview?.removeObserver(self, forKeyPath: "frame") if isScrollView { if let superviews = self.getAllSuperviews() { for superview in superviews { if superview is UIScrollView { superview.removeObserver(self, forKeyPath: "contentOffset", context: nil) } } } } super.willMove(toSuperview: newSuperview) } open override func didMoveToSuperview() { super.didMoveToSuperview() superview?.addObserver(self, forKeyPath: "frame", options: [], context: nil) if isScrollView { if let superviews = self.getAllSuperviews() { for superview in superviews { if superview is UIScrollView { superview.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) } } } } } @objc internal func deviceOrientationDidChange(_ notification: Notification) { guard let keyboardSize: CGFloat = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size.height else { return } if isCustomFrame { size = min(frame.size.width, frame.size.height) } else { setRightButtomFrame(keyboardSize) } } @objc internal func keyboardWillShow(_ notification: Notification) { guard let keyboardSize: CGFloat = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size.height else { return } if isScrollView { return } if isCustomFrame { size = min(frame.size.width, frame.size.height) } else { setRightButtomFrame(keyboardSize) } UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions(), animations: { self.frame = CGRect(x: UIScreen.main.bounds.width - self.size - self.paddingX, y: UIScreen.main.bounds.height - self.size - keyboardSize - self.paddingY, width: self.size, height: self.size ) }, completion: nil) } @objc internal func keyboardWillHide(_ notification: Notification) { if isScrollView { return } UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions(), animations: { if self.isCustomFrame { self.size = min(self.frame.size.width, self.frame.size.height) } else { self.setRightButtomFrame() } }, completion: nil) } } // Animation extension DTZFloatingActionButton { fileprivate func scaleAnimation() { UIView.animate(withDuration: animationSpeed, animations: { self.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1) }) { (bool) in UIView.animate(withDuration: self.animationSpeed, animations: { self.layer.transform = CATransform3DMakeScale(1, 1, 1) }) } } fileprivate func noneAnimation() { } } // extension UIView { fileprivate func getAllSuperviews() -> [UIView]? { guard superview != nil else { return nil } var superviews: [UIView] = [] superviews.append(superview!) if let allSuperviews = superview?.getAllSuperviews() { superviews.append(contentsOf: allSuperviews) } return superviews } }
mit
1499a9f87bc0c712fd5c4f1d54a2cc79
33.252033
167
0.591661
5.027446
false
false
false
false
KiloKilo/WorldMatrix
WorldMatrix/Matrix.swift
1
2245
// // Matrix.swift // WorldMatrix // // Created by Alexandre Joly on 14/10/15. // Copyright © 2015 KiloKilo GmbH. All rights reserved. // public struct Matrix<T> { let rows: Int, columns: Int var grid: [T] public init(rows: Int, columns: Int, repeatedValue: T) { self.rows = rows self.columns = columns grid = Array<T>(repeating: repeatedValue, count: rows * columns) } public init(columns:Int, array:Array<T>) { grid = array self.columns = columns self.rows = grid.count / columns assert(rows * columns == grid.count, "Array is not complete. Array should have \(columns) * x elements") } public func indexIsValidForRow(_ row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } public subscript(row: Int, column: Int) -> T { get { assert(indexIsValidForRow(row, column: column), "Index out of range") return grid[(row * columns) + column] } set { assert(indexIsValidForRow(row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } } public func last() -> T? { return grid.last } } extension Matrix: Collection { public typealias Index = Int public var startIndex: Index { get { return 0 } } public var endIndex: Index { get { return grid.count } } /// Returns the position immediately after the given index. /// /// - Parameter 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 } public subscript (_i: Index) -> (row:Int, column:Int, element:T) { get { let rowColumn = getRowColumnForIndex(_i) return (rowColumn.row, rowColumn.column, grid[_i]) } } fileprivate func getRowColumnForIndex(_ index: Index) -> (row:Int, column:Int) { let row:Int = index / columns let column:Int = index % columns return (row, column) } }
mit
c323abc11356bf98e46ad8f1e4478fdf
24.5
112
0.564617
4.065217
false
false
false
false
lyle-luan/firefox-ios
Providers/Panels.swift
2
7966
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let path = documentsFolder.stringByAppendingPathComponent("test.sqlite") /* * This protocol is used for instantiating new tab panels. It ensures... */ protocol ToolbarViewProtocol { var profile: Profile! { get set } } /* * This struct holds basic data about the tabs shown in our UI. */ struct ToolbarItem { let title: String // We use title all over the place as a unique identifier. Be careful not to have duplicates. let imageName: String let generator: (profile: Profile) -> UIViewController; var enabled : Bool; } /* * A list of tabs to show. Order is important here. The order (and enabled state) listed here represent the defaults for the app. * This will be rearranged on startup to make the order stored/enabled-states set in NSUserDefaults. */ private var Controllers: Protector<[ToolbarItem]> = Protector(name: "Controllers", item: [ ToolbarItem(title: "Tabs", imageName: "tabs", generator: { (profile: Profile) -> UIViewController in let controller = TabsViewController(nibName: nil, bundle: nil) controller.profile = profile return controller }, enabled: true), ToolbarItem(title: "Bookmarks", imageName: "bookmarks", generator: { (profile: Profile) -> UIViewController in let controller = BookmarksViewController(nibName: nil, bundle: nil) controller.profile = profile return controller }, enabled: true), ToolbarItem(title: "History", imageName: "history", generator: { (profile: Profile) -> UIViewController in var controller = HistoryViewController(nibName: nil, bundle: nil) controller.profile = profile return controller }, enabled: true), ToolbarItem(title: "Reader", imageName: "reader", generator: { (profile: Profile) -> UIViewController in let controller = SiteTableViewController(nibName: nil, bundle: nil) controller.profile = profile return controller }, enabled: true), ToolbarItem(title: "Settings", imageName: "settings", generator: { (profile: Profile) -> UIViewController in let controller = SettingsViewController(nibName: "SettingsViewController", bundle: nil) controller.profile = profile return controller }, enabled: true), ]) private var setup: Bool = false // True if we've already loaded the order/enabled prefs once and the Controllers array has been updated let PanelsNotificationName = "PANELS_NOTIFICATION_NAME" // A constant to use for Notifications of changes to the panel dataset // A helper function for finding the index of a ToolbarItem with a particular title in Controllers. This isn't going to be fast, but assuming // controllers isn't ever huge, it shouldn't matter. private func indexOf(items: [ToolbarItem], val: String) -> Int { var i = 0 for controller in items { if (controller.title == val) { return i } i++ } return -1 } /* * The main object people wanting to interact with panels should use. */ class Panels : SequenceType { private var profile: Profile private var PanelsOrderKey : String = "PANELS_ORDER" private var PanelsEnabledKey : String = "PANELS_ENABLED" init(profile : Profile) { self.profile = profile; // Prefs are stored in a static cache, so we only want to do this setup // the first time a Panels object is created if (!setup) { let prefs = profile.prefs if var enabled = prefs.arrayForKey(PanelsEnabledKey) as? [Bool] { if var order = prefs.stringArrayForKey(PanelsOrderKey) as? [String] { // Now we loop through the panels and sort them based on the order stored // in PanelsOrderKey. We also disable them based on PanelsEnabledKey. Controllers.withWriteLock { protected -> Void in for (index:Int, title:String) in enumerate(order) { var i = indexOf(protected, title) if (i >= 0) { var a = protected.removeAtIndex(i) a.enabled = enabled[index] protected.insert(a, atIndex: index) } } } } } setup = true; } } /* * Returns a list of enabled items. This list isn't live. If you're using it, * you should also register for notifications of changes so that you can obtain a more * up-to-date dataset. */ var enabledItems : [ToolbarItem] { var res : [ToolbarItem] = [] Controllers.withReadLock { (protected) -> Void in for controller in protected { if (controller.enabled) { res.append(controller) } } } return res } /* * Moves an item in the list.. */ func moveItem(from: Int, to: Int) { if (from == to) { return } return Controllers.withWriteLock { protected -> Void in let a = protected.removeAtIndex(from); protected.insert(a, atIndex: to) self.saveConfig() { self.notifyChange() } } } private func notifyChange() { let notif = NSNotification(name: PanelsNotificationName, object: nil); NSNotificationCenter.defaultCenter().postNotification(notif) } /* * Enables or disables the panel at an index * TODO: This would be nicer if just calling panel.enabled = X; did the same thing */ func enablePanelAt(enabled: Bool, position: Int) { return Controllers.withWriteLock { protected -> Void in if (protected[position].enabled != enabled) { protected[position].enabled = enabled } self.saveConfig() { self.notifyChange() } } } /* * Saves an updated order and enabled dataset to UserDefaults */ private func saveConfig(callback: () -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { var order = [String]() var enabled = [Bool]() Controllers.withReadLock { protected -> Void in for controller in protected { order.append(controller.title) enabled.append(controller.enabled) } } let prefs = self.profile.prefs prefs.setObject(order, forKey: self.PanelsOrderKey) prefs.setObject(enabled, forKey: self.PanelsEnabledKey) dispatch_async(dispatch_get_main_queue()) { callback(); } } } var count: Int { var count: Int = 0 Controllers.withReadLock { protected in count = protected.count } return count } subscript(index: Int) -> ToolbarItem? { var item : ToolbarItem? Controllers.withReadLock { protected in item = protected[index] } return item; } func generate() -> GeneratorOf<ToolbarItem> { var nextIndex = 0; return GeneratorOf<ToolbarItem>() { var item: ToolbarItem? Controllers.withReadLock { protected in if (nextIndex >= protected.count) { item = nil } item = protected[nextIndex++] } return item } } }
mpl-2.0
ab95679955799cf7608ca18ef4493f28
35.87963
141
0.600301
4.875153
false
false
false
false
delba/SwiftyOAuth
Source/Token.swift
1
2883
// // Token.swift // // Copyright (c) 2016-2019 Damien (http://delba.io) // // 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 public struct Token { /// The access token. public var accessToken: String { return dictionary["access_token"] as! String } /// The refresh token. public var refreshToken: String? { return dictionary["refresh_token"] as? String } /// The remaining lifetime on the access token. public var expiresIn: TimeInterval? { return dictionary["expires_in"] as? TimeInterval } /// A boolean value indicating whether the token is expired. public var isExpired: Bool { guard let expiresIn = expiresIn else { return false } return Date.timeIntervalSinceReferenceDate > createdAt + expiresIn } /// A boolean value indicating whether the token is valid. public var isValid: Bool { return !isExpired } fileprivate var createdAt: TimeInterval { return dictionary["created_at"] as! TimeInterval } /// The token type. public var tokenType: TokenType? { return TokenType(dictionary["token_type"]) } /// The scopes. public var scopes: [String]? { return scope?.components(separatedBy: " ") } /// The scope. fileprivate var scope: String? { return dictionary["scope"] as? String } /// The full response dictionary. public let dictionary: [String: Any] public init?(dictionary: [String: Any]) { guard dictionary["access_token"] as? String != nil else { return nil } var dictionary = dictionary if dictionary["created_at"] == nil { dictionary["created_at"] = Date.timeIntervalSinceReferenceDate } self.dictionary = dictionary } }
mit
e4d7278c741a577efac9eddd4ab997df
30.336957
81
0.67187
4.773179
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/CtvCellWidgetSetting.swift
1
3221
// // CtvCellWidgetSetting.swift // Liplis // //ウィジェットメニュー画面 要素 ウィジェット設定 // //アップデート履歴 // 2015/05/05 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/05. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class CtvCellWidgetSetting : UITableViewCell { ///============================= ///カスタムセル要素 internal var parView : ViewWidgetMenu! internal var widget : LiplisWidget! ///============================= ///カスタムセル要素 internal var lblTitle = UILabel(); internal var btnRun = UIButton(); ///============================= ///レイアウト情報 internal var viewWidth : CGFloat! = 0 //============================================================ // //初期化処理 // //============================================================ internal override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.lblTitle = UILabel(frame: CGRectMake(10, 23, 300, 30)); self.lblTitle.text = "ウィジェットの基本設定画面を開きます。"; self.lblTitle.font = UIFont.systemFontOfSize(15) self.lblTitle.numberOfLines = 2 self.addSubview(self.lblTitle); //ボタン self.btnRun = UIButton() self.btnRun.titleLabel?.font = UIFont.systemFontOfSize(16) self.btnRun.frame = CGRectMake(0,5,40,48) self.btnRun.layer.masksToBounds = true self.btnRun.setTitle("設定画面", forState: UIControlState.Normal) self.btnRun.addTarget(self, action: "onClick:", forControlEvents: .TouchDown) self.btnRun.layer.cornerRadius = 3.0 self.btnRun.backgroundColor = UIColor.hexStr("DF7401", alpha: 255) self.addSubview(self.btnRun) } /* ビューを設定する */ internal func setView(parView : ViewWidgetMenu, widget : LiplisWidget) { self.parView = parView self.widget = widget } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* 要素の位置を調整する */ internal func setSize(viewWidth : CGFloat) { self.viewWidth = viewWidth let locationX : CGFloat = CGFloat(viewWidth - viewWidth/4 - 5) self.btnRun.frame = CGRectMake(locationX, 5,viewWidth/4,50) self.lblTitle.frame = CGRectMake(10, 5,viewWidth * 3/4 - 20,50) } //============================================================ // //イベントハンドラ // //============================================================ /* スイッチ選択 */ internal func onClick(sender: UIButton) { let modalView : ViewWidgetSetting = ViewWidgetSetting(widget: widget) modalView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical self.parView.presentViewController(modalView, animated: true, completion: nil) } }
mit
f92e63cdac5ddc68e3cdedac80480192
28.287129
86
0.549543
4.316788
false
false
false
false